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
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

And with function calls:

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

obj.fn1?.();
obj.fn2?.();
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from CertainPerformance on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
Optional chaining also includes two other operations. First there’s the optional element access which acts similarly to optional property accesses, but allows us to access non-identifier properties (e.g. arbitrary strings, numbers, and symbols): ... There’s also optional call, which allows us to conditionally call expressions if they’re not null or undefined.
🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › optional-chaining.ts
TypeScript: Playground Example - Optional Chaining
const callUpdateMetadata = (metadata: any) => Promise.resolve(metadata); // Fake API call const updateAlbumMetadata = async (metadata: any, callback?: () => void) => { await callUpdateMetadata(metadata); callback?.(); }; // You can read more about optional chaining in the 3.7 blog post: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/ MSG
Top answer
1 of 5
589

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
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

And with function calls:

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

obj.fn1?.();
obj.fn2?.();
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 5
50

Just found it after a little searching on the what's new page on official documentation

The right way to do it with array is to add . after ?

so it'll be like

myArray.filter(x => x.testKey === myTestKey)?.[0] // in case of object
x?.() // in case of function

I'll like to throw some more light on what exactly happens with my above question case.

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

Transpiles to

const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;

Due to which it throws the error since there's something missing after : and you probably don't want your code to be transpilled to this.

Thanks to Certain Performance's answer I learned new things about typescript especially the tool https://www.typescriptlang.org/play/index.html .

🌐
Reddit
reddit.com › r/node › conditionally call a function with optional chaining.
r/node on Reddit: Conditionally call a function with optional chaining.
November 10, 2020 - Seems like something is being used incorrectly further up the chain. ... Yep. And that's why kids, always use Typescript ❤️ ... Typescript doesn't add runtime type checks, you still have to do that yourself if you're accepting multiple types (in this case function | undefined). So no. ... unless you used a type of filter callback, and instead allowed just an object / string to be passed in? interface OptionsForSomething { filter: ((x: string) => boolean) | string; }
🌐
Scaler
scaler.com › home › topics › typescript › optional chaining and nullish coalescing in typescript
Optional Chaining and Nullish Coalescing in TypeScript - Scaler Topics
May 4, 2023 - In the preceding example, we developed a function that returns the first member of a list (assuming the list is represented as an array) if defined, else undefined. The question mark following the name of the list indicates that it is an optional parameter. As a result, its type is T[] | undefined. The two head calls will print 1 and undefined, respectively. When optional chaining in typescript is used in longer phrases, the short-circuiting it provides is limited to the three scenarios discussed above :
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-use-optional-chaining-with-arrays-and-functions-in-typescript
How to use Optional Chaining with Arrays and Functions in TypeScript ? - GeeksforGeeks
May 6, 2024 - type Approach3 = { username: string; ... This new approach involves utilizing optional chaining along with a ternary operator for more concise and flexible access to array elements and function calls....
🌐
egghead.io
egghead.io › lessons › typescript-use-the-optional-chaining-operator-in-typescript
Use the Optional Chaining Operator in TypeScript | egghead.io
[5:55] We can now call this function in our optional property chain by stating the name and then the syntax question mark dot, and parentheses for calling the function. Now this syntax might look funky to you initially, but you are going to ...
Published   February 17, 2021
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript optional chaining
TypeScript Optional Chaining | Guide to TypeScript Optional Chaining
April 20, 2023 - Optional chaining has two other operations included: Optional element access, for accessing non-identifier properties such as strings and numbers · Optional call, for calling expressions conditionally if they are not undefined or null
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-optional-chaining-works-in-typescript
How optional chaining works in TypeScript ? - GeeksforGeeks
March 22, 2022 - TypeScript Optional Chaining is the process of searching and calling variables, methods, parameters that might be nil in existence.
🌐
Marius Schulz
mariusschulz.com › blog › optional-chaining-the-operator-in-typescript
Optional Chaining: The ?. Operator in TypeScript — Marius Schulz
September 11, 2021 - TypeScript 3.7 added support for ... use this operator to descend into an object whose properties potentially hold the values null or undefined without writing any null checks for intermediate properties....
🌐
Medium
medium.com › inside-rimeto › optional-chaining-in-typescript-622c3121f99b
Optional Chaining in TypeScript. Traversing tree-like structures safely… | by Neville Bowers | Inside Rimeto | Medium
December 4, 2019 - Invoking this function on an OCType object will effectively "dereference" the object value at the current position in the chain. If no data exists at the current position (e.g., invalid path), the data accessor returns either (a) undefined or ...
🌐
LogRocket
blog.logrocket.com › home › optional chaining and nullish coalescing in typescript
Optional chaining and nullish coalescing in TypeScript - LogRocket Blog
June 4, 2024 - Nonetheless, there’s an important difference between the if and the chain of ?. calls. The former is short-circuited while the latter is not. This is intentional, as the new operator does not short-circuit on valid data, such as 0 or empty strings. The last use of ?. is optional element access, allowing us to access non-identifier properties, if defined: function head<T>(list?: T[]) { return list?.[0]; // equivalent to // return (list === undefined) ?
🌐
TutorialsPoint
tutorialspoint.com › how-optional-chaining-works-in-typescript
How optional chaining works in TypeScript?
In this article, you will understand how optional chaining works in TypeScript. Optional chaining operator (?.) accesses an object’s property. If the objects property is null or not defined, it returns ‘undefined’. Let us first understand what TypeSc
🌐
GitHub
github.com › tc39 › proposal-optional-chaining
GitHub - tc39/proposal-optional-chaining
Swift: Optional Chaining — optional property, method, or subscript call, in read and write access. CoffeeScript: Existential operator — existential operator variant for property accessor, function call, object construction (new a?()).
Starred by 4.9K users
Forked by 72 users
Languages   HTML 97.2% | Shell 2.8%
🌐
Valentino G.
valentinog.com › blog › chaining
Using Optional Chaining in TypeScript and JavaScript
February 7, 2020 - What can we do to protect our code from these kind of errors? Let's see how optional chaining helps. Let's get TypeScript to check our code. Rename optional_chaining.js to optional_chaining.ts.
🌐
DEV Community
dev.to › macsikora › what-is-wrong-with-optional-chaining-and-how-to-fix-it-3nno
What is wrong with optional chaining and how to fix it - DEV Community
May 1, 2020 - That is not the end. Lets say I do have a function which I want to call on the property which is a result of the optional chaining. We can do that by previous && operator.
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-optional-chaining
How to Use JavaScript Optional Chaining
For example, let's change getLeading() function to return "Unknown actor" when there are no actors in the movie object: ... You can use optional chaining in the following 3 forms. The first form object?.property is used to access a static property: ... What's interesting about the optional chaining operator is that as soon as a nullish value is encountered on its left-hand side leftHandSide?.rightHandSide, the evaluation of the right-hand side accessors stops. This is called short-circuiting.
🌐
InfoWorld
infoworld.com › home › software development › typescript 3.7 arrives with optional chaining
TypeScript 3.7 arrives with optional chaining | InfoWorld
November 6, 2019 - Also included are two other operations: optional element access, for accessing non-identifier properties such as numbers and arbitrary strings, and optional call, for conditionally calling expressions if they are not null or undefined.