📘
Programming
TypeScript Quick Reference
Types, interfaces, generics, utility types, and best practices for TypeScript developers.
Back to Notes Library
TypeScript Quick Reference
Basic Types
typescript
// Primitives
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let nothing: null = null;
let undef: undefined = undefined;
// Any & Unknown
let x: any = 42; // avoid — skips type checking
let y: unknown = 42; // safe: must narrow before use
// Void & Never
function log(msg: string): void { console.log(msg); }
function fail(msg: string): never { throw new Error(msg); }
// Type assertion
const input = document.getElementById("name") as HTMLInputElement;Arrays & Tuples
typescript
// Arrays
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ["a", "b"];
// Readonly array
const ro: readonly number[] = [1, 2, 3];
// Tuples — fixed-length, typed positions
let pair: [string, number] = ["Alice", 30];
let triple: [string, number, boolean] = ["Alice", 30, true];
const [name2, age2] = pair; // destructureInterfaces & Types
typescript
// Interface
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // immutable
}
// Type alias
type Point = { x: number; y: number };
type ID = string | number;
// Extending interface
interface Admin extends User {
role: "admin" | "superadmin";
}
// Intersection types
type AdminUser = User & { role: string };Union & Intersection Types
typescript
// Union — one of these types
type Status = "pending" | "active" | "inactive";
type ID = string | number;
function process(input: string | number) {
if (typeof input === "string") {
return input.toUpperCase(); // narrowed to string
}
return input.toFixed(2); // narrowed to number
}
// Discriminated unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "rect"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
case "rect": return shape.width * shape.height;
}
}Generics
typescript
// Generic function
function identity<T>(value: T): T {
return value;
}
// Generic interface
interface Box<T> {
value: T;
transform: (val: T) => T;
}
// Generic class
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
}
// Constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}Utility Types
typescript
interface User {
id: number;
name: string;
email: string;
role: string;
}
// Partial<User> — all fields optional
// Required<User> — all fields required
// Readonly<User> — all fields readonly
// Pick<User, "id"|"name"> — only id and name
// Omit<User, "role"> — exclude role
// Record<string, User> — { [key: string]: User }
// Exclude<"a"|"b", "b"> — "a"
// NonNullable<T> — removes null/undefined
// ReturnType<typeof fn> — return type of function
// Parameters<typeof fn> — parameter types as tuple
// Example usage:
type CreateUserInput = Omit<User, "id">;
type PartialUser = Partial<User>;
type UserPreview = Pick<User, "id" | "name">;Functions
typescript
// Function types
type Fn = (a: number, b: number) => number;
const add: Fn = (a, b) => a + b;
// Optional & default params
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
// Overloads
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
if (typeof value === "string") return value.toUpperCase();
return value.toFixed(decimals ?? 2);
}Enums
typescript
// Numeric enum
enum Direction { Up, Down, Left, Right }
// Direction.Up === 0
// String enum (preferred)
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING",
}
// Const enum (inlined at compile time)
const enum Color { Red, Green, Blue }Type Guards & Narrowing
typescript
// typeof
if (typeof x === "string") { /* x is string here */ }
// instanceof
if (error instanceof Error) { error.message; }
// in operator
if ("name" in user) { user.name; }
// Custom type guard
function isUser(obj: unknown): obj is User {
return typeof obj === "object" && obj !== null && "id" in obj;
}Advanced Types
typescript
// keyof — union of property names
type UserKeys = keyof User; // "id" | "name" | "email" | "role"
// typeof — infer type from value
const config = { host: "localhost", port: 3000 };
type Config = typeof config; // { host: string; port: number }
// Conditional types
type IsString<T> = T extends string ? "yes" : "no";
// Template literal types
type EventName = `on${Capitalize<string>}`;
type CssSize = `${number}px` | `${number}%` | `${number}rem`;
// Mapped types
type Optional<T> = { [K in keyof T]?: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };10K+ Members Growing Daily
Get Free AI Notes Daily
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!
📚 Free Study Notes🤖 AI Tips Daily⚡ Prompt Templates💻 Coding Resources
Join Free Channel
No spam. Leave anytime.