TypeScript 中的声明或语句预期错误

Muhammad Ibrahim Alvi 2022年5月18日
TypeScript 中的声明或语句预期错误

本教程解释了 JavaScript 或 TypeScript 中的 Declaration or statement expected 错误以及编译器抛出此错误的原因。将讨论此错误的所有主要原因,以及如何在开发人员社区中避免它。

JavaScript 或 TypeScript 中的预期的声明或语句错误

当我们在代码中出现语法错误时,就会出现 JavaScript 或 TypeScript 中的 Declaration or statement expected 错误。

例如,考虑使用错误的语法对文件中的对象进行解构,使用错误的名称导出文件中的模块,或者括号丢失或不一致。

考虑以下代码示例,其中由于代码中的语法错误而出现不同的 Declaration or statement expected

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

上面的代码产生以下错误,写在下面。

//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 错误。

let val: number;

const obj = {
  val: 1,
};

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

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

上面的代码产生以下输出。

声明或声明预期错误 - 解决方案

在导出之前已声明的内容时,有时也会出现预期声明或声明错误。每当需要执行此操作时,将导出用花括号括起来。

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