Recently I stumbled this code
type SmooshedObjectUnion<T> = {
[K in T extends infer P ? keyof P : never]: T extends infer P
? K extends keyof P
? P[K]
: never
: never
}
It combines all properties of objects consisting in union of object
so { foo: number } | { bar: number } => { foo: number, bar: number }
However i have trouble understanding this code, mainly:
-
What is the difference between
[K in T extends infer P ? keyof P : never] and [K in keyof T] ? -
What is
infer Pdoing before the question mark?
I understand what it does if this pattern is the context:A extends B ? infer Cbut i dont understand what it do if it is placed before the quetsion mark. Is P simply just a temporary variable? what is its purpose? -
How to read the whole
[]part?
Is it(K in T) extends infer...orK in (T extends infer ...)
Is the "extends" part of K in T or just T? -
What is with the extra conditional generics on the value of the mapped value?
Is it just checking if K exists within the possibilities of P? Just looking for a breakdown in general