DEV Community

Cover image for How to Start Using Typescript
Saji Wang for Codesphere Inc.

Posted on

How to Start Using Typescript

One of the most significant innovations in web development in the past decade has been the shift towards Typescript. As more and more employers are looking to limit tech debt, learning Typescript is becoming essential to landing a job as a web developer.

While dynamically-typed languages make life easier for the developer in the short run, it can become the reason for unwanted bugs that aren’t caught until runtime. We can avoid this problem with the help of TypeScript. Let’s take a closer look

What is TypeScript?

In the simplest of terms, TypeScript is a superset of JavaScript. This implies that while conventional JavaScript code will work the same in TypeScript, it will also have an extra set of features making our code cleaner and better. TypeScript uses a compiler known as tsc to check for errors in the code and generates(technically known as emitting) the JavaScript equivalent for use in web applications.

TypeScript can also be referred to as a statically typed version of Javascript but we would be overlooking a plethora of other features that TypeScript has to offer. In the next section, we take a look at some of the advantages of using TypeScript.

Advantages of using TypeScript

TypeScript has the following features to offer:

  • Strong typing - TypeScript places a lot of emphasis on the type of variables being used in the code. If the variable is assigned a value that doesn’t match the type, the TypeScript compiler tsc shows an error.

  • Object-oriented features - TypeScript introduces a whole lot of object-oriented concepts that help make the code easier to manage.

  • Compile-time errors - Since there is a compilation step involved, most of the errors get caught at compile time instead of run time.

  • Emitting with errors - TypeScript will inform the developer about the potential errors in the code but it will make sure to generate the equivalent JavaScript to keep the development process running. The final decision is up to the developer.

  • Great tooling - TypeScript provides access to a lot of great tools which help in editing, error checking, etc. as you type your code.

Let’s take a look at how we can do that with this simple demo that highlights a few of the above-mentioned features as well.


How to use TypeScript

Before moving on to the main demo and looking at a scenario similar to real-world applications let’s go through the basic building blocks of TypeScript first.

The Primitives

The usual JavaScript primitives number, string, and boolean are present here as well. In addition, you can do type annotation to fix the type of the variable at the time of declaration. TypeScript also infers the type when the variable is already defined. TypeScript also has a special type called any which is used to avoid type checking errors on a particular variable.

Functions & Objects

Functions also follow a similar pattern for type annotation where the parameter types are mentioned the same as for regular variables while the return type is mentioned between the parentheses and curly braces. Anonymous functions use a TypeScript feature called contextual typing where the type is inferred from the context of the function usage.

Objects are almost the same as JavaScript except for the fact that the types get inferred for every property inside it. Accessing properties that don’t exist gives a compiler error.
TypeScript gives us the option of creating objects using type aliases (cannot be extended) or interface(can be extended).

Types on top of JavaScript

TypeScript adds some of its own types as well.

  • Tuples are arrays that have their element types already annotated so we cannot save any other type on that location.

  • Enum’s involve giving human-readable identifiers to numbers/strings. This makes it easier to manage code and avoid the hassle of memorizing fixed values.

  • Unions allow you to use the same variable with multiple types of data without worrying about type errors. This is achieved by annotating multiple types on the same variable using the pipe(|) symbol.


Using Typescript in a Project

Since we are now familiar with the basic blocks of TypeScript, let’s build a small application and see how we can use it to write better code. This application will take two numbers as input and log their sum onto the browser console.

1. Before we create the demo we need to set up TypeScript on our machine. Follow the instructions below to set up TypeScript on your machine.

https://www.typescriptlang.org/download

2. Create two files index.html and app.ts. Make sure to call app.js inside the HTML file. We will use the app.ts to emit the app.js file for use in the browser environment.

3. Create the index.html as shown below. This file will contain two inputs for numbers and one add button. We will log the sum of the two numbers onto the console.

4. Inside the app.ts file add the following code. This TypeScript code emits the JavaScript file which we will use to take the values from the DOM, adds them, and logs the result on the browser console.

5. To emit the app.js, go to your terminal and run the following command to compile the app.ts:

tsc —target es2015 app.ts

Make sure to run this inside the folder where your app.ts is located. As mentioned earlier, tsc is the TypeScript compiler. This will compile our app.ts and emit app.js and generate error messages in case of any errors.

The target flag is required to make sure the JavaScript emitted follows the ES2015 standard. By default, tsc emits ES3 standard which is pretty old.

