在TypeScript中定义函数时出现了意外的标记’:’错误。

huangapple go评论76阅读模式
英文:

Unexpected token ':' in Typescript when defining a function

问题

我一直在跟随Josh Goldberg的《学习TypeScript》中的示例。我在一个提供TypeScript函数定义的示例中遇到了问题:

//index.ts
let songLogger: (song: string) => void;

songLogger = (song) => {
    console.log(`${song}`);
}

songLogger("Heart of Glass");

执行代码片段时,出现以下错误:

PS C:\Typescript> node index.ts
C:\Typescript\index.ts:1
let songLogger: (song: string) => void;
              ^

SyntaxError: Unexpected token ':'
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1178:20)
    at Module._compile (node:internal/modules/cjs/loader:1220:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

你知道我做错了什么吗?我找不到这个语法错误的原因。

非常感谢!

英文:

I have been following examples included in "Learning Typescript" by Josh Goldberg. I am stuck in an example providing the definition of a function in Typescript:

//index.ts
let songLogger: (song: string) => void;

songLogger = (song) => {
    console.log(`${song}`);
}

songLogger("Heart of Glass");

When executing the snippet, getting the following:

PS C:\Typescript> node index.ts
C:\Typescript\index.ts:1
let songLogger: (song: string) => void;
              ^

SyntaxError: Unexpected token ':'
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1178:20)
    at Module._compile (node:internal/modules/cjs/loader:1220:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Do you know what I am doing wrong? I am not finding the culprit of the syntax error.

Thanks a lot

答案1

得分: 3

你正在使用node来运行TypeScript。你需要先将其转译为JavaScript。你可以使用tsc来完成这个过程。

英文:

You're using node to run the typescript. You have to first transpile to JavaScript. You can use tsc to do that.

huangapple
  • 本文由 发表于 2023年8月9日 05:05:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定