Declaration or Statement Expected Error in TypeScript

Muhammad Ibrahim Alvi Apr 04, 2022
Declaration or Statement Expected Error in TypeScript

This tutorial explains the Declaration or statement expected error in JavaScript or TypeScript and why the compiler throws this error. All the major reasons for this error will be discussed, and how it can be avoided among the developer’s community.

Declaration or statement expected Error in JavaScript or TypeScript

The Declaration or statement expected error in JavaScript or TypeScript occurs when we have a syntax error in the code.

For instance, consider the destructuring of an object in the file with the wrong syntax, exporting a module in the file with the wrong name, or having a missing or inconsistent bracket.

Consider the following example of a code where a different Declaration or statement expected occurs due to the syntax error inside the code.

let oneData: number;

const obj = {
  val: 1,
};

// 1. ⛔️ Parsing error: Declaration or statement expected.
{ oneData } = obj; // 👈️ this must be wrapped in parenthesis

const sumObj = (a: number, b: number) => a + b;

// 2. ⛔️ Error: Parsing error: Declaration or statement expected.eslint
export sumObj // 👈️ should be export {sum}

// 3. Make sure you're not using reserved words
const caseVal = 'hello world' // 👈️ case is reserved word

The above code produces the following errors, which are written below.

//output or errors
Variable 'one' is used before being assigned.

Declaration or statement expected. This '=' follows a block of statements, so if you intend to write a destructuring assignment, you might need to wrap the whole assignment in parentheses.

Declaration or statement expected.

'case' is not allowed as a variable declaration name.

Variable declaration expected.

Variable declaration expected.

Declaration or statement expected error

Consider the following code, compiled correctly with no Declaration or statement expected errors.

let val: number;

const obj = {
  val: 1,
};

// ✅ OK
({ val } = obj); // 👈️ this must be wrapped in parenthesis

console.log(val); // 👉️ 1

The above code produces the following output.

Declaration or statement expected error - solution

Declaration or statement expected error also arises sometimes when exporting something that has been declared previously. Whenever this needed to be done, wrap the export in curly braces.

const objSum = (a: number, b: number) => a + b;

// ✅ OK
export { objSum };
Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn