Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to TypeScript
TypeScript Generics Explained

TypeScript Generics Explained

TypeScriptBy Muhammad Fareed
typescriptgenerics

Short answer: generics let you write reusable code that works with many types while keeping full type safety. You declare a type parameter, usually T, and TypeScript fills it in from how you use the function or type.

The problem generics solve

function firstAny(items: any[]): any {
  return items[0];
}

const x = firstAny([1, 2, 3]);   // x is any, so type safety is lost

Using any removes checking. Generics keep the relationship between input and output:

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

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

TypeScript infers T from the argument. You can also state it: first<string>(["a"]).

Generic interfaces and types

interface ApiResponse<T> {
  data: T;
  status: number;
  error?: string;
}

type User = { id: number; name: string };

const res: ApiResponse<User> = {
  data: { id: 1, name: "Asha" },
  status: 200,
};

const list: ApiResponse<User[]> = { data: [], status: 200 };

One definition now describes a response for any payload.

Generic classes

class Stack<T> {
  private items: T[] = [];
  push(item: T) { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
}

const numbers = new Stack<number>();
numbers.push(1);
// numbers.push("two");   // Error: string is not a number

Constraints with extends

Sometimes the type must have certain properties:

interface HasLength { length: number }

function longest<T extends HasLength>(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
// longest(10, 20);            // Error: number has no length

keyof and indexed access

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 1, name: "Asha" };
getProp(user, "name");     // string
// getProp(user, "age");   // Error: "age" is not a key of user

keyof T is a union of the property names of T, and T[K] is the type of that property.

Default type parameters

interface Box<T = string> {
  value: T;
}

const a: Box = { value: "text" };        // T defaults to string
const b: Box<number> = { value: 42 };

A practical example: a typed fetch helper

async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json() as Promise<T>;
}

type Post = { id: number; title: string };
const post = await getJson<Post>("/api/posts/1");
console.log(post.title);   // typed as string

The as cast trusts the server; validate untrusted data with a runtime checker if correctness matters.

Common mistakes

  • Using generics when a simple type would do. If a type parameter appears only once, you may not need it.
  • Over-constraining or under-constraining T.
  • Using any inside a generic function and losing the benefit.
  • Forgetting that <T> in .tsx files can look like JSX; write <T,> or <T extends unknown> for arrow functions.

Where generics appear in practice

Built-in types such as Array<T>, Promise<T> and Map<K, V> are generic, as are the utility types like Partial<T>; see utility types. For the object-shape side, read interfaces vs types, and for the basics, what TypeScript is.

FAQs

What does T stand for?

"Type". It is just a convention; you can use any name, and common ones are T, U, K and V.

What is the difference between generics and any?

any turns off type checking. Generics keep it by linking types together.

Can a function have multiple type parameters?

Yes: function pair<A, B>(a: A, b: B): [A, B].

Do generics exist at runtime?

No. They are erased when TypeScript compiles to JavaScript; they only help during development.