6. If you are using the code given above, it should work straight away. To see TypeScript in action, you need to remove the type annotations. Every time you make a change you need to compile the app.ts again. Changes that don’t conform to TypeScript will generate errors. It will still, however, generate the JavaScript and you can even run it but it might give unexpected results.


We’ve just scratched the surface with what TypeScript has to offer! The biggest thing that you can do to get more familiar with typescript is begin to use it in your passion projects. The more comfortable you are working with Typescript, the easier time you’ll have using it to write clean code at your company.

Looking for a place to deploy that clean code? Check out Codesphere, the only cloud provider that makes deploying in the cloud as easy as testing locally.

Happy Coding!

Discussion (20)

Collapse
lukeshiru profile image
Luke Shiru

A tip I always give: "Use types when TS doesn't infer them". Using your

// No need for `!` (you should avoid ! as much as possible in TS btw)
const number1 = document.querySelector("#num1") as HTMLInputElement;
const number2 = document.querySelector("#num2") as HTMLInputElement;

// No need to type the output of this function, its inferred
const addNum = (num1: number, num2: number) => num1 + num2;

// You could also use default values and infer the params as well
const addNum = (num1 = 0, num2 = 0) => num1 + num2;

document.querySelector("#add-btn").addEventListener("click", () =>
    console.log(
        // Remember to always use the radix parameter with `parseInt`
        addNum(parseInt(number1.value, 10), parseInt(number2.value, 10)),
    ),
);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
karfau profile image
Christian Bewernitz

I would say that ! is as dangerous as as Xyz.

Basically you are saying: "I know what I'm doing, leave me alone."

But typescript only ever checks at compile time, never at runtime, so when you get back something else, a lot of assumptions in your code will go away.

It's better to check for undefined/null values if typescript tells you.

Which is also very convinient by using the operators introduced for that, like ?., ?? etc.

Collapse
lukeshiru profile image
Luke Shiru

Indeed. The good thing about as is that is more explicit and it gives you errors if the types aren't compatible (and to override it you have to do even more as unknown as Type). But yeah, good points!

Collapse
api_patrol profile image
Pawel Duda

WHat does "!" mean here?

Collapse
lukeshiru profile image
Luke Shiru

Is a shorthand for the NonNullable type. Is kinda like saying to the compiler: "I know this will never be null or undefined, but ideally you should actually check for that instead of forcing it with !.

Collapse
uponthesky profile image
UponTheSky • Edited on

Thanks for the good article.
I'm just wondering, that how you set up your own tsconfig.json?
It always gives me a big headache whenever I start my own ts-related projects or deploy them with Dockerfile.

I would like to listen to your opinion. Thanks!

Collapse
liorbd profile image
Lior Ben-David

Hi!

I tend to defer to Typescript's base configs. They have ones that you can take for vanilla JS, node, or react native projects:

typescriptlang.org/docs/handbook/t...

From there, I just adjust the config out of necessity, but these base configs tend to be sufficient.

Collapse
uponthesky profile image
UponTheSky

Thanks for the reply! Have a nice day!

Collapse
karfau profile image
Christian Bewernitz

I really like your careful introduction and it provides a way to use TS in the JS world.

But if you are curios about typescript without much hassle, try Deno.
It's really easy to get started and you don't have to transpile anything before being able to run TS code.
It even comes with a REPL ...

Collapse
sewangco profile image
Saji Wang Author

thanks for the feedback Christian! Much appreciated :)

Collapse
corinnedonon profile image
CorinneDonon

To run the TypeScript compiler, which one ran the npm command to install the TypeScript command on the terminal ?

surah taha for love marriage

Collapse
liorbd profile image
Lior Ben-David

Hi Corinne,

You can install typescript in an npm project with:

npm install typescript --save-dev

Collapse
jwp profile image
John Peters

Fantastic, 😊

Collapse
sewangco profile image
Saji Wang Author

Glad you enjoyed it!

Collapse
thenickest profile image
TheNickest

Nice :)

Collapse
gaurangjindal15 profile image
Gaurang jindal

Hello I am looking for a javascript and react js developer who can support in online hackathon which is going to conduct from 12th Jan.

In case you are interested please ping me. !!! its urgent !!!!

Collapse
nnivxix profile image
Hanasa

nice article for getting start using TS

Collapse
sewangco profile image
Saji Wang Author

thanks :)

Collapse
johnb8005 profile image
John B • Edited on

here's a typescript boilerplate for those wanting to try typescript quickly (<1min): github.com/nexys-system/boilerplat...

Collapse
luizc91 profile image
LuizC91

These terminal commands can be used directly in the Windows Terminal? If not, how can I adapt it to run without any problem?