TypeScript Cheatsheet: Master Core Concepts & Best Practices

Installing, running, types, classes, all the basics

Page content

Here is my concise TypeScript cheatsheet covering key concepts, syntax, and code examples commonly referenced by developers:

typescript cheatsheet 3d

TypeScript Cheatsheet

Getting Started

  • Install globally:
    npm install -g typescript
    
  • Compile file:
    tsc filename.ts
    
  • Check version:
    tsc --version
    

Basic Types

let a: number = 10;
let s: string = "TypeScript";
let b: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ["TS", 2025];
let anyValue: any = "Flexible";
let unknownVal: unknown = 5;
let notDefined: undefined = undefined;
let notPresent: null = null;

Union & Literal Types

let id: number | string = 42;
let direction: 'left' | 'right' = 'left';

Type Aliases & Interfaces

type Point = { x: number; y: number };
interface Person { name: string; age: number; }
let user: Person = { name: "Alice", age: 25 };

Functions

function sum(a: number, b: number): number {
  return a + b;
}
const multiply = (a: number, b: number): number => a * b;
function log(msg: string): void { console.log(msg); }

Classes

class Animal {
  name: string;
  constructor(name: string) { this.name = name; }
  move(distance: number = 0): void { console.log(`${this.name} moved ${distance}`); }
}

Access Modifiers

  • public (default), private, protected, readonly
class Point {
  constructor(private x: number, private y: number) {}
}

Generics

function identity(arg: T): T { return arg; }
let output = identity("myString");

Enums

enum ResourceType { BOOK, FILE, FILM }
let r: ResourceType = ResourceType.BOOK;

Type Assertions / Casting

let someVal: unknown = "Hello";
let strLength: number = (someVal as string).length;

Modules

// Export
export function foo() {}
// Import
import { foo } from "./module";

Advanced Types

  • Intersection:
    type A = { a: number }; type B = { b: number };
    type AB = A & B; // { a: number, b: number }
    
  • Conditional:
    type IsString = T extends string ? true : false;
    
  • Mapped:
    type Readonly = { readonly [P in keyof T]: T[P]; }
    
  • Template Literal Type:
    type EventName = `on${Capitalize}`;
    

Useful Utility Types

Partial, Required, Readonly, Pick, Omit, Record

Narrowing

  • Use typeof and instanceof for type narrowing:
function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value;
  }
  return padding + value;
}

This summary provides core syntax and features essential for most TypeScript development workflows.