Functions and Generics

Harry · 14 Sep 2026 · 2 views
Advertisement
Advertisement

Typing functions

function add(a: number, b: number): number {
  return a + b;
}

// arrow function with an inferred return type
const multiply = (a: number, b: number) => a * b;

// optional and default parameters
function greet(name: string, greeting = "Hello"): string {
  return `${greeting}, ${name}`;
}

A ? after a parameter name makes it optional; a default value both provides a fallback and makes the parameter optional.

Why generics

Without generics you either write the same function for every type or fall back to any and lose safety. A generic keeps the type flexible and checked. The type parameter (conventionally T) is filled in when the function is called:

function first<T>(items: T[]): T {
  return items[0];
}

const n = first([1, 2, 3]);        // n is number
const s = first(["a", "b"]);       // s is string

The return type follows the input type automatically – no casting, full autocomplete.

Generic constraints

Constrain a type parameter with extends so you can rely on certain properties:

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest("hello", "hi");            // works: strings have length
longest([1,2,3], [1]);             // works: arrays have length

Generic interfaces

interface ApiResponse<T> {
  data: T;
  status: number;
}
const res: ApiResponse<User> = { data: user, status: 200 };

Key points

  • Annotate parameters and return types; use ? and defaults for optional inputs.
  • Generics keep code reusable while preserving type information.
  • The type parameter is inferred from the arguments at the call site.
  • Constrain generics with extends to use specific properties safely.
Share this post:

Comments (0)

Please login or register to comment.