如何在Typescript中对数组使用可选链接? [英] How to use optional chaining with array in Typescript?

查看:51
本文介绍了如何在Typescript中对数组使用可选链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将可选链接与数组而不是对象一起使用,但不确定如何做到这一点:

I'm trying to use optional chaining with array instead of object but not sure how to do that:

这就是我想要做的 myArray.filter(x => x.testKey === myTestKey)?[0] .

但是它给出了这样的错误,所以如何在数组中使用它.

But it's giving error like that so how to use it with array.

推荐答案

您需要在?后面放置.才能使用可选链接:

You need to put a . after the ? to use optional chaining:

myArray.filter(x => x.testKey === myTestKey)?.[0]

游乐场链接

仅使用?会使编译器认为您正在尝试使用条件运算符(然后由于未看到:而引发错误.稍后)

Using just the ? alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a : later)

可选链接不仅是TypeScript的事情,而且是已完成的提案也使用普通JavaScript .

Optional chaining isn't just a TypeScript thing - it is a finished proposal in plain JavaScript too.

它可以与上述括号符号一起使用,但也可以与点符号属性访问一起使用:

It can be used with bracket notation like above, but it can also be used with dot notation property access:

const obj = {
  prop2: {
    nested2: 'val2'
  }
};

console.log(
  obj.prop1?.nested1,
  obj.prop2?.nested2
);

并带有函数调用:

const obj = {
  fn2: () => console.log('fn2 running')
};

obj.fn1?.();
obj.fn2?.();

这篇关于如何在Typescript中对数组使用可选链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