I’ve done a fair amount of JavaScript, here and there, and have written some TypeScript, too. But I’ve never actually started anything in TypeScript. Attempting a basic “hello world” in TypeScript turned out to be completely non-trivial, so this should help you.
Editor
I use Visual Studio Code.
Node
Setup node.js. I use nvm, whatever recent version of node and npm.
Ts-Node
TypeScript comes with an execution and REPL for node.js called ts-node.
Hello World
Create a file called hello.ts
. It’s JavaScript disguised as TypeScript for now.
Run it.
Underneath ts-node
this file got transpiled into JavaScript with tsc hello.ts
, the TypeScript compiler and executed. We can do this ourselves as follows.
Asynchronous Code
Let’s write a basic function that returns a value.
Make it asynchronous by returning a promise. You can run this with node async-function.js
.
Now we can rewrite this in TypeScript and use ES6 fat arrows. We add a type to f()
, expressing that the function must promise (return a Promise
) to return a string
. We mark everything asynchronous with async
, and use await
to wait for the asynchronous f
to finish.
The async
/await
pair is a lot nicer than having to use then
and having types removes all the guesswork from what functions return.
If you just run this with ts-node
without any arguments you will have a few issues.
These are fixed by calling the compiler with --lib es6
.
These are fixed by including a target library with --lib dom
.
Both arguments are required to run our code with ts-node
.
Config
Having to specify -O
with a JSON for every invocation of ts-node
is annoying. You can create a file called tsconfig.json
with this configuration.
It gets loaded automatically.
Adding Lodash
Better, create a package.json
and run npm install
.
This creates node_modules/lodash
and node_modules/@types/lodash
, which includes lodash TypeScript definitions.
Now that we have dependencies we can introduce some project structure. The code should live in src/index.ts
.
And an updated tsconfig.json
.
Run it.
Links
The code for this post can be found here.