covariance 和 contraviance
https://dmitripavlutin.com/typescript-covariance-contravariance/
image.pngThe function type is contravariant by the parameter types, but covariant by the return types.
// 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
网友评论