TypeScript 教程 - ‘infer’ 关键字
大家好,这是 TypeScript 高级教程系列的第一篇。今天我将介绍以下代码的基本用法:
infer
对我来说,一开始很难理解我能用它做什么infer
。让我们从一个非常基本的例子开始。
type FlattenIfArray<T> = T extends (infer R)[] ? R : T
那么让我们分析一下这段代码:
- 我们检查泛型类型是否是数组
- 如果它是数组,从中提取真实类型
- 如果它不保持原样
不过,我们仍然不清楚 infer 的作用,所以让我们继续看另一个例子
type Unpromisify<T> = T extends Promise<infer R> ? R : T
这个看起来更清楚,因为它没有括号:
- 我们检查类型是否扩展了 Promise
- 如果是,我们从承诺中提取类型
- 如果它不保持原样
看到了吗?如果你使用 extends 只是为了检查类型是否是 Promise,那么你应该使用
type Unpromisify<T> = T extends Promise<any> ? T : never
在 infer 中,我们不用任何关键字,而是根据类型推断值。接下来我们尝试更高级的类型:
type FuncWithOneObjectArgument<P extends { [x: string]: any }, R> = (
props: P
) => R;
type DestructuredArgsOfFunction<
F extends FuncWithOneObjectArgument<any, any>
> = F extends FuncWithOneObjectArgument<infer P, any> ? P : never;
const myFunction = (props: { x: number; y: number }): string => {
return "OK";
};
const props: DestructuredArgsOfFunction<typeof myFunction> = {
x: 1,
y: 2
};
例如,您可以使用它来推断 React Component props 或其他使用解构参数的函数。
文章来源:https://dev.to/aexol/typescript-tutorial-infer-keyword-2cn