This chapter gives tips for quickly trying out TypeScript.
The TypeScript Playground is an online editor for TypeScript code. Features include:
.d.ts
).
The Playground is very useful for quick experiments and demos. It can save both TypeScript code snippets and compiler settings into URLs, which is great for sharing such snippets with others. This is an example of such a URL:
https://www.typescriptlang.org/play/?#code/«base64»
Many social media services limit the characters per post, but not the characters per URL. Therefore, we can use Playground URLs to share code that wouldn’t fit into a post.
node --watch
This is the basic approach:
We create a file playground.mts
.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.
Note that Node.js does not type-check the code. But the type checking we get in TypeScript editors should be enough in this case (since we are only working with a single file).
tsconfig.json
and package.json
For more sophisticated experiments, we may need two additional files:
tsconfig.json
with our preferred settings
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.
--watch
Watches a file and its imports for changes and re-runs the file whenever that happens.
--watch-path
Overrides the default of watching the imports and tells Node.js which files to watch instead.
--watch-preserve-output
Disables the clearing of the console before the file is re-run.
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:
pbpaste
Get-Clipboard
On macOS, I added the following line to my .zprofile
:
alias pbts='pbpaste | node --input-type=module-typescript'