常用模式
优先使用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;
参考:
10、hsiaofongw.notion.site/TypeScript-…
13、ghaiklor.github.io/type-challe…