深入研究打字稿&#s推断关键字

使用typescript条件类型中的infer关键字进行类型推断

本文介绍TypeScript中infer关键字在条件类型中的用法,尤其是在处理复杂类型时,它能有效地提取或转换类型信息。

基本用法

infer关键字只能用于条件类型中,通常与extends关键字结合使用。其语法如下:

type InferType = T extends infer U ? U : never;

其中,T extends infer U 表示尝试推断T的类型并将其赋值给U。如果类型推断成功,U将成为推断出的类型。

以下是一些示例:

type InferType = T extends infer U ? U : never;type StringType = InferType; // stringtype NumberType = InferType; // numbertype UnionType = InferType; // string | numberinterface User {  name: string;  age: number;}type UserType = InferType; // User

这些例子中,InferType 实际上只是返回T本身,没有进行任何转换或处理,主要用于演示条件类型和类型推断的基本用法。

常见示例

提取函数的返回类型

假设我们有一个函数类型,需要提取其返回类型:

type GetReturnType = T extends (...args: any[]) => infer R ? R : never;type ExampleFunction = (x: number, y: string) => boolean;type ReturnTypeOfExampleFunction = GetReturnType; // boolean

代码解释:T extends (...args: any[]) => infer R 检查T是否为函数类型;infer R 推断函数的返回类型并赋值给R? R : never 如果T是函数类型则返回推断出的返回类型R,否则返回never

提取数组的元素类型

同样可以使用infer提取数组的元素类型:

type GetArrayElementType = T extends (infer U)[] ? U : never;type MyArray = string[];type ElementTypeOfMyArray = GetArrayElementType; // string

T extends (infer U)[] 推断数组元素类型U。由于Tstring[]U将是string

快转字幕 快转字幕

新一代 AI 字幕工作站,为创作者提供字幕制作、学习资源、会议记录、字幕制作等场景,一键为您的视频生成精准的字幕。

快转字幕 357 查看详情 快转字幕 提取Promise的值类型

对于Promise类型,可以提取其解析类型:

type GetPromiseValueType = T extends Promise ? U : never;type ExamplePromise = Promise;type ValueTypeOfExamplePromise = GetPromiseValueType; // number

T extends Promise 检查T是否为Promise类型;infer U 推断Promise的解析值类型并赋值给U

提取函数的参数类型

infer 也可以用来提取函数的参数类型:

type GetParameters = T extends (...args: infer P) => any ? P : never;type ExampleFunction = (a: number, b: string) => void;type Params = GetParameters; // [number, string]

T extends (...args: infer P) => any 检查T是否为函数类型;infer P 推断函数的参数类型并赋值给P

提取构造函数的参数类型

类似地,可以提取类的构造函数的参数类型:

type ConstructorParameters = T extends new (...args: infer P) => any ? P : never;class ExampleClass {  constructor(public a: number, public b: string) {}}type Params = ConstructorParameters; // [number, string]

高级示例:复杂的类型推断

以下示例展示了在条件类型中使用更复杂的推断逻辑:

type IsArray = T extends (infer U)[] ? U : never;type IsFunction = T extends (...args: any[]) => infer R ? R : never;type ExtractType = T extends any[]  ? IsArray  : T extends (...args: any[]) => any  ? IsFunction  : T;// Examplestype ArrayType = ExtractType; // stringtype FunctionReturnType = ExtractType number>; // numbertype DefaultType = ExtractType; // boolean

总结

infer关键字在TypeScript条件类型中用于从其他类型推断新的类型变量,能够有效地提取和利用特定的子类型或属性,增强了TypeScript类型系统的表达能力和灵活性。 它简化了从复杂类型中提取所需部分的过程。

深入研究打字稿&#s推断关键字深入研究打字稿&#s推断关键字

以上就是深入研究打字稿&#s推断关键字的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/371212.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月6日 07:40:04
下一篇 2025年11月6日 07:43:59

相关推荐

发表回复

登录后才能评论
关注微信