typescriptinterface

Typescript Interface SyntaxError: Unexpected identifier at interface name


I'm new to Typescript and I'm still figuring my way out, I searched this problem everywhere otherwise I wont be asking this question. I have a SyntaxError at the interface name and don't know how to solve it. Here is my short code:

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}`)
    }
}

and this is the error:

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

Solution

  • There is no Typescript syntax error in your code. You can see that it has no errors at all in the Typescript playground.

    But from the stacktrace it appears that you are trying to execute the Typescript directly from Node.js as if it were Javascript. That would explain the error because Javascript does not support interfaces; it's a Typescript thing.

    You can compile or transpile the *.ts files to *.js using a tool like tsc, esbuild, deno or bun.

    Or you can run Typescript directly using tsx or ts-node. Node.js has recently (Node v22.6.0, 2024) added experimental support for running Typescript directly like this:

    node --experimental-strip-types example.ts
    

    I can't give you a more specific answer without you providing more info about your setup, the command you executed that produced that error, etc.