TypeScript - איך לסנן סוג איחוד על בסיס תנאי


נניח שיש לי סוג איחוד של:

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

האם יש דרך ליצור תת-קבוצה שמכילה רק את foo?

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

תשובה #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'>