TypeScript Cheat Sheet

Type Annotations

let name: string = "TypeScript";
let age: number = 30;

Primitive Types

let isDone: boolean = false;
let total: number = 100;
let greeting: string = "Hello";

Arrays and Tuples

let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["age", 30];

Enums

enum Direction {
  Up,
  Down,
  Left,
  Right
}

any, unknown, never, void

let anything: any = 5;
let maybe: unknown = "unknown";
function fail(): never {
  throw new Error("Error!");
}
function log(): void {
  console.log("logging");
}

Type Inference

Types are inferred automatically if not explicitly annotated.

let greeting = "hello"; // inferred as string

Function Parameter and Return Types

function greet(name: string): string {
  return `Hello, ${name}`;
}

Optional and Default Parameters

function log(message: string, level: string = "info") {
  console.log(`[${level}] ${message}`);
}

function print(name?: string) {
  console.log(name ?? "Anonymous");
}

Rest Parameters

function sum(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0);
}

Function Overloads

function reverse(x: string): string;
function reverse(x: number): number;
function reverse(x: string | number): string | number {
  if (typeof x === "string") {
    return x.split('').reverse().join('');
  }
  return Number(x.toString().split('').reverse().join(''));
}

Object Types

let user: { name: string; age: number } = {
  name: "Alice",
  age: 25
};

Interfaces

interface Person {
  name: string;
  age: number;
}

Optional & Readonly Properties

interface Car {
  readonly vin: string;
  model?: string;
}

Extending Interfaces

interface Animal {
  name: string;
}

interface Dog extends Animal {
  breed: string;
}

Intersection & Union Types

type A = { a: number };
type B = { b: string };
type C = A & B;

let obj: C = { a: 1, b: "test" };

let value: string | number = "text";

Class Properties & Methods

class Point {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  move(dx: number, dy: number) {
    this.x += dx;
    this.y += dy;
  }
}

Access Modifiers

class Employee {
  public name: string;
  private salary: number;
  protected department: string;

  constructor(name: string, salary: number, department: string) {
    this.name = name;
    this.salary = salary;
    this.department = department;
  }
}

Readonly Modifier

class Book {
  readonly isbn: string;

  constructor(isbn: string) {
    this.isbn = isbn;
  }
}

Inheritance

class Animal {
  speak() {
    console.log("Animal speaks");
  }
}

class Cat extends Animal {
  speak() {
    console.log("Meow");
  }
}

Implements Keyword

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

Type Aliases

type ID = string | number;

Literal Types

type Direction = "up" | "down";

Type Guards

function isString(value: unknown): value is string {
  return typeof value === "string";
}

Discriminated Unions

interface Square {
  kind: "square";
  size: number;
}
interface Circle {
  kind: "circle";
  radius: number;
}
type Shape = Square | Circle;

Type Assertions

let input = document.getElementById("input") as HTMLInputElement;

Non-null Assertion (!)

let value: string | null = getValue();
console.log(value!.length);

Indexed Access Types

type Person = { name: string; age: number };
type NameType = Person["name"];

Keyof and typeof Operators

type Keys = keyof Person;
const person = { name: "Alex", age: 20 };
type PersonType = typeof person;

Generic Functions

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

Generic Interfaces & Classes

interface Box {
  value: T;
}

Generic Constraints

function logLength(arg: T): void {
  console.log(arg.length);
}

Default Type Parameters

interface Response {
  data: T;
}

Utility Types

type User = {
  name: string;
  age: number;
};

Partial
Required
Readonly
Pick
Omit
Record
ReturnType<() => string>
Parameters<(a: number) => void>

Import / Export

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

// main.ts
import { add } from './math';

Module Augmentation

declare module "express" {
  interface Request {
    user?: User;
  }
}

Ambient Declarations

declare var myGlobal: string;

Namespaces (legacy)

namespace MathUtils {
  export function square(x: number): number {
    return x * x;
  }
}

tsconfig.json Options

{
  "compilerOptions": {
    "target": "es6",
    "strict": true,
    "module": "commonjs"
  }
}

Type Declaration Files (.d.ts)

declare module "my-lib" {
  export function greet(name: string): void;
}

Using DefinitelyTyped (@types)

npm install --save-dev @types/lodash

Strict Mode

Enable options like strictNullChecks, noImplicitAny to enforce strict typing rules.

JS Interop

declare function require(moduleName: string): any;

Working with 3rd Party JS Libraries

Use type declarations via @types packages or write your own .d.ts files.

ES Modules vs CommonJS

Use import/export for ES Modules and require/module.exports for CommonJS compatibility.

Decorators (Experimental)

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

Mapped Types

type ReadonlyUser = {
  readonly [P in keyof T]: T[P];
};

Conditional Types

type IsString = T extends string ? true : false;

Infer Keyword

type ReturnType = T extends (...args: any[]) => infer R ? R : never;