前端 TypeScript 面试题, TypeScript 的关键字 infer 有什么作用?
前端 TypeScript 面试题, TypeScript 的关键字 infer 有什么作用?
QA
Step 1
Q:: What is the purpose of the 'infer' keyword in TypeScript?
A:: The 'infer' keyword in TypeScript is used within conditional types to extract and infer the type of a particular element. It allows you to create more complex and reusable type definitions by inferring types from certain positions within other types. This is particularly useful when working with utility types and type transformations.
Step 2
Q:: Can you provide an example of how 'infer' is used?
A:: Certainly! Consider the following example:
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
const fn = (x: number) => 'hello';
type ReturnTypeOfFn = GetReturnType<typeof fn>; // 'ReturnTypeOfFn' will be inferred as 'string'
In this example, the 'infer R' keyword is used to infer the return type 'R' from the function type 'T'.
Step 3
Q:: What are some common use cases for the 'infer' keyword in TypeScript?
A:: The 'infer' keyword is commonly used in utility types to extract types from function signatures or tuples, enabling the creation of more flexible and reusable types. For example,
it is used in utilities like ReturnType``,
Parameters``,
and ConstructorParameters``, which infer types from functions and constructors. It's also valuable in creating custom type utilities where dynamic type extraction is required.
Step 4
Q:: What are the limitations or challenges of using 'infer' in TypeScript?
A:: 'Infer' can only be used in conditional types, which can make its application somewhat limited. Additionally, because 'infer' relies on conditional types, the logic can become complex and difficult to read or maintain in larger codebases. Developers need to be cautious with its use to avoid over-complicating type definitions.