4

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.

1 Answer 1

15

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly! It works for me, thanks.
this answers deserve more upvotes, clean and simple explication ! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.