TypeScript:SyntaxError:控制台中的“意外令牌”消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39775112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: SyntaxError: "Unexpected token" message in console
提问by venber
Why this code doesn't work?
为什么这段代码不起作用?
I have the following app.ts
我有以下 app.ts
var a = 1;
var b = 3;
console.log(`Before a = ${a}, b = ${b}`);
[a, b] = [b, a];
console.log(`After a = ${a}, b = ${b}`);
when I try to run it with
当我尝试运行它时
node app.ts
节点应用程序
I have the next:
我有下一个:
[a, b] = [b, a];
^
ReferenceError: Invalid left-hand side in assignment
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
But I expect:
但我希望:
Before a = 1, b = 2
After a = 2, b = 1
TypeScript Version 1.8.10
打字稿版本 1.8.10
回答by Martin
You need to compile your code first.
您需要先编译代码。
tsc app.ts
Then run it with
然后运行它
node app.js
回答by Quentin
You are running the code with NodeJS. You aren't transpiling it from TypeScript to JavaScript, so you are trying to treat your TypeScript as if it were JavaScript.
您正在使用 NodeJS 运行代码。您没有将它从 TypeScript 转换为 JavaScript,因此您试图将 TypeScript 视为 JavaScript。
That might be OK, since TypeScript is a superset of JavaScript. In this particular case, your code also happens to be valid JS.
这可能没问题,因为 TypeScript 是 JavaScript 的超集。在这种特殊情况下,您的代码也恰好是有效的 JS。
The destructuring assignmentsyou are trying to use are an ES6 feature that are only supported in NodeJS from 6.5 onwards.
您尝试使用的解构赋值是一项 ES6 功能,仅在 NodeJS 6.5 及以后的版本中受支持。
You need to upgrade NodeJS to a newer version.
您需要将 NodeJS 升级到更新的版本。
Alternatively, transpile the TypeScript to ES5 with tsc app.ts
或者,使用以下命令将 TypeScript 转换为 ES5 tsc app.ts