2023-03-10

covariance 和 contraviance

https://dmitripavlutin.com/typescript-covariance-contravariance/

The function type is contravariant by the parameter types, but covariant by the return types.

image.png

https://www.typescriptlang.org/play?#code/C4TwDgpgBAyglgcwHYEklQLxQBQBMCGw+AXFAN4QC2+cANqQM7ABOcSCANFGPgwwO4B7ZrkYs2CAL5QAlJgB8UAG6C4uANwAoUJCgAFZoLANMUHASKkAShADGw3AB4mrdlwCuSANZJB-JPJyGIoqaprhAPQRZgyIqOgAFvhK0AyQtnAAZnC2UDrQuIIQJr7AUELMXlCa9khMULHIaKTwTehYeIQk5FQ09A3ibty8Ag5irlJBimRQtQyCtBAAdLSCCJ1ES710XBb4Szx8FbhyklpzZYJIMO4ARpRwwMQGRiZYDXFokdHACXAmFS8DBqV3qVxu90eACZnoZjKYcBRqDthkcHJIpuRZqCFstVuttrQuIdRiIZJIgA

// This issue can be also tackled with generics like this

type SignInData = {email: string, password: string};
type SignIn = (data: SignInData) => void;
const signIn: SignIn = async ({email, password}) => { console.log(email, password) };

type Props<DATA extends Record<string, unknown>> = { onSubmit: (data: DATA) => void};

const onSubmit: Props<SignInData> = {onSubmit: signIn};

https://github.com/Microsoft/TypeScript/pull/21496
infer 关键字在conditional type

主要要看下infered type对于协变(union type)和逆变(intersection )的处理

The following example demonstrates how multiple candidates for the same type variable in co-variant positions causes a union type to be inferred:

type Foo<T> = T extends { a: infer U, b: infer U } ? U : never;
type T10 = Foo<{ a: string, b: string }>;  // string
type T11 = Foo<{ a: string, b: number }>;  // string | number

Likewise, multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred:

type Bar<T> = T extends { a: (x: infer U) => void, b: (x: infer U) => void } ? U : never;
type T20 = Bar<{ a: (x: string) => void, b: (x: string) => void }>;  // string
type T21 = Bar<{ a: (x: string) => void, b: (x: number) => void }>;  // string & number

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容