我想知道为什么使用T1时,我无法获得与{ a: string, b: number, c: boolean }相同的类型?如果没有泛型,-?将无法工作。它只适用于泛型。
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
}发布于 2021-11-18 09:05:17
事实上,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 Playground
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
}https://stackoverflow.com/questions/70016835
复制相似问题