TypeScript Cheatsheet
extension to javascript
#Compiler
npm install -g typescript
npm install --save @types/node
tsc --outDir dist index.ts#Linter
npm install -g tslint
tslint file1.ts file2.tsnpm install --save @types/express
typescriptlang.org
Example ts file:
// main.ts
const a: string = "1";
console.log("aaa" , a);
How to Run a file:
tsc main.ts -w
-w : to run the file in watch mode
Configuration with tsconfig.json
{
"compilerOptions":
{
"module":"commonjs",
"outDir": "dist",
"sourceMap": true
},
"include": [
"src/**/*.ts"
]
}
Type Declarations
function combineNames(first: string, last: string): string {
return first+" "+last;
}const firstName: string = "Sumit";
const lastName: string = "Bopche";console.log(combineNames(firstName,lastName));//type declaration for an object
const user : { name: string, age: number} = {
name: "Monster",
age: 30
};
We must declare type explicitly for better code readability.
let hello = "world"
hello = 2 //this will give error as typescript will set type of hello variable as string.
Union
If we want to allow property to have more than one type then we can use union operater ‘|’.
let pageNumber: string | number = "1";
let error: string | null = null; //if we don't assign any value then default value is undefined, so must assign the value.
Type Alias
type ID = string;interface UserInterface {
id: ID;
name: string;
}
Type Assertion (Type Casting)
We can use “as” for converting from value of unkown type to desired type
let alien: unknown = 101;
let alienCode: string = alien as string;
For other data types we must convert it to unknown data type then convert to desired data type
let rollNo: string = "7";
let studentId: number = (rollNo as unknown) as number;
We can directly convert “any” data type to desired data type
let page: any = "1";
let pageNumber: string = page as string;
Interfaces
interface IPerson {
firstName: string;
lastName: string;
age: number;
}const studentDetails: IPerson = {
firstName: "Sumit",
lastName: "Bopche",
age: 25
}
Naming Convention: Instead of naming the interface as “Person”, we should go with IPerson or PersonInterface for better readability.
All the fields specified in IPerson interface are mandatory.
const student2: IPerson = {
firstName: "Ved",
lastName: "Up"
} // this will give compile time error as we are not assigning any value to required age property.
To make any field non mandatory then we should add “?” for those properties while creating an interface.
interface IPerson {
firstName: string;
lastName: string;
age?: number;
address?: string;
}
Classes
public, private,protected, readonly
interface IShip {
name: string;
sail(): void;
}class Ship implements IShip {
private shipName: string; public get name(){
return this.shipName;
} public sail(): void {
//start sailing
}}
Modules
import { IShip } from "./IShip";export class Ship implements IShip {
private shipName: string; public get name(){
return this.shipName;
} public sail(): void {
//start sailing
}}
Generics
const addId = <T extends object>(obj: T) => {
const id = Math.random().toString(16);
return {
...obj,
id
};
};interface UserInterface<T, V> {
name: string;
data: T;
meta: V;
}const user: UserInterface<{meta: string}, string> = {
name: "Elon",
data: {
meta: "foo"
},
meta: "SpaceX"
};const user2: UserInterface<string[], number> = {
name: "John",
data: ["foo", "bar"],
meta: 1
};const result = addId(user);
console.log("result", result);
Enums
enum ShipmentStatusEnum {
Booked,
Packaged,
Shipped,
Delivered,
Returned,
Cancelled
}let shipment1Status: ShipmentStatusEnum = ShipmentStatusEnum.Booked;