0

i have a sample code for generics in typescript.

const variab = function identity<Type>(arg: Type): Type {
    return arg;
  }

  let output = variab<string>("myString");
  console.log(output);

but in run have this error:

D:\practice2\index.ts:21 const variab = function identity(arg: Type): Type { ^

SyntaxError: Unexpected token '<' at internalCompileFunction (node:internal/vm:74:18) at wrapSafe (node:internal/modules/cjs/loader:1141:20) at Module._compile (node:internal/modules/cjs/loader:1182:27) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47

Node.js v18.13.0

1 Answer 1

2

I think you are using the native js compiler to run the ts file. My best guess is that you're just using node index.ts to run your file. But unfortunately, it doesn't work that way.

You'll need this npm package ts-node to run your typescript files. You can install the module globally by running the following two commands

npm install -g typescript
npm install -g ts-node

then you can run your file with ts-node index.ts and it will work fine. Else you can just run it inline via npx ts-node index.ts and it will produce the same result. The code that you've written works perfectly fine and it produces the desired output. You can check that on the Typescript Playground

I recommend you to watch some beginner typescript tutorials on YouTube before getting started with TypeScript as they really help a lot.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer. run this code by npx ts-node index.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.