【发布时间】: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