Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript exclude Type from Type

interface First {
  field1: number;
}

interface Second {
  field2: number
}

interface Third extends First, Second {

}

// type Forth = Omit<Third, Second>
// expect Fourth to be { field1: number}

With the well know Omit type we can omit properties from a type

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

E.g.

 Omit<Third, 'field2'> and it will work as the above

But the problem is when Second has more than a few fields

Is this achievable? How?

like image 567
ZenVentzi Avatar asked Oct 15 '25 03:10

ZenVentzi


1 Answers

If you want to exclude all the keys of one type from another type, you can use keyof as the parameter to Omit:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

interface First {
  field1: number;
}

interface Second {
  field2: number
}

interface Third extends First, Second {

}

type ThirdWithoutSecond = Omit<Third, keyof Second>
like image 199
Titian Cernicova-Dragomir Avatar answered Oct 18 '25 09:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!