This article will be a help if you want to get started with TypeScript. I am breaking down the topics into smaller chunks so that you can understand it easily.
Prerequisite
- Basics of JavaScript or any programming language will also help.
What is TypeScript ?
TypeScript is a typed superset of JavaScript. So what do typed means let's understand?
So when we code in java or c++ we define the data type of the variable.The compiler must know the type that it will be a number, a string, or a boolean. When the type is known during the compile time it is called Static typing
In JavaScript we don't define the data type . The data type is checked during the run time also called Dyanamic Typing.
But in TypeScript we define type of the variable whether it is a string, number or a boolean and superset means it has all the features of JavaScript.
Example
Suppose const apple = 1 here the datatype of apple is a number. We can assign any data type to the variable apple.
///Here the apple can have any datatype number, boolean,string etc
const apple = 1
Let's say we want to assign only a number type to the variable apple. How can we achieve it? TypeScript for the rescue.
///Here we declare that the type of apple that should be a number
type AppleType = number
///Then we assign the type to the apple
const apple : AppleType = 5
Now this variable apple it will take only number type. If you assign any other datatype it will through an error.
Let's see what error it will throw
So we can see the error Type "string" is not assignable to type "number". This occurs because a specific type is been assigned to the variable apple. It will not accept any other datatype rather than a number. This is the power of TypeScript . It tells you that only the type which is being assigned will only be taken rather than any other type. The best part of typescript is that it will highlight the code instantly if you do not assign the proper type for the variable and it also helps in lowering the bugs in the code.
Assigning Types
Let's understand how you can assign types in TypeScript
Arrays
Here we specify the type of the array i.e it will be an array of strings.
const userArray:string[] =[ "ram", "lakshman" , "bharat"]
If we put a number say 1 in the array it will show an error like this on the below.
We can see the error that Type 'number' is not assignable. This is fair enough as we have declared strictly the type will be a string[]
i.e array of strings.Suppose we want a number in the array we can achieve it which I will show you in the further examples.
The same goes for number[]
.It will accept only number type.
const numberArray :number[] = [1,2,3,4]
Any
The type any
means that a particular value can have any datatype and the compiler will throw zero errors.
Let's take the userArray example. Above we saw that when we specified the type of the array to be string[]
, it accepted only strings. Now when we assigned the type to be any
it is accepting a number also.
const userArray: any=[ "ram", "lakshman" , "bharat",1]
Objects
///1st Example
const user = {
name:"pratim",
age :18
}
///2nd Example
const user = {
name:18,
age :"pratim"
}
For 1st example, we have a user object with a name and age. The name is a string and the age is a number. In the 2nd example, the name is a number and the age is a string which is wrong because we know that the name will always be a string and the age will always be a number. So we can assign types to both name and age like below
type User ={
name : string,
age:number
}
const user :User={
name :"pratim",
age:18
}
Now the name will accept only a string and the age will accept only a number. If we assign datatypes which is not being specified to the name and age it will throw an error like this
That's why TypeScript has a great value in large-scale applications.
Functions
Functions as we know is the heart of javascript. So let's look at how can we specify the type of the parameters of a function.
function welcome(name :string){
return "Hello " + name
}
welcome("pratim")
Let's understand the example. We have a function that is taking one parameter and it is being specified that it will be type string
. So when an argument will be passed to the function the type will be checked whether it is a string
or of any other datatype. Since in the above the type of the argument is string
it works fine. But if we have given it a type number
it will throw an error something like this
Optional Properties
type User = {
name: string;
age?: number;
};
function welcome(obj: User) {
return "hello " + obj.name;
}
///this works
console.log(welcome({ name: "pratim " })) ///"hello pratim"
Since we have given the age ?
optional it doesn't give an error. The code will run and it will print "hello pratim".
But if we remove the optional from the age it will throw an error like that a property is missing and is required.
That's the working of optional?
properties. Until the age has ?
it will not throw an error if it is not being used.
Union Types
So now that we have a fair understanding of how to build types. Let us understand how can we combine types and make it more interesting. A union type can be formed by combining one or more types
In this function, the parameter type is number |
string . So the argument passed to the function can be a number or a string. If we pass a type that is not a string or a number it will throw an error.
function userId(id :number | string){
return id
}
userId(1) //ok
userId("pratim")//ok
userId(true)///Argument of type 'boolean' is not assignable to parameter of type 'string | number
TypeGuard
We are getting this error because Typescript is warning us that we cannot apply the +
operator both on string | number
because we might not get the desired output.
So here comes in picture type guards to handle the error.
So in the function below we can see that num can be of typestring | number
. Inside the if statement we are saying that num is of type number
which means that after the end of our if statement TypeScript cleverly knows that we are using a string. Now we will be able to use all the string methods on by using dot
on num
function sum(num : string |number) {
if(typeof num === 'number') {
return num+5
}
num. //string
}
So now lets pass a number:
function sum(num : string |number) {
if(typeof num === 'number') {
return num+5
}
return num.toLocaleUpperCase()
}
console.log(sum(5)) /// 5
Lets pass a string :
function sum(num : string |number) {
if(typeof num === 'number') {
return num+5
}
return num.toLocaleUpperCase()
}
console.log(sum("pratim"))///PRATIM
References TypeScript Handbook
This is my first article.I hope you have learned something new today. We can connect on (twitter.com/pratimcodes) and have some great conversations regarding react, javascript, typescript.
Keep Coding :) Peace out !!