TypeScript setup

TypeScript setup

Node.js can execute .ts files if those do not contain any TypeScript specific syntax. However, the running code like the following example:

interface Movie {
  title: string
  year: number
}

Yields the following error

[moreillon@fedora ts-test]$ node index.ts
/home/moreillon/node/ts-test/index.ts:3
interface Movie {
          ^^^^^

SyntaxError: Unexpected identifier
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Here, TS code must be converted into plain JS. This is achieved using the TypeScript Compiler, or TSC. The compiler can be installed using npm:

npm i -D typescript

With the typescript module installed, tsc can be invoked as

npx tsc myFile.ts

This results in the file myFile.js, which is a compiled version of myFile.ts. myFile.js can then be run as a normal JavaScript file using the node command.

ts.config.json

The configuration of the TypeScript compiler is achieved using a file called ts.config.json. Creating such file can be done using the following tsc command:

npx tsc --init

ts-node

Having to invoke tsc each time one wants to run TypeScript code can be time-consuming. To solve this problem, the ts-node module can be used. ts-node runs .ts code just like the node command runs .js files. It can be installed using npm:

npm i -D ts-node

And invoked using npx:

npx ts-node