打字稿类型注释抛出 'Unexpected token ":"'

Typescript Type Annotations throws 'Unexpected token ":"'

我试图用类型注释我的变量,但是当 运行 代码时它只是给出一个错误:

let foo: number = 23;
console.log( foo );

// let foo: number = 23;
          ^

// SyntaxError: Unexpected token ':'
// [90m    at Object.compileFunction (node:vm:352:18)[39m
// [90m    at wrapSafe (node:internal/modules/cjs/loader:1031:15)[39m
// [90m    at Module._compile (node:internal/modules/cjs/loader:1065:27)[39m
// [90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)[39m
// [90m    at Module.load (node:internal/modules/cjs/loader:981:32)[39m
// [90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)[39m
// [90m    at Function.executeUserEntryPoint [as runMain] // (node:internal/modules/run_main:79:12)[39m
// [90m    at node:internal/main/run_main_module:17:47[39m

您有两个选择:

先用tsc myfile.ts编译成纯JS,运行用node myfile.js编译成JS文件。

npm install ts-node 可以让您 运行 TS 文件就像 运行 JS 文件一样:ts-node myfile.ts