DEV Community

Cover image for TS: How to override properties with type intersection
Slava Borodulin
Slava Borodulin

Posted on • Updated on

TS: How to override properties with type intersection

Hi, let's imagine the situation. We have type

type A = {
  a: string;
  b: string;
}
Enter fullscreen mode Exit fullscreen mode

We want to get a new type using an intersection. It's just what we thought

type AB = A & {
  b: number;
};
Enter fullscreen mode Exit fullscreen mode

But it's not working☹️

Of course, we can use interfaces instread

interface A {
  a: string;
  b: string;
}

interface AB extends A {
  b: number;
}
Enter fullscreen mode Exit fullscreen mode

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 }>

Enter fullscreen mode Exit fullscreen mode

Pretty easy and very helpful. 🤟

Top comments (7)

Collapse
 
marcosfreitas profile image
marcosfreitas

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?

Collapse
 
nosovandrew profile image
Andrew Nosov

Awesome! Thanks you.

Collapse
 
pubkey profile image
Daniel M

Thank you. That what I was looking for.

Collapse
 
mattvalleycodes profile image
mattvalleycodes

Nice one, Viacheslav! Thanks for sharing.

Collapse
 
tanth1993 profile image
tanth1993

many thanks

Collapse
 
ujwal profile image
Ujwal Setlur

Very nice, thanks!

Collapse
 
laurodm profile image
Laurodm

Thanks!