Getting Started With TypeScript
Chinmay Mhatre
Posted on August 9, 2022
I'll proceed with the blog assuming you have previously worked with JavaScript. Knowing JavaScript would have you catch on to TypeScript concepts pretty easily.
Typescript has gained a lot of popularity over the years since it was made.
credits: The State of the Octoverse
Looking at issues you might run into in JavaScript
Let's start with a simple problem. Say we have a object that has these properties.
const person = {
name: 'John',
age: 30,
hobbies: ['Sports', 'Cooking']
}
After writing plenty of code we wanted to access a property of this object. We forgot the object doesn't have a property called "lastName" but we tried to access it anyways.
const lastName = person.lastName;
JavaScript won't throw an error but it will return undefined
. Now imagine, the variable getting passed through multiple layers of functions .
Locating the point of error would drain the life of our finitely mortal life.
We can solve this problem by using TypeScript.
being able to access a variable not present.
multiple null.
fixes JavaScript problems with types.
Types
Types are basically the kind of data that a variable can hold. Some primitive types of types are: Integers, Strings etc.
If anyone comes from a C++, C or a Java background, they would know about types.
In JavaScript when we declare a variable
let name = 'John';
const age = 30;
Here in both age
and name
any kind of data can be stored. While this may seem convenient to a developer in the beginning is a nightmare while debugging if you input a wrong type of data.
Static type checking
Typescript is what we call a static type checker. It
checks for errors relate to types before we run our code.
TypeScript doesn't really run our code. It performs this type checking before we run our code using JavaScript.
After compiling Typescript is compiled to JavaScript which can be executed as usual.
If we take the above example in TypeScript we can see the compiler warn us before even running our code.
Running TypeScript
TypeScript cannot be run directly through the browser or node. TypeScript is compiled to JavaScript. To do so, we install typescript globally using npm.
npm i -g typescript
Once we have installed TypeScript globally, we get access to the tsc
command.
We'll look at running TypeScript and it's many features in the next blog.
Posted on August 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.