Hi, let's imagine the situation. We have type
type A = {
a: string;
b: string;
}
We want to get a new type using an intersection. It's just what we thought
type AB = A & {
b: number;
};
But it's not working☹️
Of course, we can use interfaces instread
interface A {
a: string;
b: string;
}
interface AB extends A {
b: number;
}
But how do that with types? Let's create a new utility type that can help us
type Override<T1, T2> = Omit<T1, keyof T2> & T2;
type AB = Override<A, { b: number }>
Pretty easy and very helpful. 🤟
Top comments (7)
I think it could be more useful if We can still validates the presence of the properties as in the T1 interface.
interface T1 {
a: object
}
type overridenTypeOnly = Override
The result would be that "a" property has its type changed, but can't accept "b" property because it isn't in T1 interface.
Any solution for this?
Awesome! Thanks you.
Thank you. That what I was looking for.
Nice one, Viacheslav! Thanks for sharing.
many thanks
Very nice, thanks!
Thanks!