Difficulty: Intermediate
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.
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.
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.
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.
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 |
async function get<T>(url: string): Promise<T> with ApiResponse<T> wrappers.Map<K, V>, Promise<T>, Array<T>, a typed LRU cache.useState<T>, generic <Select<T>> or <Table<Row>> components.Partial<T>, Pick<T, K>, Record<K, V> are all generic types.function log<T>(x: T): void. If T appears only once it adds nothing; use unknown instead.T from fetch().json() without validation. That is a type assertion in disguise; validate with Zod or similar at system boundaries.T extends any[] when readonly unknown[] would accept more inputs.// 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.
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.
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.
Generics, Type Parameters, Generic Constraints, keyof, Type Argument Inference