英文:
How to use infer to extract a common key from a union type?
问题
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;
// I want to make a type, which is equivalent to this:
// export type FooBarBazTypes = 'Foo' | 'Bar' | 'Baz';
// But I want to do it with some magic infer stuff.
export type SomeMagicCrap<T> = T extends Base<infer U> ? U : never;
export type FooBarBazTypes = SomeMagicCrap<FooBarBaz> // Should be equivalent to 'Foo' | 'Bar' | 'Baz';
如何提取'Foo'
、'Bar'
和'Baz'
?我知道它涉及到infer
,但我不记得具体是怎么做的。
英文:
I'm creating a library where I need to use a common type distinguished by name; I need to be able to get the names easily.
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;
// I want to make a type, which is equivalent to this:
// export type FooBarBazTypes = 'Foo' | 'Bar' | 'Baz';
// But I want to do it with some magic infer stuff.
export type SomeMagicCrap<T>;
export type FooBarBazTypes = SomeMagicCrap<FooBarBaz > // Should be equivalent to 'Foo' | 'Bar' | 'Baz';
How can I extract 'Foo'
, 'Bar'
and 'Baz'
? I know it involves infer
but I don't remember exactly how.
答案1
得分: 1
你可以检查FooBarBaz
联合类型(Foo | Bar | Baz
)的值是否扩展了Base
,然后通过infer
推断传递给Base
的泛型值,并将其返回,以生成一个新的联合类型从这些字符串值中。
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;
type SomeMagicCrap<T> = T extends Base<infer U> ? U : never;
export type FooBarBazTypes = SomeMagicCrap<FooBarBaz>; // 'Foo' | 'Bar' | 'Baz'
英文:
What you can do is check whether values of the FooBarBaz
union (Foo | Bar | Baz
) extend Base
and then infer
the generic value passed to Base
and return it to generate a new union from those string values.
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;
type SomeMagicCrap<T> = T extends Base<infer U> ? U : never;
export type FooBarBazTypes = SomeMagicCrap<FooBarBaz>; // 'Foo' | 'Bar' | 'Baz'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论