A
AiTechWorlds
AiTechWorlds
Types, interfaces, generics, utility types, and best practices for TypeScript developers.

// 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
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; // destructure// 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 โ 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;
}
}// 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];
}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">;// 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);
}// 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 }// 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;
}// 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 };Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Last reviewed on June 13, 2026 by the AiTechWorlds Notes Team. Free cheat sheet no signup required.
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content 100% free!
No spam. Leave anytime.