Typescript

Custom Types(in TS):

There are 3 custome types in TS:

  1. Interface
  2. enum
  3. Class

Interface:

syntax-

interface interface_name{
//declaration
var_name: type;
}

Note:the interface will not be compiled to corresponsing js, it is just instruction of transpiler to insure the type

To make a property Optional use ? next to prop name-

example-

interface interface_name{
//declaration
var_name?: type;
}

Example:

interface TODO{
name: string;
completed?: boolean;
}

While using above interface it’s not mandatory to pass/use completed type.

Interface can even have function as it’s property:

interface TODO{
getAllTOdo(): TODO[];
getTODObyID(todoID: number): TODO;
deleteTODO(todoID: number);
addTodo(todo: TODO):TODO;
}

Accessing or using interface :

step 1: assign the interface to a variable

var someTodoVar: TODO={

name=”the name of todo”;

}

or you can explicity,mark the object type to expected interface type by using casting -syntax i.e angular brancket and the type i.e <TODO>

Use case:

if there is an existing Interface by 3rd party and you want to add more type check TS allows you to create the same name interface and put the type checks in that Interface inthis way it avaoid code change as it behaves as if were updated in original Interface.

Example :

Original one:

interface TODO{
name: string;
}

new checks:

interface TODO{
getAllTodo(todoId: number): TODO[];
}
enumDefining Constants

IT is same as defined in other langages,

example:

enum toDOEnum{
Active=1,
New,
completed,
Aborted

}
the number to others states are autoassifned based on first i.e
Active=1,
New=2,
completed=3,
Aborted=4
Using enum:
var some_var : number= toDOEnum.Active;
Anonymous type:

Enum can be defined inline doing away with need to type word enum & it’s name at same time it enforces the type-check

example:

var some_name:{name:string}

Assigning and accessing above inline or anonymous type:

some_name={name:”Hello World”}
var result=some_name.name;

CLASS

prototype syntax-

Prototypical inheritance introduced inECMA6 , it can be used to create the constructor function usig prototype.

class syntax-

There is also another way to create constructor function & apply OOPS principal using class:

syntax-
class class_name{
prop_var:type;
constructor(){
}
method_name(){
}
}

syntactical sugar:

adding private parameter to constructor acts as if you have created a property and initialed it with default.

Example:

class some_call{
constructor(private var_name: type[])
}

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment