TypeScript — An Object-Oriented Programming Language
TypeScript is a programming language built on top of JavaScript. It is considered a superset of JavaScript because code that is written in TypeScript can be converted into JavaScript to be run as per usual. Actually, TypeScript can’t be understood by the browser so the conversion to JavaScript is necessary. It is a process known as trans-pile. If you know JavaScript, learning TypeScript should come easily once you get a hang of its special features.
Set-Up
To install TypeScript, just enter this command in the terminal as it will be saved globally.
// npm
npm install --global typescript//yarn
yarn global add typescript
Once TypeScript is installed, you may use TypeScript commands with tsc
.
TypeScript files end with the extension .tsc
and can be converted to JavaScript files by using the following command.
tsc fileName.tsc
This command will create a JS file with the TypeScript converted into JavaScript. That’s how you can make use of TypeScript but still be developing in JS. Now let’s take a look at some of the features of TypeScript that give it a boost compared to vanilla JS.
Static Typing
The feature that has gained TypeScript so much popularity is the static typing that comes with the programming language.
As you may know, JavaScript does not support static typing. When you initialize a variable in JS it looks something like this.
let num = 2;
num
is set to a value of 2 but the variable num
does not have to store an integer. It can be assigned to a string or any other data type.
num = 'Hello';
As num
is being reassigned to a string 'Hello'
, JS will not show any errors as it is completely fine for the num
variable to be reassigned a different data type. This may raise many issues during development due to the uncontrollable typing of variables. TypeScript can provide that layer of protection by showing errors when it is being compiled.
Another feature that comes in handy is the ability to create interfaces
and classes
.
Interfaces
Interfaces allow for the structure of the data being handled to be checked so that there are no surprises when dealing with other code. This can be seen as a contract between code that agrees to allow a defined data structure so that your program can run smoothly across files.
Classes
TypeScript comes with the ability to create classes in JavaScript. In vanilla JavaScript, functions and prototypical inheritance are used to create reusable components. This may seem unusual compared to the object-oriented way of creating classes for creating objects and inheriting functionality/properties. TypeScript provides an object-oriented approach to building dynamic and rich applications.
For a guide to TypeScript, take a look at the documentation
or this article.