TypeScript Cheat Sheet
TypeScript types, generics, utility types, interfaces, enums, and common patterns you need every day — in one quick-reference page.
7 sections 27 snippets
Basic Types
Primitives
let name: string = 'Alice';
let age: number = 30;
let active: boolean = true;
let id: bigint = 100n;
let sym: symbol = Symbol('id'); Arrays and tuples
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ['a', 'b'];
let pair: [string, number] = ['age', 30]; Any, unknown, never
let val: any = 42; // opts out of checking
let safe: unknown = 42; // must narrow before use
function fail(): never { throw new Error(); } Union and literal types
type Status = 'active' | 'inactive';
type ID = string | number;
let s: Status = 'active'; Interfaces and Type Aliases
Interface
interface User {
name: string;
age: number;
email?: string; // optional
readonly id: number; // immutable
} Extend interface
interface Admin extends User {
permissions: string[];
} Type alias
type Point = { x: number; y: number };
type Callback = (data: string) => void;
type Result = Success | Failure; Intersection types
type AdminUser = User & { permissions: string[] }; Generics
Generic function
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
first<number>([1, 2, 3]); // 1 Generic constraints
function getLength<T extends { length: number }>(item: T): number {
return item.length;
} Generic interface
interface ApiResponse<T> {
data: T;
status: number;
error?: string;
} Multiple type params
function merge<A, B>(a: A, b: B): A & B {
return { ...a, ...b };
} Utility Types
Partial and Required
Partial<User> // all fields optional
Required<User> // all fields required Pick and Omit
Pick<User, 'name' | 'email'> // only those keys
Omit<User, 'id'> // all except id Record
type Scores = Record<string, number>;
const s: Scores = { math: 90, eng: 85 }; ReturnType and Parameters
type R = ReturnType<typeof fetchUser>; // return type
type P = Parameters<typeof fetchUser>; // param tuple Readonly and NonNullable
Readonly<User> // all fields readonly
NonNullable<string | null> // string Type Guards and Narrowing
typeof guard
function format(val: string | number) {
if (typeof val === 'string') return val.toUpperCase();
return val.toFixed(2);
} in operator
if ('permissions' in user) {
// user is Admin here
} Custom type guard
function isUser(val: unknown): val is User {
return typeof val === 'object' && val !== null && 'name' in val;
} Discriminated unions
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number };
function area(s: Shape) {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2;
case 'rect': return s.width * s.height;
}
} Enums and Const Assertions
String enum
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
} as const
const ROLES = ['admin', 'user', 'guest'] as const;
type Role = typeof ROLES[number];
// 'admin' | 'user' | 'guest' satisfies operator
const config = {
port: 3000,
host: 'localhost',
} satisfies Record<string, string | number>; Common Patterns
Async function typing
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json();
} Event handler typing
function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log(e.currentTarget.value);
} Generic React component
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map(renderItem)}</ul>;
}