【问题标题】:Typescript Interface SyntaxError: Unexpected identifier at interface nameTypescript Interface SyntaxError:接口名称处的意外标识符
【发布时间】:2021-07-04 02:39:09
【问题描述】:

我是 Typescript 的新手,我仍在寻找出路,我到处搜索这个问题,否则我不会问这个问题。我在接口名称处有一个 SyntaxError 并且不知道如何解决它。这是我的短代码:

interface Cars {
    name:string
    model:string
    topSpeed:number
    colors:string[]
    speedPrint(carSpeed:number):void
}

class BMW implements Cars{
    name = 'BMW X6'
    model = 'S'
    topSpeed = 320
    colors = ['cobalt red','phantom blue','white']
    speedPrint(topSpeed:number):void{
        console.log(`My car top speed is ${topSpeed}`)
    }
}

这是错误:

app.ts:1
interface Cars {
          ^^^^

SyntaxError: Unexpected identifier
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

【问题讨论】:

  • 您需要提供更多信息。请参阅我的部分答案。

标签: typescript interface


【解决方案1】:

我遇到了同样的错误,但我执行了以下操作并且有效:

  1. 通过在终端npm install -g typescript 中键入此命令来安装 ts
  2. 此类型后tsc filename.ts
  3. 然后node ./file.js(不是ts)看看终端会发生什么

【讨论】:

    【解决方案2】:

    您的代码中没有 Typescript 语法错误。你可以看到it has no errors at all in the Typescript playground

    但是从堆栈跟踪看来,您正在尝试将 Typescript 直接作为 Javascript CommonJS 模块执行?这可以解释错误,因为 Javascript 不支持接口;那是打字稿的事情。

    如果您不提供有关您的设置、您执行的导致该错误的命令等的更多信息,我将无法为您提供更多帮助。

    【讨论】:

    • 感谢您的解释,我试图在 VS Code 中获取日志,就像我正在关注的教程一样,但我想我错过了一些东西。
    • np。我使用 Webstorm,所以你提供的信息对我来说并不明显。顺便说一句,我不介意你也赞成我的回答;)
    • 这是我在阅读您的回答后首先想到的,但我做不到,因为我还没有 15 的声望。
    【解决方案3】:

    我认为你可以运行而不是运行 node .ts

    1. tsc .ts
    2. 节点.js 因为当您运行第一个命令时,它会生成与您的 typescript 文件对应的等效 javascript 文件。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2017-10-11
      • 1970-01-01
      • 2018-03-09
      相关资源
      最近更新 更多