Generics & Utility Types

Difficulty: Intermediate

Question

What are generics in TypeScript and why are they better than using `any`? Write a type-safe generic function that works with any data type.

Answer

Generics let you write a function, class or type once and have it work with many types while keeping the exact type information. A type parameter like <T> is a placeholder that TypeScript fills in from the arguments at each call site, so first([1, 2, 3]) returns number and first(["a"]) returns string. With any you get reuse but lose all checking; with generics you get both.

How type parameters are inferred

When you call identity("upi"), the compiler sees that the argument has type string and binds T = string for that call. You rarely write the type argument yourself; you add it explicitly only when inference has nothing to work from, such as useState<User | null>(null) or new Map<string, number>(). Inference flows from arguments, not from the expected return type, which is why JSON.parse style functions still need an explicit annotation or a validator.

Constraining what T can be

An unconstrained T can be anything, so you cannot access .length or .id on it. Constraints fix that:

The keyof plus indexed-access pattern is the classic interview example because it shows generics relating two parameters to each other, which any can never do.

Generics vs any vs unknown

anyunknownGeneric T
Accepts every typeYesYesYes
Output keeps input's typeNoNoYes
Can call methods without checksYes, unsafeNoOnly what constraints allow

Where you see generics in real code

Common mistakes

How a generic call is typed. The compiler infers T from the argument and threads it to the return type.
  1. Call first([10, 20]): Argument has type number[].
  2. Infer T = number: Matches T[] against number[].
  3. Check the body once: Body is checked against the constraint, not each call.
  4. Return type number | undefined: Caller gets the precise type back.

Code examples

any vs generic

// any: reusable but the type is lost
function firstAny(arr: any[]): any {
  return arr[0];
}
const x = firstAny([1, 2, 3]); // any, x.toUpperCase() compiles and crashes

// generic: reusable and precise
function first<T>(arr: readonly T[]): T | undefined {
  return arr[0];
}
const n = first([1, 2, 3]);        // number | undefined
const s = first(["upi", "card"]);  // string | undefined
const e = first<boolean>([]);       // explicit when nothing to infer

The generic version infers T from each call and carries it to the return type, so misuse is caught at compile time.

Relating two type parameters with keyof

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

const order = { id: "ord_91", amountPaise: 49900, paid: true };

const amt = getProperty(order, "amountPaise"); // number
const paid = getProperty(order, "paid");       // boolean
// getProperty(order, "total");
// Error: Argument of type '"total"' is not assignable to
// parameter of type '"id" | "amountPaise" | "paid"'

K is constrained to the keys of T and the return type is the indexed access T[K], so both the key and the result are checked.

Generic API helper with a default type

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

async function getJson<T = unknown>(url: string): Promise<ApiResponse<T>> {
  const res = await fetch(url);
  return { data: (await res.json()) as T, status: res.status };
}

interface Restaurant { id: string; name: string; rating: number }

const { data } = await getJson<Restaurant[]>("/api/restaurants");
data[0].rating.toFixed(1); // fully typed

const raw = await getJson("/api/health"); // data: unknown, must narrow

The default of unknown forces callers who do not specify a type to narrow before use. Note the `as T` is still an unchecked assertion; validate untrusted data at the boundary.

Key points

Common follow-up questions

Interview tips

Concepts covered

Generics, Type Parameters, Generic Constraints, keyof, Type Argument Inference

More TypeScript Interview questions