首页 > 解决方案 > 打字稿从类型中排除类型

问题描述

interface First {
  field1: number;
}

interface Second {
  field2: number
}

interface Third extends First, Second {

}

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

使用众所周知的省略类型,我们可以省略类型中的属性

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

例如

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

但问题是当 Second 有多个字段时

这是可以实现的吗?如何?

标签: typescripttypes

解决方案


如果要从另一种类型中排除一种类型的所有键,可以将keyof其用作参数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>

推荐阅读