TypeScript Quick Reference
A quick lookup for TypeScript concepts and syntax grouped by category. All examples assume TypeScript 5+ with strict mode enabled.
Primitive Types
Section titled “Primitive Types”| Type | Examples | Notes |
|---|---|---|
string | 'hello', "world" | Text |
number | 42, 3.14, -1 | All numbers (int and float) |
boolean | true, false | |
null | null | Explicit absence of value |
undefined | undefined | Uninitialized variable |
bigint | 100n | Large integers |
symbol | Symbol('id') | Unique identifiers |
Type Annotations
Section titled “Type Annotations”// Variablelet name: string = 'Alice';let count: number = 0;let isActive: boolean = true;
// Function parameters and return typefunction greet(name: string): string { return `Hello, ${name}`;}
// Arrow functionconst add = (a: number, b: number): number => a + b;
// No return valuefunction log(msg: string): void { console.log(msg);}
// Function that never returnsfunction fail(msg: string): never { throw new Error(msg);}Arrays and Tuples
Section titled “Arrays and Tuples”// Arrayslet names: string[] = ['Alice', 'Bob'];let scores: Array<number> = [95, 87, 100];
// Readonly arrayconst ids: readonly number[] = [1, 2, 3];
// Tuple — fixed length, specific types at each positionlet point: [number, number] = [10, 20];let entry: [string, number] = ['score', 100];
// Optional tuple elementlet pair: [string, number?] = ['alone'];Interfaces
Section titled “Interfaces”interface User { id: number; name: string; email?: string; // optional property readonly createdAt: Date; // cannot be reassigned after creation}
// Extending an interfaceinterface Admin extends User { role: 'admin' | 'superadmin'; permissions: string[];}
// Function type in interfaceinterface Formatter { format(value: number): string;}
// Index signature — any number of properties with string keysinterface Dictionary { [key: string]: string;}Type Aliases
Section titled “Type Aliases”// Object shape (similar to interface)type Point = { x: number; y: number;};
// Union typetype Status = 'pending' | 'active' | 'closed';type ID = string | number;
// Intersection type — combines multiple typestype AdminUser = User & { role: string };
// Function typetype Callback = (error: Error | null, result?: string) => void;
// Conditional typetype IsString<T> = T extends string ? true : false;Interface vs type alias: Use interface for object shapes that may be extended. Use type for unions, intersections, primitives, and computed types.
Literal Types
Section titled “Literal Types”// String literalstype Direction = 'north' | 'south' | 'east' | 'west';type Theme = 'light' | 'dark';
// Number literalstype DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
// Boolean literaltype AlwaysTrue = true;
// Template literal typetype EventName = `on${string}`; // matches 'onClick', 'onChange', etc.// Numeric enum (default — values auto-increment from 0)enum Direction { Up, // 0 Down, // 1 Left, // 2 Right, // 3}
// String enum (preferred — values are readable at runtime)enum Status { Pending = 'PENDING', Active = 'ACTIVE', Closed = 'CLOSED',}
const current: Status = Status.Active;console.log(current); // 'ACTIVE'Generics
Section titled “Generics”// Generic functionfunction identity<T>(value: T): T { return value;}identity<string>('hello');identity(42); // TypeScript infers T = number
// Generic with constraintfunction getLength<T extends { length: number }>(value: T): number { return value.length;}getLength('hello'); // 5getLength([1, 2, 3]); // 3
// Generic interfaceinterface ApiResponse<T> { data: T; status: number; message: string;}
// Using ittype UserResponse = ApiResponse<User>;type ListResponse = ApiResponse<User[]>;
// Generic classclass Stack<T> { private items: T[] = []; push(item: T): void { this.items.push(item); } pop(): T | undefined { return this.items.pop(); }}const stack = new Stack<number>();stack.push(1);Type Narrowing
Section titled “Type Narrowing”// typeof guardfunction processInput(input: string | number) { if (typeof input === 'string') { return input.toUpperCase(); // TypeScript knows it's a string here } return input.toFixed(2); // TypeScript knows it's a number here}
// instanceof guardfunction handleError(error: unknown) { if (error instanceof Error) { console.log(error.message); // Error properties available }}
// in operator guardinterface Dog { bark(): void; }interface Cat { meow(): void; }
function makeSound(animal: Dog | Cat) { if ('bark' in animal) { animal.bark(); } else { animal.meow(); }}
// Truthiness guardfunction printName(name: string | null) { if (name) { console.log(name.toUpperCase()); // name is string here }}
// Discriminated uniontype Shape = | { kind: 'circle'; radius: number } | { kind: 'square'; side: number };
function area(shape: Shape): number { switch (shape.kind) { case 'circle': return Math.PI * shape.radius ** 2; case 'square': return shape.side ** 2; }}
// Type predicatefunction isString(value: unknown): value is string { return typeof value === 'string';}Utility Types
Section titled “Utility Types”| Utility | What it does | Example |
|---|---|---|
Partial<T> | All properties optional | Partial<User> |
Required<T> | All properties required | Required<User> |
Readonly<T> | All properties readonly | Readonly<User> |
Pick<T, K> | Keep only listed keys | Pick<User, 'id' | 'name'> |
Omit<T, K> | Exclude listed keys | Omit<User, 'password'> |
Record<K, V> | Object with key type K and value type V | Record<string, number> |
Exclude<T, U> | Remove types from union | Exclude<Status, 'closed'> |
Extract<T, U> | Keep only types in union | Extract<string | number, string> |
NonNullable<T> | Remove null and undefined | NonNullable<string | null> |
ReturnType<T> | Return type of a function | ReturnType<typeof greet> |
Parameters<T> | Parameter types as tuple | Parameters<typeof greet> |
// Examplestype UserPreview = Pick<User, 'id' | 'name'>;type SafeUser = Omit<User, 'password' | 'secret'>;type UpdateUser = Partial<Pick<User, 'name' | 'email'>>;type Scores = Record<string, number>;Classes
Section titled “Classes”class Animal { // Access modifiers public name: string; private age: number; protected species: string; readonly id: string;
constructor(name: string, age: number, species: string) { this.name = name; this.age = age; this.species = species; this.id = crypto.randomUUID(); }
// Getter get info(): string { return `${this.name} (${this.species})`; }
// Static method static create(name: string): Animal { return new Animal(name, 0, 'unknown'); }}
// Extendingclass Dog extends Animal { breed: string;
constructor(name: string, breed: string) { super(name, 2, 'Canis lupus'); this.breed = breed; }
bark(): void { console.log(`${this.name} says woof!`); }}
// Shorthand parameter propertiesclass Point { constructor( public x: number, public y: number, private label: string = 'point' ) {}}| Modifier | Accessible from |
|---|---|
public | Anywhere (default) |
private | Only inside this class |
protected | Inside this class and subclasses |
readonly | Read anywhere, set only in constructor |
DOM Types
Section titled “DOM Types”// Selecting elementsconst btn = document.querySelector<HTMLButtonElement>('#submit');const input = document.querySelector<HTMLInputElement>('.search');const items = document.querySelectorAll<HTMLLIElement>('.item');
// Type assertionconst canvas = document.getElementById('myCanvas') as HTMLCanvasElement;
// Null checks required with strict modebtn?.addEventListener('click', handleClick); // optional chaininginput!.value; // non-null assertion (use sparingly)
if (btn) { btn.textContent = 'Submitted'; // narrowed to HTMLButtonElement}
// Event typesfunction handleClick(e: MouseEvent): void { ... }function handleInput(e: InputEvent): void { const target = e.target as HTMLInputElement; console.log(target.value);}function handleSubmit(e: SubmitEvent): void { e.preventDefault();}function handleKey(e: KeyboardEvent): void { if (e.key === 'Enter') { ... }}Special Types
Section titled “Special Types”| Type | Meaning |
|---|---|
any | Opts out of type checking — avoid |
unknown | Type-safe alternative to any — must narrow before use |
never | A value that can never occur (exhaustive checks, throwing functions) |
void | Function returns nothing meaningful |
object | Any non-primitive value |
// unknown — must check before usefunction parse(input: unknown): string { if (typeof input === 'string') return input; if (typeof input === 'number') return input.toString(); throw new Error('Unsupported type');}
// never — exhaustive switch checkfunction assertNever(x: never): never { throw new Error('Unexpected value: ' + x);}tsconfig.json Key Options
Section titled “tsconfig.json Key Options”{ "compilerOptions": { "target": "ES2020", // output JavaScript version "module": "ESNext", // module system "strict": true, // enables all strict checks "noImplicitAny": true, // error on implicit any "strictNullChecks": true, // null/undefined must be handled explicitly "outDir": "./dist", // compiled output directory "rootDir": "./src", // source files root "esModuleInterop": true, // better CommonJS/ESModule interop "forceConsistentCasingInFileNames": true, "skipLibCheck": true // skip type checking of .d.ts files }}