I have two TS interfaces:
interface Alpha { name: string; login: string; amount: string; }
and
interface Beta { id: number; name: string; login: string; amount: string; }
I would like to create the third interface Gamma which extends those two, add new field to it and make amount field can be null as well as a string:
interface Gamma extends Alpha, Beta { targetAmount: string | null, amount: string | null }
Those amount: string | null is not possible to do without extra actions. I've find a few answers here, but they are about extending types or 'nulling' all properties.
You can create a type that combines Alpha and Beta (an intersection type) omitting amount via the Omit utility type, then either extend that using interface syntax or add targetAmount and amount via intersection:
interface Gamma extends Omit<Alpha & Beta, "amount"> {
targetAmount: string | null;
amount: string | null;
};
Playground link
Or with type using an intersection instead:
type Gamma = Omit<Alpha & Beta, "amount"> & {
targetAmount: string | null;
amount: string | null;
};
Playground link
Either way, Gamma's amount ends up as string | null.
For what it's worth, here are some sections of the handbook contrasting interfaces and type aliases, and extending vs. intersection:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With