如何使用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
相关产品推荐
相关产品推荐

