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 };
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。