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?.();

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
🌐
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....
🌐
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....
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
🌐
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
🌐
Convex
convex.dev › core concepts › object-oriented programming (oop) › optional chaining
Optional Chaining | TypeScript Guide by Convex
Pay attention to TypeScript type checking when using optional chaining, as the resulting type will include undefined as a possibility. This often requires the nullish coalescing operator to ensure type safety. Optional chaining shines when working with external data sources like API responses, where the structure may vary or contain missing fields. // Fetching user data from an API async function getUserDetails(userId: string) { try { const response = await fetch(`https://api.example.com/users/${userId}`); const data = await response.json(); // Safely access nested properties with optional chaining const userLocation = { city: data?.address?.city ??
🌐
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.
🌐
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.