Generics Interview Questions
What are generics and why are they better than any?
Generics are type parameters (<T>) that make code reusable across types while keeping the relationship between inputs and outputs. With any, first([1, 2]) returns any; with first<T>(items: T[]): T | undefined it returns number | undefined and mistakes are still caught.
What does T extends keyof U mean? Write a type-safe getProperty.
K extends keyof T constrains K to the property names of T. Combined with indexed access T[K], the return type follows the key.
getProperty
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const order = { id: "OD-1", total: 1299, paid: true };
const total = getProperty(order, "total"); // number
const paid = getProperty(order, "paid"); // boolean
console.log(total + 1, paid);Output
1300 true
What is a generic constraint and a default type parameter?
A constraint (<T extends { id: number }>) limits what T can be, so you can safely use t.id inside. A default (<T = unknown>) is used when the caller does not pass and TypeScript cannot infer T, e.g. interface ApiResponse<T = unknown> { data: T }.
What are const type parameters?
TypeScript 5.0: function f<const T>(x: T) infers the argument as if it were written with as const, keeping literal types. defineRoutes(["/", "/cart"]) then gives readonly ["/", "/cart"] instead of string[], without the caller adding as const.