typescripttypescript-generics

What's the difference between <T extend any> and <T>?


I've seen some times <T extend any> in a any d.ts files. I don't know what's the difference between <T extend any> and <T>.

Because T extend any never giving restriction to T therefore I think there is no difference to <T> that allow anything could pass to the generics.


Solution

  • That is called Distributive Conditional Types

    example:

    type AllKeys<T> = T extends any ? keyof T : never;
    

    if we pass a union type AllKeys<A|B> then intutively we could expect this to transform into:

    // the following line is incorrect!
    AllKeys<A|B> = (A|B) extends any ? keyof (A|B) : never
    

    but instead it is transformed into:

    AllKeys<A|B> = (A extends any ? keyof A : never) | (B extends any ? keyof B : never) 
    AllKeys<A|B> = keyof A | keyof B //that is correct