Optional chaining arrays in Ionic Framework (typescript) throws error

255 views Asked by At

I want to use optional chaining in my Ionic project but I receive errors even though I use the correct notation.

My code

// Get Array (might be empty)
const array = await getArray();

return array?.[0];

My compiler throws 3 errors:

ERROR in path/to/file.ts:12:34 - error TS1109: Expression expected.
[ng] 12         return array?.[0];
[ng]                         ~
[ng] path/to/file.ts:12:34 - error TS1003: Identifier expected.
[ng] 12         return array?.[0];
[ng]                          ~
[ng] path/to/file.ts:12:34 - error TS1005: ':' expected.
[ng] 12         return array?.[0];
[ng]                            ~

I don't understand why there is an error. According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#array_item_access_with_optional_chaining the syntax would be correct. My IDE (vscode) also doesn't throws me an error

Array item access with optional chaining You can use bracket notation for optional chaining on arrays:

const arr = ['a', 'b', 'c', 'd']; let arrayItem = arr?.[42];

1

There are 1 answers

0
Ljonja On

My typescript-version just seemed to be too old (3.4.3). Optional chaining was introduced in 3.7 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html), so it makes sense that it does not work in my old version.

I just assumed that my project was relatively up to date but turns out it wasn't.