Typescript Cheatsheet
Core Concepts
Datatypes
-
number
let age: number;
age = 25;
let age = 25; -
string
let name: string;
name = "John";
let name = "John"; -
boolean
let isValid: boolean;
isValid = true;
let isValid = true; -
array
let numbers: number[];
numbers = [1,2,3];
let numbers = [1,2,3]; -
tuple
let random: [string, number, string] = ["A", 1, "B"]
-
enum
enum Color {
Red,
Blue
}
enum CustomColorCode {
Red = "#233233"
Blue = "#434384"
}
let red = CustomColorCode.Red; -
any
// Do not use it unless unavoidable or for dynamic values
let dynamicValue: any = 5; -
void
function sayHello():void {
console.log("Hello")
} -
null
let nullValue: null = null;
-
undefined
let undefinedValue: undefined = undefined;
-
object
let user:object = {
name: "john",
age: "25"
}
Operators
- Arithmetic -
+,-,*,/,%
- Assignment -
=,+=,-=,*=,/=,%=
- Comparison -
==, !=, ===, !==, > < , >=, <=
- Logical -
&&, ||, !
Control flow
if...else
do...while
switch
while
Functions
- Simple function
function addNumbers(number1: number, number2: number): number {
return number1 + number2;
}
const result = addNumbers(1,2);
- Optional parameter
function addNumbers(number1: number, number2?: number): number {
// function body
}
const result = addNumbers(1);
const result = addNumbers(1,2);
- Default parameter
function addNumbers(number1: number, number2= 10): number {
// function body
}
const result = addNumbers(1);
const result = addNumbers(1,2);
- Rest parameter
function addNumbers(number1: number, ...numbers: number[]): number {
// function body
}
const result = addNumbers(1);
const result = addNumbers(1,2,3,4,5);
- No return
function NOOP(): void {
// function body
}
Interfaces & Classes
Interface - defines the structure of objects and provide contract for implementing classes
interface Person {
name: string;
age: number;
sayHi: () => void
}
let person: Person = {
name: "Balaji",
age: "22",
sayHi: function() {
// function body
}
}
Classes - defines the object blue print
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHi():void {
console.log(`Hi ${this.name}`)
}
}
let person:Person = new Person("Balaji", 22)
person.sayHi();
Advanced Concepts
- Union types -allows multiple types
|
- Intersection types - combine multiple types
&
- Type aliases - create custom names for types
- Generics - reusable methods that can work with multiple types
- Module - encapsulate code into seperate files
- export
- import
- default export
- Namespace - internal modules, code organization
- Type inference - auto infer types of variables
- Type guards - infer type during runtime
typeof
- Module resolution - relative path, package import
- Decorators - add metadata, modify the behavior of classes, methods at design time
- Inheritance - can
extend
classes - Encapsulation - bundle related properties and methods
private
,public
andprotected
- Polymorphism - method overloading
Generics
- Methods
function identity<T>(arg: T) {
return arg;
}
- Classes
class Box<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
let stringBox = new Box<string>("Typescript");
console.log(stringBox.getValue());
let numberBox = new Box<number>(40);
console.log(numberBox.getValue());
- Constraints with Generics
interface LengthType {
length: number;
}
function getLength<T extends LengthType>(arg: T): number {
return arg.length
}
let arrayLength = getLength([1,2,3,4,5]);
console.log(arrayLength);
Decorators
Special declaration that can be attached to classes, methods, properties or parameters. Prefixed with @
. Executed at runtime.
function log(target: any) {
console.log("target is", target);
}
@log
class MyClass {
// class body
}
class MyClass {
@readonly
name: string = "John";
@log
method() {
// method body
}
method1(@dec input: string) {
// method body
}
}
metadata
Attach additional data to classes, methods, properties or parameters.
class MyClass {
// Set metadata
@Reflect.metadata("custom tag", "some data");
method() {
// method body
}
}
const metadata = Reflect.getMetadata("custom:tag", MyClass.prototype, "method");
console.log(metadata); // some data
Useful in logging and debugging. Argument decorators can be used in input validation. Dependency injection for frameworks, routing and middleware.
From architecture perspective, the above features can help in code modularity by seperating concerns.Others being readability and runtime reflection.
Async
- Callback
function getData(callback: (data: string) => void) {
setTimeout(() => {
callback("Hello")
}, 1000)
}
getData((msg: string) => {
console.log(msg)
})
- Promises
function fetchData():Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success")
}, 1000)
})
}
fetchData().then((data) => {
console.log(data)
}).catch((e) => {
console.log(e)
})
- Async await
async function fetchData():Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success")
})
})
}
async function getData() {
try {
const data = await fetchData();
console.log(data); // success
} catch(e) {
console.error(e)
}
}
getData()
Updates to TS
--- coming soon! ---