Programming62 entries

TypeScript Essentials

Types, interfaces, generics, utility types, type guards, and advanced TypeScript patterns

1Basic Types

let name: string = "hello"
String type annotation
let age: number = 25
Number type (int & float)
let active: boolean = true
Boolean type
let items: string[] = ["a", "b"]
Array of strings
let tuple: [string, number] = ["a", 1]
Tuple with fixed types
let anything: any = 42
Opt out of type checking
let unknown: unknown = getData()
Type-safe alternative to any
let nothing: void = undefined
Void (no return value)
let impossible: never
Never type (unreachable code)
let nullable: string | null = null
Nullable type with union

2Interfaces & Type Aliases

interface User { name: string; age: number; }
Define an object shape
interface User { email?: string; }
Optional property with ?
interface User { readonly id: number; }
Read-only property
interface Admin extends User { role: string; }
Extend an interface
type ID = string | number
Type alias with union
type Point = { x: number; y: number }
Type alias for object
type Callback = (data: string) => void
Function type alias
type Status = "active" | "inactive"
String literal union type

3Generics

function identity<T>(arg: T): T { return arg; }
Generic function
interface Box<T> { value: T; }
Generic interface
function getLength<T extends { length: number }>(x: T)
Constrained generic
type Pair<K, V> = { key: K; value: V }
Multiple type parameters
function create<T = string>(val: T)
Default generic type
class Stack<T> { items: T[] = []; push(item: T) {} }
Generic class

4Utility Types

Partial<User>
Make all properties optional
Required<User>
Make all properties required
Readonly<User>
Make all properties read-only
Pick<User, "name" | "email">
Pick specific properties
Omit<User, "password">
Omit specific properties
Record<string, number>
Object with typed key-value pairs
ReturnType<typeof fn>
Extract function return type
Parameters<typeof fn>
Extract function parameter types
Awaited<Promise<string>>
Unwrap Promise type
NonNullable<string | null>
Remove null and undefined

5Type Guards & Narrowing

if (typeof x === "string") { ... }
typeof type guard
if (x instanceof Date) { ... }
instanceof type guard
if ("name" in obj) { ... }
Property existence check
function isUser(x: any): x is User { ... }
Custom type predicate
value as string
Type assertion (use sparingly)
value!.property
Non-null assertion operator
value ?? "default"
Nullish coalescing
obj?.nested?.prop
Optional chaining

6Enums & Mapped Types

enum Direction { Up, Down, Left, Right }
Numeric enum (0, 1, 2, 3)
enum Color { Red = "#f00", Blue = "#00f" }
String enum
const enum Status { Active = 1 }
Const enum (inlined at compile)
type Flags = { [K in keyof User]: boolean }
Mapped type from keys
type ReadonlyUser = { readonly [K in keyof User]: User[K] }
Mapped readonly type
[key: string]: unknown
Index signature for dynamic keys

7Functions & Overloads

function greet(name: string): string { ... }
Typed function with return type
const add = (a: number, b: number): number => a + b
Arrow function with types
function log(msg: string, level?: string)
Optional parameter
function log(msg: string, level = "info")
Default parameter value
function sum(...nums: number[]): number
Rest parameters
function parse(input: string): number;
Function overload signature

8Advanced Patterns

type EventMap = { click: MouseEvent; keydown: KeyboardEvent }
Discriminated type map
type DeepPartial<T> = { [K in keyof T]?: DeepPartial<T[K]> }
Recursive partial type
type Keys = keyof User
Get union of object keys
type Val = User["name"]
Indexed access type
type IsString<T> = T extends string ? true : false
Conditional type
type Flatten<T> = T extends Array<infer U> ? U : T
Infer keyword in conditional
satisfies Record<string, number>
Validate type without widening
as const
Const assertion for literal types