TypeScript, a statically-typed superset of JavaScript, has gained massive popularity in the tech community due to its ability to catch errors early and improve code readability. One of TypeScript’s powerful features is the infer keyword, which allows developers to write more expressive and dynamic types.
Introduced in TypeScript 2.8, the infer keyword is used within conditional types to create temporary type variables. These type variables can then be used to infer types within a true or false branch of a conditional type. The infer keyword enables developers to write more dynamic and expressive types, as it allows TypeScript to determine a specific type based on the context in which it's used.
To better understand how infer works, let's take a look at the basic syntax of a conditional type:
type MyConditionalType<T> = T extends SomeType ? TrueType : FalseType;
In this example, T is a generic type parameter, and SomeType represents a type that T is being compared to. If T extends SomeType, the type of MyConditionalType
Now, let’s introduce the infer keyword into the mix:
type MyInferredType<T> = T extends SomeType<infer U> ? U : FalseType;
Here, we use the infer keyword to create a temporary type variable U within the true branch of the conditional type. If T extends SomeType, TypeScript will try to infer the type of U based on the type of T.
ReturnType is a utility type that extracts the return type of a function. It's a perfect example of how the infer keyword can be used to create dynamic types. Here's the definition of ReturnType:
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
In this definition, T is a function type that takes any number of arguments and returns any type. Using the infer keyword, we create a temporary type variable R to represent the return type of the function. If T is a function, TypeScript infers the return type and assigns it to R.
Let’s see ReturnType in action:
function greet(name: string): string { return `Hello, ${name}!`; } type GreetReturnType = ReturnType<typeof greet>; // GreetReturnType is inferred as 'string'
Here, ReturnType is used to infer the return type of the greet function, which is string.
Another useful utility type that leverages the infer keyword is Parameters. This type extracts the parameter types of a function as a tuple. The definition of Parameters is as follows:
type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
In this example, we create a temporary type variable P to represent the parameter types of the function. If T is a function, TypeScript infers the parameter types and assigns them to P as a tuple.
Let’s look at an example using Parameters:
function add(a: number, b: number): number { return a + b; } type AddParameters = Parameters<typeof add>; // AddParameters is inferred as [number, number]
Here, Parameters is used to infer the parameter types of the add function, which is a tuple [number, number].
The PromiseType utility type can be used to extract the type that a Promise resolves to. This is particularly useful when dealing with asynchronous functions. Here's the definition of PromiseType:
type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
In this example, we create a temporary type variable U to represent the type that the Promise resolves to. If T is a Promise, TypeScript infers the resolved type and assigns it to U. Here’s an example:
async function fetchData(): Promise<string> { return "Fetched data"; } type FetchedDataType = PromiseType<ReturnType<typeof fetchData>>; // FetchedDataType is inferred as 'string'
In this case, PromiseType is used to infer the type that the fetchData function's promise resolves to, which is string.
The UnboxArray utility type can be used to extract the type of the elements within an array. Here's the definition of UnboxArray:
type UnboxArray<T extends Array<any>> = T extends Array<infer U> ? U : never;
In this example, we create a temporary type variable U to represent the type of the elements within the array. If T is an array, TypeScript infers the element type and assigns it to U. For instance:
type MyArray = number[]; type ElementType = UnboxArray<MyArray>; // ElementType is inferred as 'number'
Here, UnboxArray is used to infer the type of elements within the MyArray type, which is number.
While the infer keyword is incredibly powerful, it has some limitations:
It can only be used within conditional types.
It’s not always possible for TypeScript to infer the correct type, especially when dealing with complex or recursive types. In such cases, developers may need to provide additional type annotations or refactor their types to help TypeScript infer the correct type.
By understanding and leveraging the power of infer, you can create more flexible TypeScript projects. Start considering incorporating the infer keyword into your toolkit today.
If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!
The above is the detailed content of Understanding the infer Keyword in TypeScript. For more information, please follow other related articles on the PHP Chinese website!