# Generics & Utility Types

> 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.

Canonical: https://www.internhack.in/learn/interview/typescript-interview/ts-generics-interview
Last updated: 2026-11-28

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:

- `<T extends { id: string }>` accepts any object that has at least an `id`.
- `<T, K extends keyof T>` ties a second parameter to the keys of the first, enabling `getProperty(obj, key): T[K]`.
- `<T = string>` sets a default when nothing is inferred or passed.

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

|  | `any` | `unknown` | Generic `T` |
| --- | --- | --- | --- |
| Accepts every type | Yes | Yes | Yes |
| Output keeps input's type | No | No | Yes |
| Can call methods without checks | Yes, unsafe | No | Only what constraints allow |

### Where you see generics in real code

- API layers: `async function get<T>(url: string): Promise<T>` with `ApiResponse<T>` wrappers.
- Collections and caches: `Map<K, V>`, `Promise<T>`, `Array<T>`, a typed LRU cache.
- React: `useState<T>`, generic `<Select<T>>` or `<Table<Row>>` components.
- Utility types: `Partial<T>`, `Pick<T, K>`, `Record<K, V>` are all generic types.

### Common mistakes

- Using a type parameter only once, like `function log<T>(x: T): void`. If `T` appears only once it adds nothing; use `unknown` instead.
- Returning `T` from `fetch().json()` without validation. That is a type assertion in disguise; validate with Zod or similar at system boundaries.
- Over-constraining with `T extends any[]` when `readonly unknown[]` would accept more inputs.

**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

- A type parameter is inferred per call from the arguments; explicit type arguments are the exception.
- Use \`extends\` constraints to unlock property access on T.
- \`K extends keyof T\` with return type \`T\[K\]\` is the canonical constrained generic.
- If a type parameter appears only once in a signature, it is probably unnecessary.
- Generics are erased at runtime; you cannot do \`typeof T\` or \`new T()\` without passing a constructor.

## Common follow-up questions

- How would you implement Partial<T> yourself?
- Why can you not write \`new T()\` inside a generic function?
- What are const type parameters introduced in TypeScript 5.0?
- When would you use NoInfer<T>?

## Interview tips

- Write the any version first, then the generic version, and point at the inferred types; it makes the value obvious.
- Mention that generics are compile-time only, which shows you understand type erasure.
- Bring up validation at API boundaries so you do not sound like generics make fetched data safe.

## Concepts covered

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

Previous: [Type System Fundamentals](https://www.internhack.in/learn/interview/typescript-interview/ts-type-system-basics) · Next: [Type Guards & Narrowing](https://www.internhack.in/learn/interview/typescript-interview/ts-type-guards-narrowing) · [All of TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)

## More TypeScript Interview questions

- [Why TypeScript? JS vs TS](https://www.internhack.in/learn/interview/typescript-interview/ts-why-typescript)
- [Basic Types & Annotations](https://www.internhack.in/learn/interview/typescript-interview/ts-basic-types)
- [Arrays, Tuples & Enums](https://www.internhack.in/learn/interview/typescript-interview/ts-arrays-tuples-enums)
- [Functions & Overloads](https://www.internhack.in/learn/interview/typescript-interview/ts-functions-overloads)
- [Object Types & Optional Props](https://www.internhack.in/learn/interview/typescript-interview/ts-object-types)
- [Union & Intersection Types](https://www.internhack.in/learn/interview/typescript-interview/ts-union-intersection)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)
