【问题标题】:Typescript access a property a union type in which not all members have said property [duplicate]打字稿访问属性联合类型,其中并非所有成员都具有所述属性[重复]
【发布时间】:2022-10-04 18:05:07
【问题描述】:

我有以下代码:

interface A {
    a: number;
}

interface B extends A {
    b: number;
}

const instanceOfB: B = {
    a: 1,
    b: 2,
}

const myFunct = (arg: A | B) => {
    const myNumber = arg.b ?? 42;
    console.log(myNumber);
};

myFunct(instanceOfB);

myFunct 内部,我想访问argb 属性,这取决于arg 是否属于B 类型,arg 上可能存在也可能不存在。如果它不存在并且访问返回undefined,我使用42 的后备值。
Typescript 抱怨 Property 'b' does not exist on type 'A | B'.,这是真的。 A | BA 基本相同,因为它们之间仅共享a,但我仍然想尝试访问它并使用我的后备值(如果没有)。 我知道我可以通过将相关行更改为例如更改我的 JavaScript 以满足 Typescript const myNumber = "b" in arg ? arg.b : 42;,但是当我的代码(在我看来)非常好时,我真的不想为了让 Typescript 开心而更改我的 JavaScript 代码。

我的 Typescript 唯一问题是否有 Typescript 唯一解决方案?

另外,如果有人知道,我会对 Typescript 为什么抱怨 arg.b ?? 42 而不是 "b" in arg ? arg.b : 42 非常感兴趣。

【问题讨论】:

  • 在这种情况下,只需使用 in 运算符。见examplein 运算符与工会配合得很好,或者尝试 StrictUnion 助手。见this答案

标签: typescript types


【解决方案1】:

对于 nullundefined 值,?? 运算符会转到“否则”情况。换句话说,它与检查密钥的存在不同。

"b" in arg 有效,因为 in 将为已设置为 nullundefined 的密钥返回 true:

const arg = { a: undefined }
console.log(arg.a ?? "not in") // not in
console.log("a" in arg ? "in" : "not in") // in

打字稿在这里只是严格假设你的意思是说这个值存在,是空还是未定义当您使用?? 时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2017-06-15
    • 2019-10-06
    • 2019-08-15
    • 2022-01-04
    相关资源
    最近更新 更多