ENGIMY.IO - CHEATSHEET
TYPESCRIPT × QUICK REFERENCE
REFERENCE vTypeScript 5.0

TS Quick Reference

Everything you need day‑to‑day – types, classes, generics, and modern features.

Basic Types

Primitives
  • string"hello"
  • number42, 3.14
  • booleantrue, false
  • bigint100n
  • symbolunique identifier
  • null / undefined
Complex Types
  • anyopt out of type checking
  • unknowntype‑safe any
  • voidno return value
  • neverfunction never returns
  • objectnon‑primitive
  • Array<T> or T[]
  • Tuplefixed‑length array
  • Enumnamed constants

Type Declarations

let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["Alice", 25];

Enums

// Numeric enum (auto‑incremented)
enum Color {
    Red = 0,
    Green = 1,
    Blue = 2
}
let c: Color = Color.Green;

// String enum
enum Status {
    Success = "SUCCESS",
    Failure = "FAILURE",
    Pending = "PENDING"
}

// Const enum (inlined at compile time)
const enum Direction {
    Up = "UP",
    Down = "DOWN"
}

Interfaces

// Basic interface
interface Person {
    name: string;
    age: number;
    email?: string;          // optional
    readonly id: number;     // read‑only
}

// Interface with method
interface Greetable {
    greet(): void;
}

// Extending interfaces
interface Employee extends Person, Greetable {
    department: string;
    salary: number;
}

// Index signature
interface StringMap {
    [key: string]: string;
}

// Function interface
interface SearchFunc {
    (source: string, substring: string): boolean;
}

Interface vs Type

// Use interface for objects that can be extended
interface Animal { name: string; }

// Use type for unions, intersections, primitives, etc.
type ID = string | number;
type Point = { x: number; y: number };

Type Aliases

// Primitive alias
type UserID = string;

// Union type
type Status = "pending" | "approved" | "rejected";

// Intersection type
type FullPerson = Person & { department: string };

// Type with generics
type Response<T> = {
    data: T;
    status: number;
    error?: string;
};

Classes

class Animal {
    private name: string;      // accessible only inside class
    protected age: number;    // accessible in subclasses
    public species: string;   // accessible anywhere (default)

    constructor(name: string, age: number, species: string) {
        this.name = name;
        this.age = age;
        this.species = species;
    }

    public speak(): void {
        console.log(`${this.name} makes a sound`);
    }
}

// Inheritance
class Dog extends Animal {
    private breed: string;

    constructor(name: string, age: number, breed: string) {
        super(name, age, "canine");
        this.breed = breed;
    }

    public override speak(): void {
        console.log(`${this.name} barks!`);
    }
}

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

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

Functions

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

// Arrow function
const multiply = (a: number, b: number): number => a * b;

// Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string {
    return `${greeting}, ${name}`;
}

// Rest parameters
function sum(...numbers: number[]): number {
    return numbers.reduce((acc, n) => acc + n, 0);
}

// Function overloads
function process(value: string): string;
function process(value: number): number;
function process(value: any): any {
    if (typeof value === "string") {
        return value.toUpperCase();
    }
    if (typeof value === "number") {
        return value * 2;
    }
}

// Void return
function logMessage(msg: string): void {
    console.log(msg);
}

Generics

// Generic function
function identity<T>(value: T): T {
    return value;
}
let num = identity<number>(42);  // explicit
let str = identity("hello");    // inferred

// Generic interface
interface Box<T> {
    value: T;
    getValue(): T;
}

// Generic class
class Stack<T> {
    private items: T[] = [];

    public push(item: T): void {
        this.items.push(item);
    }
    public pop(): T | undefined {
        return this.items.pop();
    }
}

// Generic constraints
function getLength<T extends { length: number }>(obj: T): number {
    return obj.length;
}

Utility Types

Common Utilities
  • Partial<T>all properties optional
  • Required<T>all properties required
  • Readonly<T>all properties read‑only
  • Pick<T, K>select specific keys
  • Omit<T, K>exclude specific keys
  • Record<K, T>object with keys K of type T
