Simple TypeScript playgrounds via node --watch

[2025-02-25] dev, typescript
(Ad, please don’t block)

Now that Node.js has built-in support for TypeScript, we can use it as the foundation of simple playgrounds that let us interactively explore TypeScript code.

A simple playground  

This is the basic approach:

  • We create a file playground.mts
    • The filename extension is .mts so that we don’t need a package.json file to tell Node.js that .ts means ESM module.
  • We run the following command in a terminal:
    node --watch ./playground.mts
    
  • We edit playground.mts. Whenever we save it, Node.js re-runs it and shows its output.

Suppressing “ExperimentalWarning”  

At the moment, Node’s built-in support for TypeScript still prints the following warning every time we use it:

ExperimentalWarning: Type Stripping is an experimental feature and
might change at any time

We can switch off that warning via the CLI option --disable-warning=ExperimentalWarning – e.g.:

node --disable-warning=ExperimentalWarning --watch ./playground.mts

More configuration: tsconfig.json and package.json  

Alas, we often need two additional files:

  • A tsconfig.json with our preferred settings
  • A package.json with "type":"module" so that we can use the filename extension .ts.

I have created the GitHub repository nodejs-type-stripping where both are already set up correctly.

Running copied TypeScript code via Node.js  

For simple experiments, it can be enough to simply copy TypeScript code and run it via Node.js:

«paste-command» | node --input-type=module-typescript

«paste-command» depends on your operating system:

  • MacOS: pbpaste
  • Windows PowerShell: Get-Clipboard
  • Linux: There are many options. wl-clipboard worked well for me on Ubuntu, where I installed it via the App Center (snap).

On macOS, I added the following line to my .zprofile:

alias pbts='pbpaste | node --input-type=module-typescript'

Further reading