在Typescript中,是否可以从另一个联合类型的字段值获取联合类型?
type MyUnionType =
| { foo: 'a', bar: 1 }
| { foo: 'b', bar: 2 }
| { foo: 'c', bar: 3 }
// can I generate this automatically?
// i.e. a union of the possible values of foo in MyUnionType?
type Foos = 'a' | 'b' | 'c'
我曾希望Pick<MyUnionType, 'foo'>
可以做到,但它并不能完全满足需求——它返回了我想要的类型,但是嵌套在一个名为foo
的字段下:{ foo: 'a' | 'b' | 'c' }