In this guide, we'll explore the role of the infer clause in TypeScript. The infer keyword is a powerful tool that allows you to create more flexible and reusable types by capturing and reusing type information within conditional types.
infer?The infer keyword is used within the context of conditional types to infer a type variable from a given type. This is particularly useful when you want to extract specific types from complex structures, such as function parameters or return types.
infer?Using infer can help you:
Let's start with a simple example to illustrate how infer works. Consider the following type:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
In this example, we're using infer to capture the return type of a function. If T is a function type, R will be the inferred return type; otherwise, it will be never.
Create a type GetElementType<T> that extracts the element type from a Set. For example, GetElementType<Set<number>> should be number.
Create a type GetSecondParam<T> that extracts the second parameter type from a function. Return never if there's no second parameter.
E.g.:
GetSecondParam<(a: string, b: number, c: boolean) => void> should be number.
GetSecondParam<(a: string) => void> should be never.
Create a type Flatten<T> that recursively unwraps nested arrays to get the innermost type. For example:
Flatten<number[][][]> should be numberFlatten<string[][]> should be stringFlatten<boolean[]> should be booleanThe infer keyword is a powerful feature in TypeScript that allows for more expressive and flexible type definitions. By leveraging infer, you can create types that adapt to the structure of your code, making it easier to work with complex types and improving overall type safety.