DEV Community

Cover image for TS: How to override properties with type intersection
Viacheslav Borodulin
Viacheslav 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. 🤟

Discussion (6)

Collapse
nosovandrew profile image
Andrew Nosov

Awesome! Thanks you.

Collapse
pubkey profile image
Daniel M

Thank you. That what I was looking for.

Collapse
tanth1993 profile image
tanth1993

many thanks

Collapse
ujwal profile image
Ujwal Setlur

Very nice, thanks!

Collapse
mattvalleycodes profile image
mattvalleycodes

Nice one, Viacheslav! Thanks for sharing.

Collapse
laurodm profile image
Laurodm

Thanks!