Bla*_*mba 107 javascript arrays function typescript optional-chaining
我正在尝试将可选链接与数组而不是对象一起使用,但不确定如何执行此操作:
这就是我想要做的myArray.filter(x => x.testKey === myTestKey)?[0]
。还用一个函数尝试类似的事情:
let x = {a: () => {}, b: null}
console.log(x?b());
Run Code Online (Sandbox Code Playgroud)
但是它给出了这样的错误,所以如何将它与数组或函数一起使用。
Cer*_*nce 218
您需要在.
之后?
使用可选链接:
myArray.filter(x => x.testKey === myTestKey)?.[0]
Run Code Online (Sandbox Code Playgroud)
仅使用?
only 会使编译器认为您正在尝试使用条件运算符(然后它会抛出错误,因为它:
稍后看不到)
可选链不仅仅是 TypeScript 的东西——它也是一个用纯 JavaScript完成的提案。
它可以与上面的括号表示法一起使用,但也可以与点表示法属性访问一起使用:
myArray.filter(x => x.testKey === myTestKey)?.[0]
Run Code Online (Sandbox Code Playgroud)
并使用函数调用:
const obj = {
prop2: {
nested2: 'val2'
}
};
console.log(
obj.prop1?.nested1,
obj.prop2?.nested2
);
Run Code Online (Sandbox Code Playgroud)
Luk*_* Vo 32
我正在 Edge Chromium 84 上测试的 ECMA 262 (2020) 可以在没有 TypeScript 转译器的情况下执行可选链接运算符:
// All result are undefined
const a = {};
console.log(a?.b);
console.log(a?.["b-foo-1"]);
console.log(a?.b?.());
// Note that the following statements throw exceptions:
a?.(); // TypeError: a is not a function
a?.b(); // TypeError: a?.b is not a function
Run Code Online (Sandbox Code Playgroud)
Bla*_*mba 17
在官方文档上的新内容页面上进行了一些搜索后才找到它
使用数组的正确方法是在.
后面添加?
所以它会像
myArray.filter(x => x.testKey === myTestKey)?.[0]
Run Code Online (Sandbox Code Playgroud)
我想更多地了解我上面的问题案例到底发生了什么。
myArray.filter(x => x.testKey === myTestKey)?[0]
Run Code Online (Sandbox Code Playgroud)
转译为
const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;
Run Code Online (Sandbox Code Playgroud)
因此,它会抛出错误,因为 : 之后缺少某些内容,并且您可能不希望将代码转换为此。
感谢某些性能的回答,我学到了关于打字稿的新知识,尤其是工具https://www.typescriptlang.org/play/index.html。
Las*_*M4N 15
该函数不一定位于对象内部,您也可以使用可选链接来运行函数,如下所示:
someFunction?.();
Run Code Online (Sandbox Code Playgroud)
如果someFunction
存在则运行,否则跳过执行,不会报错。
这项技术实际上非常有用,特别是当您使用可重用组件而某些组件可能没有此功能时。