February 2019
Beginner
694 pages
18h 4m
English
When working with conditional types, we can extract the type of each parameter using the infer keyword. This is best explained through some examples, as follows:
type extractArrayType<T> = T extends (infer U)[] ? U : never; let stringType : extractArrayType<["test"]> = "test"; let stringTypeNoArray : extractArrayType<"test"> = "test";
Here, we have a conditional type named extractArrayType that is using generic syntax, and as such must be used with a type named T. Our conditional type then checks whether the type of T is an array. If it is an array, we then use the infer keyword to infer a type named U; otherwise we return the type never. Note that inferred type names (U in this case) can only be used within a ...
Read now
Unlock full access