RedditPP Mascot

RedditPP

r/typescript • … • u/Tuckertcs

How to create a soft-union type, for objects that don't share the same properties?

How could I create a type that's a union of a bunch of objects, but with undefined placed on properties that don't exist in every object?

For example:

type Foo = { type: 'foo', a: string, b: number, };

type Bar = { type: 'bar', a: number, c: string, };

type FooBar = Foo | Bar; // Result: { // type: 'foo', // a: string, // b: number, // } | { // type: 'bar', // a: number, // c: string, // };

type SoftFooBar = ...; // Result: { // type: 'foo', // a: string, // b: number, // c: undefined, // How do I do this? // } | { // type: 'bar', // a: number, // b: undefined, // How do I do this? // c: string, // };

Bonus points if it works recursively for nested properties too.

Is this possible?

Edit:

Please trust that I know *why* I'm doing it and there's a reason for it, I just need help on *how* to do it.

— 0