如何对数组或函数使用可选链接? [英] How to use optional chaining with array or functions?
问题描述
我正在尝试对数组而不是对象使用可选链接,但不知道该怎么做:
I'm trying to use optional chaining with an array instead of an object but not sure how to do that:
这就是我想要做的myArray.filter(x => x.testKey === myTestKey)?[0]
.还用函数尝试类似的事情:
Here's what I'm trying to do myArray.filter(x => x.testKey === myTestKey)?[0]
.
Also trying similar thing with a function:
let x = {a: () => {}, b: null}
console.log(x?b());
但是它给出了这样的错误,所以如何将它与数组或函数一起使用.
But it's giving an error like that so how to use it with an array or a function.
推荐答案
你需要在 ?
后面放一个 .
才能使用可选链:
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?.();
这篇关于如何对数组或函数使用可选链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!