使用减号映射类型时,似乎正在从属性中删除修饰符。我认为这是由排除类型引起的,但我不确定为什么。
我希望减号仅从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
答案 0 :(得分:3)
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>>