I use Visual Studio Code.
TypeScript comes with an execution and REPL for node.js called ts-node.
Create a file called
tsc hello.ts, the TypeScript compiler and executed. We can do this ourselves as follows.
Let’s write a basic function that returns a value.
Make it asynchronous by returning a promise. You can run this with
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.
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
These are fixed by including a target library with
Both arguments are required to run our code with
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.
Better, create a
package.json and run
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
And an updated
The code for this post can be found here.