打字稿从类型中排除类型

时间:2019-02-17 17:39:15

标签: typescript types

interface First {
  field1: number;
}

interface Second {
  field2: number
}

interface Third extends First, Second {

}

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

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

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

例如

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

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

这可以实现吗?怎么样?

1 个答案:

答案 0 :(得分:2)

如果要将一种类型的所有键从另一种类型中排除,则可以使用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>
相关问题