TypeScript Cheatsheet
1. Basic Types
let isDone: boolean = false;
let decimal: number = 6;
let color: string = 'blue';
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ['hello', 10];
2. Enums
enum Color {Red, Green, Blue};
let c: Color = Color.Green;
// String Enums
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
}
3. Type Assertions
let someValue: unknown = 'this is a string';
let strLength: number = (someValue as string).length;
// or using angle-bracket syntax
let strLength2: number = (<string>someValue).length;
4. Functions
function add(x: number, y: number): number {
return x + y;
}
// Anonymous function
let myAdd = function(x: number, y: number): number { return x + y; };
// Arrow function
let myAddArrow = (x: number, y: number): number => x + y;
5. Interfaces
interface Person {
firstName: string;
lastName: string;
}
function greet(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
let user = { firstName: 'John', lastName: 'Doe' };
greet(user);
6. Classes
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
let dog = new Animal('Dog');
dog.move(10);
7. Inheritance
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
let dog = new Dog('Dog');
dog.bark();
dog.move(10);
8. Access Modifiers
class Person {
public name: string;
private age: number;
protected gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
9. Generics
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>('myString');
let output2 = identity<number>(100);
10. Union Types
function padLeft(value: string, padding: number | string) {
if (typeof padding === 'number') {
return Array(padding + 1).join(' ') + value;
}
if (typeof padding === 'string') {
return padding + value;
}
}
padLeft('Hello', 4);
padLeft('World', '>> ');
11. Type Aliases
type StringOrNumber = string | number;
let example: StringOrNumber = 'Hello';
example = 100;
12. Intersection Types
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type Worker = Person & Employee;
let worker: Worker = { name: 'John', employeeId: 1234 };
13. Modules
// Exporting a module
export class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
}
// Importing a module
import { Animal } from './Animal';
let cat = new Animal('Cat');
14. Namespaces
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return /^[a-zA-Z]+$/.test(s);
}
}
}
let validator = new Validation.LettersOnlyValidator();
console.log(validator.isAcceptable('Hello'));
15. Decorators
function log(target: any, key: string) {
console.log(`${key} was accessed.`);
}
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
@log
get name(): string {
return this._name;
}
}
let person = new Person('John');
person.name;
16. Optional Parameters & Default Parameters
function buildName(firstName: string, lastName?: string) {
return firstName + ' ' + (lastName || '');
}
let result1 = buildName('Bob'); // works correctly
let result2 = buildName('Bob', 'Adams'); // works correctly
17. Null and Undefined
let u: undefined = undefined;
let n: null = null;
// By default null and undefined are subtypes of all types.
18. Type Guards
function isString(x: any): x is string {
return typeof x === 'string';
}
function example(foo: number | string) {
if (isString(foo)) {
console.log('It is a string');
} else {
console.log('It is a number');
}
}
19. keyof and Lookup Types
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // 'name' | 'age'
let key: PersonKeys = 'name';
20. Mapped Types
type ReadOnly<T> = {
readonly [P in keyof T]: T[P];
};
interface Person {
name: string;
age: number;
}
let readonlyPerson: ReadOnly<Person> = { name: 'John', age: 25 };
21. Conditional Types
type NonNullable<T> = T extends null | undefined ? never : T;
let value: NonNullable<string | null> = 'Hello'; // works
22. Utility Types
type Person = { name: string; age: number };
let partialPerson: Partial<Person> = { name: 'John' };
let readonlyPerson: Readonly<Person> = { name: 'John', age: 25 };
let pickedPerson: Pick<Person, 'name'> = { name: 'John' };