Menu

Generic Functions

Lesson 1: Generic Functions

Why do we need generics?

Approach Works for many types? Keeps the exact type?
Write one function per type Yes, with lots of duplication Yes
Use any Yes No: result is any
Use unknown Yes No: result must be checked again
Use a generic <T> Yes Yes

Example

// Without generics: the return type is lost
function firstAny(items: any[]): any {
  return items[0];
}

// With generics: T is filled in by each call
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const product = first([{ name: 'Milk 1L', price: 6400 }]); // { name: string; price: number } | undefined
const slot = first(['morning', 'evening']);                 // string | undefined
const count = first<number>([3, 1, 2]);                     // explicit type argument

// Several type parameters
function pair<K, V>(key: K, value: V): [K, V] {
  return [key, value];
}
const entry = pair('MILK-1L', 40); // [string, number]

// Generic arrow function
const lastItem = <T,>(items: readonly T[]): T | undefined => items[items.length - 1];

How it works

  • <T> declares a type parameter. T is just a name; conventional names are T, K, V, E, or descriptive ones like TItem.
  • TypeScript infers T from the arguments, so you rarely write first<number>(...).
  • The relationship between input and output is preserved: whatever goes in determines what comes out.
  • In .tsx files, write <T,> in arrow functions so the parser does not mistake it for JSX.

Common mistakes

Mistake Effect Fix
Using any instead of a type parameter Return type lost Use <T>
A type parameter used only once Adds complexity with no benefit Replace it with the concrete type or unknown
Writing type arguments everywhere Noisy code Let TypeScript infer them

Key takeaways

  • Generics let one function work with many types while keeping the exact type.
  • A type parameter is useful only when it links two or more places, such as input and output.

Try it: Write a generic groupBy<T>(items: T[], getKey: (item: T) => string): Record<string, T[]> and use it to group products by category.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details