Advanced Utilities
  • Exclude<T, U>remove types from T that are assignable to U
  • Extract<T, U>extract types from T that are assignable to U
  • NonNullable<T>remove null and undefined
  • ReturnType<T>return type of a function
  • Parameters<T>tuple of function parameters
  • Awaited<T>unwrap Promises

Examples

interface User {
    id: number;
    name: string;
    email: string;
    age?: number;
}

type UserPartial = Partial<User>;      // all optional
type UserReadonly = Readonly<User>;    // all read‑only
type UserNameOnly = Pick<User, "name">;  // { name: string }
type UserNoAge = Omit<User, "age">;    // without age
type UserMap = Record<"admin" | "user", User>;

Type Guards & Narrowing

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

// instanceof guard
function isDog(animal: Animal): animal is Dog {
    return animal instanceof Dog;
}

// In operator
if ("speak" in animal) {
    animal.speak();
}

// User‑defined type guard
function isValidPerson(obj: any): obj is Person {
    return obj typeof "object" && "name" in obj && "age" in obj;
}

// Narrowing with type predicates
function processValue(value: string | number) {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

Decorators (Experimental)

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

@sealed
class MyClass {}

// Method decorator
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function(...args: any[]) {
        console.log(`Calling ${propertyKey} with`, args);
        return original.apply(this, args);
    };
}

class Example {
    @log
    public greet(name: string): string {
        return `Hello, ${name}`;
    }
}

Modules

// Exporting
export interface User {
    id: number;
    name: string;
}

export const API_URL = "https://api.example.com";

export default class UserService {
    public getUser(id: number): User {
        return { id, name: "Alice" };
    }
}

// Importing
import UserService, { User, API_URL } from "./UserService";
import * as Utils from "./utils";  // namespace import

// Re‑export
export * from "./types";
export { User } from "./models";

Type Declarations (.d.ts)

// ambient declaration
declare module "my-library" {
    export function doSomething(): void;
    export interface Config {
        debug: boolean;
    }
}

// global declarations
declare global {
    interface Window {
        MY_APP_CONFIG: {
            version: string;
        };
    }
}

Conditional Types

// Basic conditional type
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">;  // true
type B = IsString<number>;   // false

// Type inference with infer
type ElementType<T> = T extends (infer U)[] ? U : never;
type C = ElementType<string[]>;  // string

// Distributive conditional types
type ToArray<T> = T extends any ? T[] : never;
type D = ToArray<string | number>;  // string[] | number[]

Mapped Types

// Basic mapped type
type ReadonlyFields<T> = {
    readonly [K in keyof T]: T[K];
};

// With property modifiers
type NullableFields<T> = {
    [K in keyof T]: T[K] | null;
};

// Key remapping
type Getters<T> = {
    [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "lib": ["ES2020", "DOM"],
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "declaration": true,
        "declarationMap": true,
        "sourceMap": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}

Best Practices

  • Use unknown instead of anyunknown is type‑safe, any opts out of type checking.
  • Enable strict mode in tsconfig.json for full type safety.
  • Use interface for objects that can be extended; use type for unions, intersections, and primitives.
  • Use readonly for properties that should not be mutated.
  • Use const assertions (as const) for literal types.
  • Use satisfies to check that an expression matches a type without widening it.
  • Use as const for enum‑like objects instead of enums when possible.
  • Use NonNullable utility type to remove null and undefined.
  • Use Pick and Omit to create derived types.
  • Use typeof to infer types from values.
  • Use keyof to get union of keys from a type.
  • Use @ts-expect-error instead of @ts-ignore to document expected errors.
📌 Quick Reference
Check TypeScript version: tsc --version
Compile: tsc
Compile with watch: tsc --watch
Initialize tsconfig: tsc --init
Run with ts‑node: npx ts-node file.ts
← Back to All Cheatsheets