const acceptDogCovariance = function (value: Covariant<Dog>) { ... }
acceptDogCovariance(newAnimal()) // Error, since Animal is a supertype of Dog acceptDogCovariance(newDog()) // Ok acceptDogCovariance(newGreyhound()) // Ok since Greyhound is a subtype of Dog
const acceptDogContravariance = function (value: Contravariance<Dog>) { ... } acceptDogContravariance(newAnimal()) // Ok, since Animal is a supertype of Dog acceptDogContravariance(newDog()) // Ok acceptDogContravariance(newGreyhound()) // Error since Greyhound is a subtype of Dog
typeToOnePartial<T, K extends keyof T> = { [P in K]?: T[P] } & { [P in keyof T as P extends K ? never : P]: T[P]; }; typeResToOnePartial = ToOnePartial<ObjectTypeA, "a" | "b">;
typeToOmit<T, K extendsstring | number | symbol> = { [P in keyof T as P extends K ? never : P]: T[P]; }; typeResToOmit = ToOmit<ObjectTypeA, "a">;
typeToPick<T, K extends keyof T> = { [P in K]: T[P] }; typeResToPick = ToOnePartial<ToPick<ObjectTypeA, "a" | "b">, "a">;
typePickByValueType<T extendsobject, Type> = { [K in keyof T as T[K] extendsType ? K : never]: T[K]; }; typeResPickByValueType = PickByValueType<ObjectTypeA, string>;
//联合类型 typeToExclude<T, K> = T extends K ? never : T; // 分布式类型 传入联合类型 T 会与 extends 后的类型逐个判断 typeResToExclude = ToExclude<UnionTypeA, "a">;
typeToExtract<T, K> = T extends K ? T : never; typeResToExtract = ToExtract<UnionTypeA, "a">;
typeNonNullType = null | undefined | "a" | "b"; typeToNonNullable<T> = T extendsnull | undefined ? never : T; typeResToNonNullable = ToNonNullable<NonNullType>;
functionfunctionA(this: number, name: string, age?: string) { // this 参数为特殊参数,可以被 infer 筛选掉 return { a: name, b: age }; } typeGetFunctionParamsType<T extends (...args: any) => any> = T extends ( ...args: infer Params ) => any ? Params : never; type functionAParamsType = GetFunctionParamsType<typeof functionA>;
typeGetFunctionReturnType<T extends (...args: any) => any> = T extends ( ...args: any ) => infer ReturnType ? ReturnType : never; type functionAReturnType = GetFunctionReturnType<typeof functionA>;
typeGetThisParamsType<T> = T extends ( this: infer ThisType, ...args: any ) => any ? ThisType : unknown; type functionAThisParamsType = GetThisParamsType<typeof functionA>;
typeOmitThisType<T> = unknownextendsGetThisParamsType<T> //通过 infer 筛选 this ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; typeResOmitThisType = OmitThisType<typeof functionA>;