
上QQ阅读APP看书,第一时间看更新
The infer keyword
In the preceding section, we have defined the Flatten type. However, this behavior was hardcoded to return a number when an array of one dimension is provided. This means that the flatten type only works as expected with arrays of numbers. Fortunately, since the TypeScript 2.8 release, we can use the infer keyword to overcome this limitation:
type TypedFlatten<T> = T extends Array<infer U> ? U : T;
The infer keyword can be used in other scenarios. For example, we can use it to infer the return type of a function:
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
type func1 = () => number;
type returnOfFunc1 = ReturnType<func1>; // number