Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Typescript interface with two another interfaces and add 'null' to one property

Tags:

typescript

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.

like image 874
TwittorDrive Avatar asked Oct 28 '25 21:10

TwittorDrive


1 Answers

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:

  • Differences Between Type Aliases and Interfaces
  • Interfaces vs. Intersections
like image 136
T.J. Crowder Avatar answered Oct 31 '25 10:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!