【问题标题】:Typescript: Mapped type with exclude changes property modifiers打字稿:具有排除更改属性修饰符的映射类型
【发布时间】:2019-01-05 22:16:55
【问题描述】:

当使用 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 modifier mapped-types


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2020-05-02
      • 2018-09-14
      • 2019-11-19
      • 2021-01-29
      • 1970-01-01
      • 2020-06-01
      • 2019-08-15
      相关资源
      最近更新 更多