Typescript:具有排除更改属性修饰符的映射类型

Lio*_*Tay 2 modifier typescript mapped-types

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

我期望 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
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 5

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

type Minus<T, U> = Pick<T, Exclude<keyof T, keyof U>>
Run Code Online (Sandbox Code Playgroud)