DEV Community

Javel Rowe
Javel Rowe

Posted on

TAWIL: How to use Typescript ️

Today at work I learnt how to do the above in preparation for a project where I want to use type-driven design. Let's fire up VS Code and take the four steps needed to layer a type-system onto a JS project.

Step 1 - Ingredients: Sugar, spice and everything niceee

In addition to Node.js and VS Code, we just need to sprinkle npm init onto our command line. After initializing our environment, we add a dash of npm install typescript then finish up with a side of npx tsc -v for good measure. After the smoke clears, you should see something like this appear:

Version 4.1.3
Enter fullscreen mode Exit fullscreen mode

It may not be those exact version but it means we got typescript onto our system successfully.

Step 2 - Where do we put all this stuff?

We're going to end up summoning a regular degular javascript file with the concoction we created above so let's setup a space for it to appear!
In your command line, type npx tsc --init. A file titled tsconfig.json should appear. At line 17 in the file, remove comments from outDir then add "./test" as the key value.

Step 3 - It's a bird, it's a plane..... it's TYPESCRIPT!

Now, let's exercise the strength in our typing fingers and bring some typescript into existence! Create a file titled test.ts then add this bit of code:

let message:string = "Hello world!";
console.log(message);
Enter fullscreen mode Exit fullscreen mode

Here message:string we are setting the type of the variable message to string. From now til the end of time it will only accept strings.

Step 4 - Compile!

The final step is to compile the file. This will output a regular javascript file that we can then use like usual. In your terminal, run npx tsc. A new file titled test.js should appear in the test folder we had created earlier.

Just like that, you've used typescript! Here's some extra enough to get you up and running:

Typescript for JS Programmers

Top comments (0)