How to use optional chaining with array in Typescript?

Black Mamba

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

Here's what I'm trying to do myArray.filter(x => x.testKey === myTestKey)?[0].

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

CertainPerformance

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

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

Playground link

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)

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
);

And with function calls:

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Optional chaining and Array in swift

From Java

How to enable optional chaining with Create React App and TypeScript

From Java

How to use optional chaining in Node.js 12

From Dev

How to use optional chaining while searching through a dictionary in swift?

From Dev

Object is possibly 'undefined' Error on Optional Chaining Typescript

From Dev

Java stream: use optional filter() operations on chaining

From Dev

js: proper way to use optional chaining?

From Dev

How to know where Optional Chaining is breaking?

From Dev

how to extend optional chaining for all types

From Java

Typescript optional chaining error: Expression expected.ts(1109)

From Java

Optional chaining (?.) in nashorn

From Dev

Optional Chaining returning an Int

From Dev

Swift 3.0 Optional Chaining

From Dev

Optional Chaining in JavaScript

From Dev

swift optional chaining with cast

From Dev

Optional Chaining Not Working As Expected

From Dev

Optional chaining with Swift strings

From Dev

Chaining Optional.orElseThrow

From Dev

Optional chaining for constructor calls?

From Dev

How to use boost::optional

From Dev

How to use Optional in Java?

From Dev

How to port from java.util.Optional method call chaining to Guava Optional?

From Dev

Optional chaining not working for optional protocol requirements

From Dev

Is there an equivalent to optional chaining with arithmetic operators?

From Dev

dynamicType of optional chaining not the same as assignment

From Dev

Optional.ofNullable and method chaining

From Dev

Optional Chaining or ternary expression in Swift?

From Dev

Chaining Promises in Typescript

From Dev

How to use numpy in optional typing

Related Related

HotTag

Archive