Fix - Declaration or statement expected error in TypeScript

avatar

Borislav Hadzhiev

Wed Mar 16 20222 min read

banner

Photo by Redd

Fix - Declaration or statement expected error in TypeScript #

The "Declaration or statement expected" error occurs when we have a syntax error in our code, e.g. when destructuring, exporting, or have a missing or inconsistent bracket. To solve the error, make sure to correct any syntax errors in your code.

declaration or statement expected

Here are 3 examples of how the error occurs.

index.ts
let one: number; const obj = { one: 1, }; // 1. ⛔️ Parsing error: Declaration or statement expected. { one } = obj; // 👈️ this must be wrapped in parenthesis const sum = (a: number, b: number) => a + b; // 2. ⛔️ Error: Parsing error: Declaration or statement expected.eslint export sum // 👈️ should be export {sum} // 3. Make sure you're not using reserved words const case = 'hello world' // 👈️ case is reserved word

The first example shows how the error occurs when destructuring. To be able to destructure and reassign an already-declared variable, wrap the statement in parenthesis.

index.ts
let one: number; const obj = { one: 1, }; // ✅ OK ({ one } = obj); // 👈️ this must be wrapped in parenthesis console.log(one); // 👉️ 1

You might also get the error when exporting something that you previously declared. When you declare something and export it on another line, wrap the export in curly braces.

index.ts
const sum = (a: number, b: number) => a + b; // ✅ OK export { sum };

We are basically exporting an object that contains one or more named exports.

You don't have to use curly braces if you export and declare the variable in a single statement.

index.ts
// ✅ OK export const sum = (a: number, b: number) => a + b;

Another common cause of the error is having a missing bracket somewhere in your code.

Most code editors have extensions that group parenthesis and curly braces in different colors to make it more obvious when there is a missing one. An example being Bracket Pair Colorizer extension in VSCode.

Carefully check your code for a missing curly brace, parenthesis, square bracket, etc.

If you use IntelliJ as your IDE and are getting the "Declaration or statement expected" error, try closing and re-opening the file or restarting your IDE as it sometimes glitches.

Make sure you aren't using any reserved words when declaring variables.

index.ts
const case = 'hello world' // 👈️ case is reserved word

Words like case, class, Error, etc are reserved, so we're not allowed to use them as variable names.

Use the search field on my Home Page to filter through my more than 1,000 articles.