美文网首页
Conditional Types

Conditional Types

作者: bestCindy | 来源:发表于2022-06-18 13:49 被阅读0次

    A conditional type is a type which selects one of two possible types

    for example:

    type SomeType = T extends U ? X : Y
    

    that means if some type T is assignable to type U then choose type X otherwise choose type Y

    and the SomeType is X or Y which is a union of type X and type Y

    SomeType = X | Y
    

    now let's take a look at Exclude

    this is the type definition

    type Exclude<T, U> = T extends U ? never : T
    

    never is to describe some type that never happens like that doesn't exist

    what Exclude does is it takes two union types T and U and in the union type T excludes all the elements of type U

    for example

    type ResultType = Exclude<'a' | 'b' | 'c', 'a' | 'b'>
    // type ResultType = 'c'
    

    for each element in the union of type T on the left side of the expression, typescript compares each of these elements to the whole type U on the right side of expression

    it goes like this

    'a' extends 'a' | 'b' ? never : 'a'  => never
    'b' extends 'a' | 'b' ? never : 'b'  => never
    'c' extends 'a' | 'b' ? never : 'c'  => 'c'
    

    for another example

    type MyType<T> = T extends string | number ? T : never;
    type MyResult = MyType<string | number | boolean>
    

    the result is

    type MyResult = string | number
    

    if we do some change

    type MyType<T> = (() => T) extends () => string | number ? T : never;
    

    the result is

    type MyType = never;
    

    because the union type string | number | boolean is not assignable to type string | number

    we compare the whole type T against type string | number

    and we will get the same result if we wrap the type into a Tuple

    also we can use conditional type to infer some type or a part of that type

    for example

    type InferSomething2<T> = T extends { a: infer A; b: infer B } ? A & B : any;
    type Inferred2 = InferSomething2<{
      a: { someAProp: 1 };
      b: { someBProp: 'B' };
    }>
    

    the result is

    type Inferred2 = { someAProp: 1; } & { someBProp: 'B' }
    

    in TypeScript we have a utility type called ReturnType and this type returns the type of the return value of a function given some function definition

    type MyFuncReturn = ReturnType<() => true>
    type MyFuncReturn = true
    

    and the definition of ReturnType is

    type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
    

    相关文章

      网友评论

          本文标题:Conditional Types

          本文链接:https://www.haomeiwen.com/subject/mhgfvrtx.html