我想知道为什么使用T1
,我不能获得与{ a: string, b: number, c: boolean }
相同的类型?-?
在没有Generic的情况下无法工作。它只适用于泛型。
type Item = { a: string, b: number | undefined, c: boolean };
type T1 = { [P in keyof Item]-?: Item[P] }; // { a: string, b: number | undefined, c: boolean }
type T2<U> = { [P in keyof U]-?: U[P] }; // { a: string, b: number, c: boolean }
const t2: T2<Item> = {
a: 'abc',
b: 123,
c: false
}
实际上,b?: number
和b: number|undefined
是不等价的。你可以参考下面的例子。当b: number|undefined
变为b?: number
时,它将正常工作。以b: number|undefined
为例,使用T2<Item>
必须具有b
属性并不能解释问题,因为当只使用{ a: string, b: number | undefined, c: boolean}
时,b
属性也必须存在。TS游乐场
type Item = { a: string, b?: number, c: boolean };
type T1 = { [P in keyof Item]-?: Item[P] }; // { a: string, b: number | undefined, c: boolean }
type T2<U> = { [P in keyof U]-?: U[P] }; // { a: string, b: number, c: boolean }
const t2: T2<Item> = {
a: 'abc',
b: 123,
c: false
}
const t3: T1 = {
a: 'abc',
b: 123,
c: false
}
// Property 'b' is missing in type '{ a: string; c: false; }' but required in type '{ a: string; b: number | undefined; c: boolean; }'.
const t4: { a: string, b: number | undefined, c: boolean } = {
a: 'abc',
c: false
}