typescript - Bir birleşim türünü bir koşula göre nasıl filtrelerim


Diyelim ki benim şöyle bir birleşim türüm var:

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

Sadece foo içeren bir alt küme oluşturmanın bir yolu var mı?

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

Cevap #1

İlk olarak istenen anahtara göre filtreleyen (örneğin foo) ve ardından ekstra anahtara sahip herhangi bir türü Exclude<FooBar, 'foo'>'nin never olup olmadığını test ederek filtreleyen bir dağıtıcı koşullu tür yazabilirsiniz:

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'>