Typescript'te Type'dan Type'ı hariç tut


interface First {
  field1: number;
}

interface Second {
  field2: number
}

interface Third extends First, Second {

}

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

İyi bilinen Omit türü ile bir türden özellikleri çıkarabiliriz

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

Örn.

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

Ama sorun, Second birkaç alandan fazlasına sahip olduğunda ortaya çıkıyor

Bu gerçekleştirilebilir mi? Nasıl?

Cevap #1

Bir türün tüm anahtarlarını başka bir türden hariç tutmak istiyorsanız, Omit için parametre olarak keyof'u kullanabilirsiniz:

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>

İlgili makaleler