Dakito
Dakito

Reputation: 387

How can i overwrite a property type?

Given that i have following structure

type AB = {
    A: string;
    B: string;
}

but now i want to create a new type which extends keys but also overwrite the 'A' property. So final type should be

{
    A: number;
    B: string;
}

So I tried to assign AB type to my final type and append the 'A' property with new type

type final = AB & {A: number};

But it doesn't work :( So my question is; how to extend type to other with changed property type?

Upvotes: 2

Views: 1441

Answers (3)

Slava Borodulin
Slava Borodulin

Reputation: 269

type Override<T1, T2> = Omit<T1, keyof T2> & T2;

Upvotes: 0

Karol Majewski
Karol Majewski

Reputation: 25790

Creating a simple intersection (AB & {A: number}) will not work, because it will make all individual properties intersect separately. It means A would need to be of type string & number, which is impossible do achieve.

Use this instead:

type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

Usage:

type Final = Overwrite<AB, { A: number }>

Upvotes: 1

Dmitriy
Dmitriy

Reputation: 2822

I'm not sure if this is the most elegant solution, but you could use a mapped type to filter out keys that you want to override and then intersect it with override:

type Override<T1, T2> = {
    [K in Exclude<keyof T1, keyof T2>]: T1[K]
} & {
    [K in keyof T2]: T2[K]
};

type final = Override<AB, { A: number }>;

Upvotes: 3

Related Questions