Typescript Generic的in关键字为



我想知道为什么使用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?: numberb: 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
}