'Typescript optional chaining error: Expression expected.ts(1109)
I am trying to do optional chaining in Typescript + React Native.
Let's say I have the following interfaces:
interface Bar {
y: number
}
interface Foo {
x?: Bar
}
and I try to run the following:
const test: Foo = {x: {y: 3}};
console.log(test.x?.y);
VSCode will show an error under the ?. saying the following: Expression expected.ts(1109)
Do you have any idea why this is happening or how should I fix it? Thanks.
Solution 1:[1]
TypeScript 3.7 has been released, but the stable VS Code uses an older version.
Try ? + Shift + p and choosing Select TypeScript Version. If it's not 3.7+, that's the issue. The easiest fix is to install the ms-vscode.vscode-typescript-next extension. It'll provide a nightly TypeScript version for VS Code to use (May require restarting VS Code FYI).
You'll want to remember to remove the extension when VS Code gets TypeScript 3.7+ by default.
See https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions for more details.
Solution 2:[2]
find the typescript version using the command
tsc -v
if it didn't match with the workspace version you need to install typescript latest version globally using following commands.
npm install typescript@latest -g
or
npm update [email protected] -g
Note: this is if you are working on a single project. If You are using multiple projects use the visual studio code extension . thanks @cameron
Solution 3:[3]
So I am on version 4.5.5 in 2022 and I encountered this. For me the problem was the wrong Prettier instaled in vscode, so if you get this error is worth checking the dropdown in the Output console who throws the error, typescript or prettier My issue in 2022
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Eduard |
