如何根据条件过滤联合类型

时间:2019-06-15 05:50:41

标签: typescript

假设我的联合类型为:

type FooBar = {foo: 'a'} | {foo: 'b'} | {foo: 'c', bar: 'c'};

是否可以创建仅包含foo的子集?

type OnlyFoo = SomeFilter<FooBar, 'foo'>;
// type OnlyFoo = {foo: 'a'} | {foo: 'b'};

1 个答案:

答案 0 :(得分:1)

您可以编写一种分布式条件类型,该条件类型首先通过所需的键(例如foo)进行过滤,然后通过测试Exclude<FooBar, 'foo'>是否为never来过滤具有任何额外键的任何类型。 :

type FilterByProp<T, K extends PropertyKey> = T extends Record<K, any> ? 
    Exclude<keyof T, K> extends never ? T : 
    never : never;

type FooBar = {foo: 'a'} | {foo: 'b'} | {foo: 'c', bar: 'c'};
type OnlyFoo = FilterByProp<FooBar, 'foo'>