📘 TypeScript Cheatsheet (Beginner → Advanced)

← Go Back

1. What is TypeScript?

TypeScript is a superset of JavaScript that adds static typing.

Purpose: Catch errors early and improve code maintainability.

2. Basic Types

let isDone: boolean = false;
let age: number = 25;
let username: string = "John";
let scores: number[] = [90, 80];
let data: any = "anything";

Purpose: Declare types explicitly to avoid errors.

3. Type Inference

let city = "New York"; // inferred as string

Purpose: Let TypeScript guess the type based on assignment.

4. Functions

function add(a: number, b: number): number {
  return a + b;
}

Purpose: Type input and return values for clarity.

5. Type Aliases

type ID = number | string;
let userId: ID = "abc";

Purpose: Name a union or complex type for reuse.

6. Interfaces

interface User {
  id: number;
  name: string;
}

Purpose: Define a contract for object shapes.

7. Union and Intersection Types

let value: string | number;
type A = { a: number };
type B = { b: string };
type AB = A & B;

Purpose: Combine or separate possible types.

8. Enums

enum Direction { Up, Down, Left, Right }
let dir = Direction.Up;

Purpose: Use readable names for constants.

9. Generics

function identity(arg: T): T {
  return arg;
}

Purpose: Create reusable and type-safe functions/components.

10. Type Narrowing

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  }
}

Purpose: Safely use a value after checking its type.

11. Type Assertions

let someValue: any = "hello";
let length = (someValue as string).length;

Purpose: Tell TS a more specific type when you know better.

12. Classes

class Person {
  constructor(public name: string) {}
  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
}

Purpose: Write OOP-style code with reusable logic.

13. Access Modifiers

class Car {
  private speed: number;
  protected model: string;
  public brand: string;
}

Purpose: Control access to class members.

14. Abstract Classes

abstract class Shape {
  abstract area(): number;
}

Purpose: Enforce implementation of abstract methods in subclasses.

15. Utility Types

Partial
Required
Readonly
Pick
Omit

Purpose: Modify existing types with built-in helpers.

16. Conditional Types

type IsString = T extends string ? true : false;

Purpose: Create types that depend on conditions.

17. Modules

// math.ts
export function add(x: number, y: number): number { return x + y; }
// app.ts
import { add } from './math';

Purpose: Organize code across multiple files.

18. Bonus Tips

type Keys = keyof User;
type Book = Record;
let val: never = (() => { throw "error" })();

Purpose: Leverage TS power tools for advanced control.