打字稿:带有排除更改 属性 修饰符的映射类型

Typescript: Mapped type with exclude changes property modifiers

当使用 Minus 映射类型时,它似乎正在从属性中删除修饰符。我认为这是由 Exclude 类型引起的,但我不确定为什么。

我希望 Minus 只从 T 中删除 U 的键而不更改 T 的 属性 修饰符。

type Minus<T, U> = { [P in Exclude<keyof T, keyof U>]: T[P] }
type Noop<T> = { [P in keyof T]: T[P] }

interface Student {
  readonly gpa: number
  hobby?: string
  name: string
}

interface Person {
  name: string
}

type Difference = Minus<Student, Person>
// type Difference = {
//   gpa: number; <-- Where did readonly go?
//   hobby: string | undefined; <-- Why is it no longer optional? It seems to have picked up '| undefined' though...
// }

const test1: Difference = { gpa: 4 } // <-- Error: property 'hobby' is missing

type NoopType = Noop<Student>
// type StringsOnly = {
//   readonly gpa: number;
//   hobby?: string | undefined;
//   name: string;
// }

const test2: NoopType = { gpa: 4, name: "bob" } // OK

Typescript 将保留同态映射类型的修饰符,如 here 所述,但基本思想是,如果类型具有 { [P in keyof T]: T[P] } 或类似形式的形式,则保留修饰符。在您的情况下,由于 Exclude<keyof T, keyof U> ,编译器无法将映射类型识别为同态,我很确定此限制已记录在某处,但我目前无法找到它。解决这个问题的简单方法是通过 Pick 使用额外的间接寻址,例如:+

type Minus<T, U> = Pick<T, Exclude<keyof T, keyof U>>