📡 You're offline — showing cached content
New version available!
Quick Access
TypeScript Reference

TypeScript

Static typing, interfaces, generics, and decorators.

All Topics

Type System Basics

Primitives & Literals
string, number, boolean, null, undefined, bigint, symbol. Literal types: "left" | "right".
Example: type Dir = "north" | "south" | "east" | "west"; let d: Dir = "north";
type vs interface
Interfaces are open (extendable via declaration merging). Types can be unions/intersections. Use interface for objects/classes.
Example: interface User { id: number; name: string; } // can be extended elsewhere
Intersection types (A & B)
Combine multiple types — object must satisfy ALL requirements. Useful for mixins and composition.
Example: type AdminUser = User & { permissions: string[]; auditLog: AuditEntry[]; };
Union types (A | B)
Value is ONE of the types. Narrow with typeof, instanceof, or discriminant field.
Example: type Result = { ok: true; data: User } | { ok: false; error: string };
Discriminated unions
Union where each member has a shared literal field — TypeScript narrows automatically in switch/if.
Example: type Event = {type:'click';x:number} | {type:'key';key:string}; // switch(e.type)
Tuple types
Fixed-length array with specific types at each position. Labeled tuples improve readability.
Example: type RGB = [r: number, g: number, b: number]; const red: RGB = [255, 0, 0];
Enums vs const enums / as const
const enums are inlined at compile time. as const on objects creates readonly literal types.
Example: const STATUS = { ACTIVE: 'active', PENDING: 'pending' } as const; type Status = typeof STATUS[keyof typeof STATUS];
never type
Exhaustiveness checking — if TS infers never, you missed a union case. Also return type of always-throws.
Example: function assertNever(x: never): never { throw new Error('Unexpected: ' + x); }

Generics

Generic functions
Type parameter inferred from arguments — write algorithms once, use with any type.
Example: function first<T>(arr: T[]): T | undefined { return arr[0]; }
Generic constraints (extends)
Restrict what T can be — ensures specific properties/methods are available.
Example: function getLen<T extends { length: number }>(x: T): number { return x.length; }
Default type parameters
Provide fallback type if generic isn't specified explicitly.
Example: type ApiResponse<T = unknown> = { data: T; status: number; };
Conditional types (T extends U ? X : Y)
Branch type logic based on type relationships — powerful for utility types and inference.
Example: type IsArray<T> = T extends any[] ? true : false;
infer keyword
Extract a type from a generic type position in conditional types.
Example: type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
Mapped types
Transform object types key-by-key. Combine with as for key remapping.
Example: type Optional<T> = { [K in keyof T]?: T[K] }; // makes all props optional
Template literal types
String manipulation at the type level. Construct event names, CSS class strings, routes.
Example: type EventName<T extends string> = `on${Capitalize<T>}`; type ClickEv = EventName<"click">; // "onClick"

Utility Types

Partial<T> / Required<T>
Make all properties optional / required. Partial is perfect for update/patch request bodies.
Example: function updateUser(id: number, patch: Partial<User>): Promise<User>
Readonly<T>
Make all properties readonly — prevent accidental mutation. Deep with DeepReadonly custom type.
Example: const config: Readonly<Config> = Object.freeze({ port: 3000 });
Pick<T, K> / Omit<T, K>
Pick = keep only listed keys. Omit = remove listed keys. Both type-safe key selection.
Example: type PublicUser = Omit<User, 'password' | 'internalNotes'>;
Record<K, V>
Create object type with specific key and value types. Perfect for maps and lookup tables.
Example: const cache: Record<string, User> = {}; const roles: Record<'admin'|'user', Permission[]> = {...};
ReturnType<T> / Parameters<T>
Extract return type / parameter types of a function type at compile time.
Example: type Handler = (req: Request) => Response; type Req = Parameters<Handler>[0];
Awaited<T>
Unwrap Promise type recursively. Replaces complex infer patterns.
Example: type UserData = Awaited<ReturnType<typeof fetchUser>>;
Extract<T,U> / Exclude<T,U>
Filter union types — Extract keeps members assignable to U; Exclude removes them.
Example: type StringOrNum = string | number | boolean; type OnlyStr = Extract<StringOrNum, string>;

Type Narrowing & Guards

typeof / instanceof
Narrow primitive types with typeof / class instances with instanceof.
Example: if (typeof x === 'string') x.toUpperCase(); if (x instanceof Date) x.getTime();
in operator narrowing
"key" in obj narrows to types that have that property — great for discriminated unions.
Example: if ('data' in result) console.log(result.data); // result is success type
Type predicates (x is T)
Custom type guard function — when it returns true, TS narrows argument to T.
Example: function isUser(x: unknown): x is User { return typeof x === 'object' && x !== null && 'id' in x; }
Assertion functions
Function that asserts condition or throws — narrows type without returning boolean.
Example: function assertDefined<T>(val: T): asserts val is NonNullable<T> { if (!val) throw new Error('Null!'); }
satisfies operator
Verify value satisfies type without widening it — keeps literal types while still type-checking.
Example: const palette = { red: [255,0,0], blue: '#0000ff' } satisfies Record<string, string|number[]>;
as const assertion
Infer narrowest literal type for the entire value. Arrays become readonly tuples.
Example: const routes = ['/home', '/about', '/contact'] as const; // readonly ["/home", "/about", "/contact"]

Decorators & Declaration Files

Class decorators
Function that receives class constructor — metadata, mixins, dependency injection.
Example: @injectable() @singleton() class UserService { constructor(@inject('DB') private db: Database) {} }
@Input() / @Output() style
Property decorators annotate class fields with metadata for frameworks (Angular, NestJS, etc.).
Example: @Controller('/users') class UsersCtrl { @Get('/:id') find(@Param('id') id: string) {} }
Declaration files (.d.ts)
Type information for JS libraries without rewriting in TS. DefinitelyTyped (@types/x).
Example: declare module 'old-lib' { export function doThing(x: string): number; }
tsconfig strict: true
Enables strictNullChecks, noImplicitAny, strictFunctionTypes + more at once. Always enable.
Example: { "compilerOptions": { "strict": true, "target": "ES2022", "moduleResolution": "bundler" } }
Path aliases
Configure @/ imports in tsconfig.json + bundler config — cleaner than ../../../.
Example: "paths": { "@/*": ["./src/*"] } // then import { auth } from '@/services/auth'