原文鏈接: typescript 函數重載和一些小點
typescript handbook 裏面的一些有用類型
https://www.typescriptlang.org/docs/handbook/intro.html
需要使用特殊語法declare, 直接定義好像還不行
declare function log<T>(s: string, data: T): T;
如果需要實現, 那麼只能寫一個函數然後 if else了
declare function log(): void;
declare function log(s: string): string;
declare function log<T>(s: string, data: T): T;
interface Window {
version: string;
log: typeof log;
}
declare function log(): void;
declare function log(s: string): string;
declare function log<T>(s: string, data: T): T;
type Log = typeof log;
const _log: Log = (a: string, b: any) => {
};
// const a: void
const a = window.log();
// const b: string
const b = window.log('a');
// const c: 111
const c = window.log('abc', 111);
as const 主要是使得類型更加準確, 而且不能修改
// const a: {
// a: number;
// b: string;
// }
const a = { a: 1, b: '2' };
// const b: {
// readonly a: 1;
// readonly b: "2";
// }
const b = { a: 1, b: '2' } as const;
類型轉換 和 as類似
const c = <HTMLCanvasElement>document.getElementById('c');
元組, 如果用number[] 會報錯, 因爲長度會超過2
const args: [number, number] = [1, 2];
Math.atan2(...args);
展開, 感覺上可以寫的再深一點
type Flatten<T> = T extends Array<any> ? T[number] : T;
type s = Flatten<string[]>;