简体   繁体   English

如何检查可选的 object 属性是否存在?

[英]How to check if optional object property exists?

I'm having trouble getting TypeScript to recognise that an optional property of an object is defined.我无法让 TypeScript 识别定义了 object 的可选属性。

type OuterKeys = 'a' | 'b';

type Inner = {
    value: '';
}

type Outer = Partial<Record<OuterKeys, Inner>>;

const thisGivesError = (key: OuterKeys, outer: Outer) => {
    if (outer[key]) {
        console.log(outer[key].value);
    }
}

Even though I explicitly check if outer[key] is defined, I'm getting error when trying to access outer[key].value : Object is possibly 'undefined' .即使我明确检查outer[key]是否已定义,我在尝试访问outer[key].value时遇到错误: Object is possibly 'undefined'

How can I work around it?我该如何解决? The only way I found is assigning outer[key] to a variable and having another if , like below.我发现的唯一方法是将outer[key]分配给一个变量并拥有另一个if ,如下所示。 Is this the only way to go?这是通往 go 的唯一途径吗?

const thisWorks = (key: OuterKeys, outer: Outer) => {
    const o = outer[key];
    if (o) {
      console.log(o.value);
    }    
}

The playground with the code can be found here带有代码的游乐场可以在这里找到

Edit: I don't want to use !编辑:我不想使用! operator, as it feels like a workaround - why would I tell TypeScript that this value is set using non-null assertion, if I already checked for its existence with if ?运算符,因为它感觉像是一种解决方法 - 如果我已经用if检查了它的存在,为什么我要告诉 TypeScript 这个值是使用非空断言设置的? Same for .?同样的.? - I already have the if , so this value for sure exists and is not optional. - 我已经有了if ,所以这个值肯定存在并且不是可选的。

That's #10530 , currently TS doesn't narrow down on indexed access.那是#10530 ,目前 TS 不会缩小索引访问的范围。

Because the inner object which holds the value is never specified to not be undefined.因为保存值的内部 object 从未被指定为未定义。 You can fix this by simply adding a question mark.您可以通过简单地添加一个问号来解决这个问题。

Ex adding a question mark:例如添加问号:

const thisGivesError = (key: OuterKeys, outer: Outer) => {
    if (outer[key]) {
        console.log(outer[key]?.value);
    }
}

At this point, after checking for outer[key] being truthy, it's safe to go with non-null assertion:此时,在检查outer[key]是否为真后,使用非空断言到 go 是安全的:

if (outer[key]) {
    console.log(outer[key]!.value);
}

Though I don't know how to make TypeScript figure it out on its own.虽然我不知道如何让 TypeScript 自行解决。

You can make use of object?.key operator.您可以使用object?.key操作员。 You can learn more about it here .您可以在此处了解更多信息。

Your final code will be:您的最终代码将是:

const thisWorks = (key: OuterKeys, outer: Outer) => {
  if (outer[key]) {
    console.log(outer[key]?.value);
  }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM