typescript 函数重载和一些小点

原文链接: 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[]>;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章