首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript Generic with in keyof

Typescript Generic with in keyof
EN

Stack Overflow用户
提问于 2021-11-18 08:41:06
回答 1查看 31关注 0票数 0

我想知道为什么使用T1时,我无法获得与{ a: string, b: number, c: boolean }相同的类型?如果没有泛型,-?将无法工作。它只适用于泛型。

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

发布于 2021-11-18 09:05:17

事实上,b?: numberb: number|undefined不是等价的。你可以参考下面的例子。将b: number|undefined修改为b?: number,即可正常工作。对于b: number|undefined的示例,使用T2<Item>必须具有b属性无法解释问题,因为当仅使用{ a: string, b: number | undefined, c: boolean}时,b属性也必须存在。TS Playground

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70016835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档