【问题标题】:Typescript Generic with in keyofTypescript Generic with in keyof
【发布时间】:2021-11-18 17:05:17
【问题描述】:

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

【问题讨论】:

  • 我认为你的假设是错误的。 T2&lt;Item&gt; 仍然有 b| undefined(在映射类型之前添加 {} &amp; 使类型更清晰)typescriptlang.org/play?#code/…
  • 另外值得注意的是b: number | undefinedb?: number不同。
  • @RobbyCornelissen,我认为你找到了完全错误的部分!

标签: typescript typescript-generics


【解决方案1】:

事实上,b?: numberb: number|undefined 并不是等价的。你可以参考下面的例子。当b: number|undefined改成b?: number后,就可以正常工作了。对于b: number|undefined的例子,T2&lt;Item&gt;的使用必须有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
}

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2022-06-15
    • 2019-08-05
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2017-12-07
    相关资源
    最近更新 更多