Typescript类型体操的总结

180 阅读1分钟

常用模式

优先使用Ts提供的类型操作函数和类型工具

1、keyof、typeof、extends、infer、[]、['length']

2、Awaited、Partial、Required、Readonly、Record、Pick、Omit、Exclude、Extract、NonNullable、Parameters、ConstructorParameters、ReturnType、InstanceType、ThisParameterType、OmitThisParameter、ThisType

活用字符字面量类型和其他字面量类型

常用模式:extends, keyof、循环、infer

函数参数和返回类型的逆变协变配合infer

如果一步无法实现可以拆分子函数(类比)

infer有大用处,特别是在可迭代环境和函数环境中

注意事项

合并类型

非对象类型用 | 取并集 对象类型用 & 取并集

type StringOrNumber = string | number; // 类似string + number ,string 或 number
type StringAndNumber = string & number; // never,二者不会有交集,所以 never

/** 对象或 interface 在用|或&时表现有点相反 */
interface ICat {
  eat(): void;
  meow(): void;
}

interface IDog {
  eat(): void;
  bark(): void;
}

declare function Pet(): ICat | IDog; 

const pet = new Pet();

pet.eat(); // 成功,只能用二者共有的方法
pet.meow(); // fails
pet.bark(); // fails

declare function AnotherPet(): ICat & IDog;

const anotherPet = new AnotherPet();

anotherPet.eat(); // 成功,类似取了并集
anotherPet.meow(); // succeeds
anotherPet.bark(); // succeeds

关于keyof any

// string | number | symbol
type S = keyof any;

参考:

1、hannq.github.io/todash/

2、github.com/millsp/ts-t…

3、github.com/type-challe…

4、github.com/BryanAdamss…

5、github.com/yoZerY/juej…

6、juejin.cn/post/699928…

8、juejin.cn/post/700056…

9、juejin.cn/post/699410…

10、hsiaofongw.notion.site/TypeScript-…

11、github.com/ascoders/we…

12、github.com/linwu-hi/co…

13、ghaiklor.github.io/type-challe…

14、tsch.lovchun.com/

15、yqwoshuai.github.io/note/ts-cha…

16、wangtunan.github.io/blog/typesc…