type aliases or your own type is one of the most important part of typescript see how you can implement type aliases in typescript using type .
link->https://stackblitz.com/edit/typescript-7barjt
link->https://stackblitz.com/edit/typescript-7barjt
//creating your own type or type alias in typescript is very easy for example
//direction type what only allowed dirction values
export type Direction="north"|"south"|"east"|"west";
//strArray allowed only string and array where array is number of boolean type
export type strArray=string|Array<number|boolean>;
//an interfacce type---------
export type userdd=userDD;
interface userDD
{
userDirection:Direction
username:string
}
class human
{
private direction:Direction;
private myarray:strArray;
private newuser:userdd;
constructor()
{
/*
myarray is string and array type where Array is number or boolean
type so any other value in myarray not allowed
*/
//not allowed
//this.myarray=["manish"]
//allowrd
this.myarray=[true,false];
//newuser is userDD type so both below value allowed because
username is string type and userDirection is direction type
this.newuser={
username:"manish",
userDirection:"east"
}
}
public setDirection(_direction:Direction)
{
this.direction=_direction;
}
public getDirection()
{
return this.direction;
}
public moveMe()
{
switch(this.direction)
{
case "north":
console.log("move north")
break;
case "south":
console.log("move south")
break;
case "east":
console.log("move east")
break;
case "west":
console.log("move west")
break;
}
}
}
//check your type
var h=new human();
h.setDirection("north")//move human to north direction
h.moveMe();
Comments
Post a Comment