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 關(guān)鍵字在conditional type

主要要看下infered type對(duì)于協(xié)變(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容