TypeScript — Basics
What is TypeScript?
TypeScript extends javascript by adding types
Why TypeScript?
TypeScript simplifies javascript code making it easier to read and write
Basic datatypes:
Number :
In typescript all integer and floats comes under numbers
Eg: let sum: number = 40;
String :
Single quotes and double quotes all are comes under string
Eg: let response: string = “success”;
Boolean :
It contains true/false value
Eg: let isCorrect: boolean = yes;
Object :
Object is type that represents non-primitive types, any thing that is not number, string, boolean, undefined etc
Eg: let person = { name : “john”, age : 29 }
Array :
Array is group of elements, we can define two ways
Eg: let marks: number[]= [45,56,56,76,67]
Eg: let students: string[] = [“john”,”jack”,”krish”]
Eg: let marks: Array<number> = [54,54,54,54]
Tuple :
It is an array with fixed number of elements whose types are known, but need not be same.
Eg: let studentResult : [number, string];
studentResult = [101,”john”];
Any :
Sometimes we do not know what will be the return value in that case we will use any
Eg: getResult(input: string) : any { return input + 2; }
Void :
It is opposite to any, mostly will see void in function return type. if any function does not return any value in that case we will use void
Eg: displayResult(input: string) : void { console.log(‘display result is’,input); }
Union ( | ) :
It is combine any datatypes or objects etc
Eg1: let result : number | string;
Here we can store both number and string values in result variable using union type.
Eg2: Below function take input as number, string or boolean.
Enums :
It allows developer to define set of named constraints, it provides both numeric and string based enums.
Above Colors default RED will take 0, GREEN =1, BLUE =2 etc
Also we can initialize with default value, for eg if you give RED = 5 then GREEN take 6, BLUE =7 etc.
And also we can give custom values.
String enum are similar concept, In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
Type :
By using type we can create custom type like below
Function Type :
TypeScript functions can be created both as a named function or as an anonymous function.
A function’s type has the same two parts: the type of the arguments and the return type. When writing out the whole function type, both parts are required.
Function Callbacks:
Thanks for reading