DEV Community

Cover image for Let's learn typescript: 001 - The basics
Carlos Giner
Carlos Giner

Posted on

Let's learn typescript: 001 - The basics

Why bother?

Typescript provides static type checking. What this means is that it's capable of predicting the errors based on the data type before running the code.

Even if the code appears to be valid javascript, typescript would decide to throw some error if it makes no sense or has a lack of constraints. For example, the famous value assignment to a property that doesn’t exist on a given object.

const item = { 
    id: 123,
    name: 'toaster'
}

item.price = 15; 
Enter fullscreen mode Exit fullscreen mode

Error: Property 'price' does not exist on type '{ id: number; name: string; }'.

Also, typescript is useful to catch other unhandled bugs by javascript, like typos, uncalled functions, or even basic logic errors, like unreachable code. See the example below.

const value:string = Math.random() < 0.5 ? "yes" : "no";
if (value !== "yes") {
  // ...
} else if (value === "no") {
  // Oops, unreachable
}
Enter fullscreen mode Exit fullscreen mode

Error: This comparison appears to be unintentional because the types '"yes"' and '"no"' have no overlap.

Typescript also will enable some very useful tooling, like code completion on the IDE.

The compiler

Typescript comes with a compiler to transform the useful, understandable, human-coherent type-safe code, into...well, plain javascript. To do this first install the compiler.

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

And just type tsc filename.ts.The compiler by default will transform it to ES3 (extremely old javascript), but we could change this by passing the flag: β€” target es2015. You should see a new file with the same name but with a .js extension in your working directory. This is the output of the compiler.

In the next chapters, we will go through the core concepts and other β€œfun” kinds of stuff.

Top comments (0)