Skip to content

Exclude

从一个联合类型中返回剔除 T 包含的字符串的类型的联合类型

ts
type Exclude<T, U> = T extends U ? never : T

重点

  1. Exclude 是作用于属性的(keyof),而不是作用于类型的(typeof)

  2. 其返回的是一个联合类型("a" | "b")

  3. U中可以包含不存在于T中的类型

栗子

ts
const person = {
  name: "张三",
  age: 12,
  address: "南京",
}

type Person = typeof person
// Exclude 是作用于属性的
type PersonKeys = keyof Person

// "address"
type MiniPerson = Exclude<keyof typeof person, "name" | "age" | "sex">