What's TypeScript?
TypeScript is an open-source language developed and maintained by Microsoft built on top of JavaScript, one of the world’s most used tools, by adding static type definitions.
In simple words TypeScript is JavaScript with static typing
Why to use?
As you are reading this you are probably very familiar with JavaScript and also the fact that it's a dynamically typed language. It's although provides a lot of freedom for developers to write their code. But with freedom comes responsibility and the moment you get a little lazy, things start bouncing off, JS is out of control before you know it
The solution is TypeScript, as it strictly forces you to define a type for every variable beforehand we don't encounter a runtime error in future.
Difference between Static and Dynamic typing
All the programming languages are either of the 2 types i.e. Statically typed and dynamically typed.
In languages with static typing, the type of the variable must be known at compile-time. If we declare a variable, it should be mentioned beforehand to the compiler if it will be a number, a string, or a boolean. For example Java and C++.
In languages with dynamic typing, the type of a variable is known only when running the program. For example Python and JavaScript.
Still not clear??? Let's check out these examples
Dynamic Typing
let variable = 12 ;
variable = "Hello World";
console.log(variable); // Prints Hello World
This is the freedom provided by dynamically typed languages, but this can lead to run-time errors as:-
// JavaScript
function divide (number){
return number / 10 ;
}
let variable = 10 ;
divide(variable); // Prints 1
variable = "Hello World";
divide(variable); // Prints NaN
This type of run-time errors are a serious issue and lead to a major problem when such a code is pushed in production, which was the motto for making a static typed.
Static Typing
This same code in a statically typed language will be:-
// TypeScript
// Here the function and parameter is of number type
function divide (number : number): number{
return number / 10 ;
}
let variable: number = 10 ; // variable is given a type of number
divide(variable); // Prints 1 and will only work for number as parameters
Common types in TypeScript
Basic types
TypeScript has several basic types that are pre-defined. For eg: Number, String, boolean which we define as
const VariableName: type = value;
Boolean
Represents numeric value.
let isTrue: boolean = true;
Number
Represents numeric value.
let score: number = 12;
String
let name: string = "Gourav";
As the variables are typed beforehand, so any unexpected change is reflected as an error as:-
Arrays
Array type can be defined in two ways:- type[] and Array means the same, where type can be string, number, boolean, objects, functions, etc.
const strings: string[] = ['Hello', 'Hii', 'Ok'];
const names: Array<string> = ['Gourav', 'Kumar', 'Dey'];
const numbers: Array<numbers> = [1,2,3,true]; // Will show an error as true is not a number type
Any
Any is a special type. We use this when we don't want a particular value to cause type-checking errors. Basically, it will accept any syntactically legal type. Using any as a type makes typescript variable dynamic, so use it when you don't have any other option.
let anyThing: any = 12;
anyThing= "something";
anyThing= false;
anyThing= [1, 2, 3];
anyThing= { a: 0, b: "hi" };
Objects
Objects are mostly what we will be using in general. Its list the properties and their respective values by a ,
to separate the properties.
// Defining a type for object
type MyObject = {
name: string;
score: number;
}
Using the type in an object
const myObject: MyObject = {
name: "Gaurav",
score: 100
}
Narrowing and Discriminated unions
When there is a possibility that a variable can have more than one type and will be perfectly working in the code then unions are used to discriminate the types.
we use the pipe character |
which is often used for an OR operation
let value: number | boolean = 10;
value = true; // works fine
value = 'true'; // doesn't work
Now, as we are allowing more than 1 static type to any variable, the question arises how will we make typescript differentiate when to use which type. Here comes the term type-guard. It's a way to narrow down to one type out of all the types of the union of types.
Don't worry, there is no complex coding involved just an if-else statement
if(typeof value === "number") {
console.log(value - 3);
// -> 7
}
else {
console.log(assignMe, " is a boolean variable!");
// -> 10 is a boolean variable!
}
Discriminated union
Discriminated Unions, also called algebraic data types or tagged unions are a combination of three things:
- The discriminant
- The union
- Type guards
The Discriminant
The discriminant is a singleton type property that is common in each of the elements of the union. You can read more about Typescript Singleton. Example:
type Action =
| { type: "CORRECT"; payload: number }
| { type: "WRONG"; payload: number }
| { type: "RESET" };
The Union
The union of the discriminants can be simply created as follows:
type StatusState = "CORRECT" | "WRONG" | "RESET";
The Type guard
function ScoreReducer(CurrentScore: number, action: Action) {
switch (action.type) {
case "CORRECT":
return score: CurrentScore + action.payload
case "WRONG":
return score: CurrentScore - action.payload
case "RESET":
return score: 0 ;
}
}
Difference between type & interface
These are two ways by which a static type for a variable is declared. Both are very much similar to each other.
1. Declaration Merging
For interfaces that share the same name, the TypeScript compiler merges two or more interfaces into only one declaration.
interface Person {
name: string;
}
interface Person {
age: number;
}
const siddhi: Person = {
name: "Gourav",
age: 21
};
This is not possible with types as can be seen below
This error is because the type does not accept duplicate entries, it takes the first definition as unique and any more type of the same name is shown error where duplication is possible in the interface.
2. Intersection
We can combine multiple types with the &
keyword into a single type. But, we cannot combine them into a single interface.
type Name = {
username: string;
}
type Age = {
age: number;
}
type User = Name & Age; // It's valid
interface Name = {
username: string;
}
interface Age = {
age: number;
}
interface User = Name & Age; // It's invalid and error will be shown
3. Union
It allows us to create a new type that can have a value of one or a few more types. To create a union we have to use the |
, which known as pipe
character.
type Name = {
username: string;
}
type Age = {
age: number;
}
type User = Name | Age; // It's valid
interface Name = {
username: string;
}
interface Age = {
age: number;
}
interface User = Name | Age; // It's invalid and error will be shown
Conclusion
We can see from all the above explanations that TypeScript is far better than JavaScript with no disadvantages. For someone moving from JavaScript to TypeScript, it's irritating to see so many errors which were syntactically correct in the former.
But this prevents your code from crashing at any point in time if written in a dynamic language. That's the reason TDD is mostly used in every other organisation.
Hope you liked this article. Stay tuned for more such articles. Please share and comment below your views on TypeScript.
Connect with me on LinkedIn.