Skip to content

TypeScript

Manujaya edited this page Jul 20, 2021 · 11 revisions

Cheatsheet

Types

Assigning Variables

//Numberletx=42;letexampleNumber:number=66;//String letexampleName: string="Person1";//BooleanletexampleBoolean: boolean=false;//DateletexampleDate: Date=newDate(2021,7,17);//AnyletexampleAny: any="Can be anything";//ArrayletexampleArray1: string[]=['index1','index2'];letexampleArray2: Array<number>=[1,3];letexampleArray3: number[]=[2,4];//Enumenumcolor{RED,GREEN,BLUE,}letexampleEnum: color=color.GREEN;console.log('exampleEnum :: ${typeof exampleEnum}');//NullletexampleNull: number=null;//Tuple//Similar to an array but different indexes have different typesletexampleTuple: [string,number];

Assigning Constant

//const can be used instead of let in above typesconstexampleConstNum: number=99;constexampleConstString: string="Value";

Void Function

functionexampleVoid(msg: string): void{console.exampleVoid(msg);}

Classes

Example class:

classOrderLogic{constructor(publicorder: IOrder){}getOrderTotal(): number{letsum: number=0;for(letorderDetailofthis.order.orderDetails){sum+=orderDetail.price;}returnsum;}}

Installation

npm install TypeScript

Compiler comments

Don’t check this file

// @ts-nocheck

Check this file (JS)

// @ts-check

Ignore the next line

// @ts-ignore

Expect an error on the next line

// @ts-expect-error

Operators

&&=

leta;letb=1;// assign a value only if current value is truthya&&='default';// a is still undefinedb&&=5;// b is now 5

||=

leta;letb=1;// assign a value only if current value is falsea||='default';// a is 'default' nowb||=5;// b is still 1

??=

leta;letb=0;// assign a value only if current value is null or undefineda??='default';// a is now 'default'b??=5;// b is still 0

Clone this wiki locally