当使用 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
Typescript 将保留同态映射类型的修饰符,如所述here https://github.com/Microsoft/TypeScript/pull/12563,但基本思想是,如果类型具有以下形式,则保留修饰符{ [P in keyof T]: T[P] }
或类似的东西。在您的情况下,编译器不会将映射类型识别为同态,因为Exclude<keyof T, keyof U>
我很确定这个限制已记录在某处,但我目前无法找到它。解决这个问题的简单方法是使用额外的间接方法Pick
例如:+
type Minus<T, U> = Pick<T, Exclude<keyof T, keyof U>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)