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