62 - Type Lookup
type LookUp<U, T extends string> = {
[K in T]: U extends { type: T } ? U : never
}[T]
Could you please explain what {type: T} does, thank you? I don't understand any of this at all.
Could you please explain what
{type: T}does, thank you? I don't understand any of this at all.
{type: T} here is to make a match. U extends {type: T} will be evaluated distributively, say, (Dog extends {type: 'dog'} ? Dog : never) | (Cat extends {type: 'dog'} ? Cat : never). Thus only one will come back from the final union. However, the outer mapping is actually redundant, see #149 for a simpler solution.
@ashi009 Thank you!
anybody can tell me why this doesn't work.
type LookUp<U extends {type: any}, T> = U['type'] extends T ? U : never
Why is it not just:
type LookUp<U, T> = U extends {type: T} ? U : never;
It is simpler and still working.
anybody can tell me why this doesn't work.
type LookUp<U extends {type: any}, T> = U['type'] extends T ? U : never
I believe it's because conditional types are only distributive when they have the form "T extends ..." (for any type parameter T); a more complex expression left of "extends" does not trigger distributivity.
One benefit of this design is that you can avoid distributivity if you need to by wrapping both sides in an array, as described in the new handbook.
It is rather subtle though; I'm curious if there is any other motivation behind this design choice.
Why is this recommended compared to the simpler solution:
type LookUp<U, T extends string> = U extends { type: T } ? U : never
anybody can tell me why this doesn't work.
type LookUp<U extends {type: any}, T> = U['type'] extends T ? U : never
May you need write as the follow to triggle distributive condition type:
type LookUp<U extends { type: string }, T> = U extends U
? U["type"] extends T
? U
: never
: never;
[K in T] How to understand it ,could somebody tell me Why need it
type LookUp<U, T extends string> = {
[K in T]: U extends { type: K } ? U : never
}[T]
type LookUp<U extends {type:string,[key:string]:any}, T extends U['type']> =U extends {type:T}?U:never
U['type']
U['type']:The string type is not a literal type
A more universal solution that makes a lookup not only within the 'type' property:
type LookUp<U, T> = U extends infer K ? T extends K[keyof K] ? K : never : never;
- U extends infer K -- same as 'iterate through union U; K is 'current' member'
- T extends K[keyof K] -- does T belongs to the values of the current type? If so, return it, otherwise return 'never'
type LookUp<U, T extends string> = U extends {type:T} ? U : never