DEV Community

Cover image for Typescript advance Concept
Sankalpcreat
Sankalpcreat

Posted on

Typescript advance Concept

In this Blog we will be understanding some advance concept of typescript how union ,tuples and intersection generics and all other work in typescript
These are the special usage that make typescript better than Javascript as they can be reused again and again

Union
Firstly I will be discussing about is Union in typescript.Often sometime when you do building your project there is always some kind of doubt that what this function going to return and is this is a Sting ,number or undefined to solve this problem we use union it is denoted by symbol | this helps you to see the return type of the function

const person =(name:string|NULL)
Enter fullscreen mode Exit fullscreen mode

Here above code satisfy that name can be either a string or a NULL value with help of this we are not sure whether to give a string or NULL value so we start usage of Union which helps us to solve the doubt about that.

Tuples
Next topic which we are going to brief about is tuples .Tuples plays an import role when we have to give lot of types for the given data like if we want to give data in bulk then we need to define an array which store the value for the types they return .

var data:[string,number];
data=['Jack',3];
data=['Mick',5];
Enter fullscreen mode Exit fullscreen mode

Here above code snipped we can see that there is data variable which has return type of string and number these are again and again used for the string value like jack mick .One thing that we need to keep in mind that order of types should be same that if you have given string first you have to give string first at the time of calling that type

Generics
Here generics plays a very vital role when there is defined all kind of function It can be initialize like <> these to bracket any type inside the bracket

const inti=<T>(arg:T) =>{
return arg;}

Enter fullscreen mode Exit fullscreen mode

above code base here we use generics which use generics of type T can be any either string,number etc that typescript compiler can detect by itself so return arg can return any things like string,number,boolean depending upon the case passed

Top comments (0)