You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用infer从联合类型中提取公共属性的类型联合?

提取联合类型中name属性的字面量类型

你可以通过条件类型结合infer关键字实现这个需求,直接定义SomeMagicCrap如下:

export type SomeMagicCrap<T> = T extends Base<infer U> ? U : never;

原理说明

当传入的类型T是Base<U>的子类型时,infer U会自动推断出每个接口继承Base时传入的字面量字符串类型。由于T是联合类型Foo | Bar | Baz,TypeScript的条件类型会对联合类型的每个成员进行分发处理,最终将所有推断出的U合并成新的联合类型'Foo' | 'Bar' | 'Baz'。

如果想要更通用的实现(不依赖Base接口),可以直接提取name属性的类型:

export type SomeMagicCrap<T> = T extends { name: infer U } ? U : never;

完整验证代码

interface Base<T extends string> {
   name: T;
}

interface Foo extends Base<'Foo'> {}
interface Bar extends Base<'Bar'> {}
interface Baz extends Base<'Baz'> {}

export type FooBarBaz = Foo | Bar | Baz;

export type SomeMagicCrap<T> = T extends Base<infer U> ? U : never;

export type FooBarBazTypes = SomeMagicCrap<FooBarBaz>; // 类型等价于 'Foo' | 'Bar' | 'Baz'

内容的提问来源于stack exchange,提问作者Bryan Rayner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:50:13