Last updated: Feb 28, 2024
Reading timeยท2 min
The "Declaration or statement expected" error occurs when we have a syntax error in our code, e.g. when destructuring, exporting, or when we 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 parentheses 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 = 'bobbyhadz.com' // ๐๏ธ 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 parentheses.
let one: number; const obj = { one: 1, }; // โ OK ({ one } = obj); // ๐๏ธ this must be wrapped in parentheses console.log(one); // ๐๏ธ 1
I've also written a detailed tutorial on destructuring object parameters in functions.
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.
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 try restarting your IDE as it sometimes glitches.
Make sure you aren't using any reserved words when declaring variables.
const case = 'bobbyhadz.com' // ๐๏ธ case is reserved word
Words like case
, class
, Error
, etc, are reserved, so we aren't allowed to
use them as variable names.