Borislav Hadzhiev
Wed Mar 16 2022·2 min read
Photo by Redd
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.
Here are 3 examples of how the error occurs.
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.
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.
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.
// ✅ 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.
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.
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.