Reputation: 387
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
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
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