TypeScript generics, overloads and async functions
Functions are where types pay off most: a well-typed function tells every caller what it accepts and what it returns, and the compiler checks both ends. This hub covers the features that let one function serve many types without giving up that checking. Generics let a function, class or interface take a type as a parameter; constraints and defaults control which types are allowed; overloads give one function several distinct signatures; and async functions need their own typing rules for promises and errors.
The Functions and generics tutorial introduces parameter and return types, optional parameters and a first generic function. This hub assumes that and goes further. Every sample is a complete ES module from an invented online shop, OrdersPortal, compiled with TypeScript 7.0.2 (tsc --strict --target es2025 --module nodenext) and run with Node.js 22. Save one as sample.ts next to a package.json containing {"type": "module"}, then run npx tsc --strict sample.ts and node sample.js.
Topics on this page
Section titled “Topics on this page”| Topic | Since | Use it when |
|---|---|---|
| Generics | TypeScript 0.9 | The same code works for many types and must keep them connected. |
| Generic constraints and defaults | Constraints 0.9; defaults 2.3; const 5.0 |
A type parameter needs certain members, or a sensible default. |
| Function overloads | Early releases | The return type depends on which kind of argument was passed. |
| Async functions | ES2015 targets 1.7; all targets 2.1 | A function awaits promises and returns one. |
Generics
Section titled “Generics”Generics arrived in TypeScript 0.9 (2013). A generic function declares one or more type parameters in angle brackets, conventionally T, K or a descriptive name such as TItem, and uses them in its parameter and return types. Each call fills in the type parameters, usually by inference from the arguments, so first(["a", "b"]) returns string | undefined and first([1, 2]) returns number | undefined from one implementation.
The point of a type parameter is to connect types: the element type of the input array to the return type, the key you pass to the property type you get back. If a type parameter appears only once in a signature, it connects nothing, and a plain type (often unknown) is simpler. Classes and interfaces take type parameters the same way, which is how the standard library defines Array<T>, Map<K, V> and Promise<T>.
Compared with any, a generic keeps checking on: the compiler knows the exact type that comes out, and rejects misuse of it.
interface Order { id: string; customerId: string; total: number;}
interface Customer { id: string; name: string;}
class Repository<TEntity extends { id: string }> { private readonly items = new Map<string, TEntity>();
save(item: TEntity): void { this.items.set(item.id, item); }
find(id: string): TEntity | undefined { return this.items.get(id); }
all(): TEntity[] { return [...this.items.values()]; }}
function groupBy<TItem, TKey extends PropertyKey>( items: readonly TItem[], keyOf: (item: TItem) => TKey,): Record<TKey, TItem[]> { const groups = {} as Record<TKey, TItem[]>; for (const item of items) { (groups[keyOf(item)] ??= []).push(item); } return groups;}
const orders = new Repository<Order>();orders.save({ id: "ORD-1", customerId: "C-1", total: 40 });orders.save({ id: "ORD-2", customerId: "C-2", total: 15 });orders.save({ id: "ORD-3", customerId: "C-1", total: 25 });
const customers = new Repository<Customer>();customers.save({ id: "C-1", name: "Ada Lopez" });
const byCustomer = groupBy(orders.all(), (o) => o.customerId);for (const [customerId, list] of Object.entries(byCustomer)) { const name = customers.find(customerId)?.name ?? "unknown"; console.log(`${customerId} (${name}): ${list.map((o) => o.id).join(", ")}`);}Output:
C-1 (Ada Lopez): ORD-1, ORD-3C-2 (unknown): ORD-2Pitfalls:
- Explicit type arguments are rarely needed. Let inference work; write
new Repository<Order>()only where nothing else tells the compiler the type, as with an empty collection. - Generics are erased. There is no
Tat run time, sonew T()orvalue instanceof Tis impossible. Pass a constructor or a type guard as a parameter instead. - An assertion inside is still an assertion.
{} as Record<TKey, TItem[]>ingroupByis safe only because the loop fills it; keep such casts small and local.
Generic constraints and defaults
Section titled “Generic constraints and defaults”Constraints have been available since generics arrived in TypeScript 0.9, type parameter defaults since 2.3 and const type parameters since 5.0. A constraint, T extends Shape, limits which types a caller may pass and, in return, lets the function body use the members of Shape. Repository<TEntity extends { id: string }> above can call item.id for exactly that reason.
The most useful constraint is K extends keyof T: the key must be one of T’s property names, and the indexed access type T[K] is the type of that property. That is how a type-safe pluck or sortBy knows that sorting orders by "total" compares numbers.
A default, <T = string>, is used when a type argument is neither passed nor inferable, which is mostly useful for generic interfaces and classes. A const type parameter (<const T>) asks the compiler to infer arguments as if they were written with as const, keeping literal types such as "paid" instead of widening them to string.
interface Order { id: string; status: "pending" | "paid" | "shipped"; total: number;}
function sortBy<T, K extends keyof T>(items: readonly T[], key: K): T[] { return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));}
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] { return items.map((item) => item[key]);}
interface ApiResult<TData = unknown> { ok: boolean; data: TData;}
function defineStatuses<const T extends readonly string[]>(statuses: T): T { return statuses;}
const orders: Order[] = [ { id: "ORD-2", status: "paid", total: 15 }, { id: "ORD-1", status: "pending", total: 40 },];
const totals: number[] = pluck(sortBy(orders, "total"), "total");console.log(totals, pluck(sortBy(orders, "id"), "status"));
const raw: ApiResult = { ok: true, data: "anything" }; // TData defaults to unknownconst typed: ApiResult<Order[]> = { ok: true, data: orders };console.log(typeof raw.data, typed.data.length);
const statuses = defineStatuses(["pending", "paid"]); // readonly ["pending", "paid"]console.log(statuses.join(" -> "));Output:
[ 15, 40 ] [ 'pending', 'paid' ]string 2pending -> paidPassing a key that does not exist, sortBy(orders, "date"), fails with error TS2345: Argument of type '"date"' is not assignable to parameter of type 'keyof Order'.
Pitfalls:
- A constraint is not the type. Inside
function f<T extends Order>(x: T), returning a newOrderwhereTis expected is an error, becauseTcould be a subtype with more properties. - Over-constraining hurts reuse. Require only the members you use:
{ id: string }, not the wholeOrderinterface.
Function overloads
Section titled “Function overloads”Function overloads have been part of TypeScript since its early releases. You write several overload signatures followed by one implementation signature with a body. Callers see only the overload signatures; the implementation signature must be compatible with all of them and is invisible from outside. The compiler picks the first overload, from top to bottom, that matches the arguments.
Overloads are worth it when the return type depends on the argument type in a way a union cannot express: findOrders("ORD-1") returns one order or undefined, while findOrders({ status: "paid" }) returns an array. When every overload returns the same type, a single signature with a union parameter is simpler and also accepts union-typed arguments, which overloads do not.
The compiler checks the overload signatures against the implementation signature, but not each overload against the implementation’s body, so it is your job to make the body honor every overload.
interface Order { id: string; status: "pending" | "paid" | "shipped"; total: number;}
const orders: Order[] = [ { id: "ORD-1", status: "paid", total: 40 }, { id: "ORD-2", status: "pending", total: 15 }, { id: "ORD-3", status: "paid", total: 25 },];
function findOrders(id: string): Order | undefined;function findOrders(filter: { status: Order["status"] }): Order[];function findOrders(arg: string | { status: Order["status"] }): Order | Order[] | undefined { if (typeof arg === "string") { return orders.find((o) => o.id === arg); } return orders.filter((o) => o.status === arg.status);}
const one = findOrders("ORD-2"); // Order | undefinedconst paid = findOrders({ status: "paid" }); // Order[]console.log(one?.total, paid.map((o) => o.id));Output:
15 [ 'ORD-1', 'ORD-3' ]Calling it with a value of type string | { status: "paid" } fails, because no single overload accepts the union:
error TS2769: No overload matches this call. The last overload gave the following error. Argument of type 'string | { status: "paid"; }' is not assignable to parameter of type '{ status: "paid" | "pending" | "shipped"; }'. Type 'string' is not assignable to type '{ status: "paid" | "pending" | "shipped"; }'.Pitfalls:
- Order overloads from most to least specific. A broad overload listed first swallows calls meant for later ones.
- The implementation signature is hidden. Callers cannot use it, even though it accepts the union; add an overload for the union if callers need one.
- Consider a conditional type or separate functions. Two clearly named functions (
findOrder,findOrdersByStatus) are often easier to read than two overloads.
Async functions
Section titled “Async functions”TypeScript supported async and await for ES2015 targets in 1.7 and for every target in 2.1. An async function always returns a Promise, so its declared return type is Promise<T>, where T is the type of the value it returns; writing : Order instead of : Promise<Order> fails with error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<Order>'? The Awaited<T> utility type (TypeScript 4.5) unwraps a promise type the way await does, including nested promises. For the runtime behavior of promises and await, see the JavaScript pages on async functions and Promise.allSettled.
Two typing rules matter at the boundaries. First, data you receive, such as await response.json(), is not checked by the compiler: treat it as unknown and validate it, rather than asserting a generic T. Second, under strict the variable in catch (error) is unknown (useUnknownInCatchVariables, TypeScript 4.4), because anything can be thrown; narrow it before reading .message.
interface Order { id: string; total: number;}
// Stand-in for fetch(`https://api.example.test/orders/${id}`).then((r) => r.json())async function fetchJson(path: string): Promise<unknown> { await new Promise((resolve) => setTimeout(resolve, 10)); if (path.endsWith("ORD-404")) throw new Error(`404 for ${path}`); return { id: path.split("/").pop(), total: 59.9 };}
function isOrder(value: unknown): value is Order { return typeof value === "object" && value !== null && "id" in value && "total" in value;}
async function loadOrder(id: string): Promise<Order> { const body = await fetchJson(`/orders/${id}`); if (!isOrder(body)) throw new TypeError(`Unexpected payload for ${id}`); return body;}
type Loaded = Awaited<ReturnType<typeof loadOrder>>; // Order
const results = await Promise.allSettled(["ORD-1", "ORD-404"].map(loadOrder));for (const result of results) { if (result.status === "fulfilled") { const order: Loaded = result.value; console.log(`loaded ${order.id}: ${order.total}`); } else { const reason: unknown = result.reason; console.log(`failed: ${reason instanceof Error ? reason.message : String(reason)}`); }}
try { await loadOrder("ORD-404");} catch (error) { // error is unknown under strict console.log(error instanceof Error ? error.name : "non-error thrown");}Output:
loaded ORD-1: 59.9failed: 404 for /orders/ORD-404ErrorTop-level await, used here, needs an ES module and module set to es2022 or later, nodenext or preserve.
Pitfalls:
fetchJson<T>()returningres.json() as Promise<T>hides an assertion. The caller choosesT, and nothing checks it. Returnunknownand validate.- Floating promises are not type errors. Calling
loadOrder(id)withoutawaitcompiles. Use a linter rule such as typescript-eslint’sno-floating-promisesto catch it. Promise<void>callbacks. Passing an async function where a() => voidcallback is expected compiles, but the caller will not wait for it or see its errors, as witharray.forEach(async ...).
Choosing between them
Section titled “Choosing between them”- When input and output types are linked, use a generic; when a type parameter would appear only once, use
unknownor a concrete type. - When the body needs members of the type parameter, add a constraint; when callers usually want one type, add a default.
- When the return type depends on the kind of argument, use overloads, or two well-named functions; when it does not, use a union parameter.
- For anything that awaits, declare
Promise<T>, returnunknownfrom I/O helpers, and narrowcatchvariables.
Interview questions
Section titled “Interview questions”What is the difference between function first(items: any[]): any and function first<T>(items: T[]): T | undefined?
The any version switches off checking for both the argument and the result, so first([1, 2]).toUpperCase() compiles and fails at run time. The generic version links the element type to the result type, so the compiler knows the result is number | undefined and rejects the call.
What does K extends keyof T give you, and what is T[K]?
It restricts K to the property names of T, so a misspelled key is a compile error. T[K] is an indexed access type: the type of property K on T, which lets a function like pluck return the right element type for each key.
When would you choose overloads over a union parameter? When the return type depends on which kind of argument is passed and a caller benefits from the precise type, such as a single result for an ID and an array for a filter. If every variant returns the same type, a union parameter is simpler and also accepts union-typed arguments, which overloads reject.
Why is the catch variable unknown in strict mode?
JavaScript can throw any value, not only Error objects, so the compiler cannot know its type. useUnknownInCatchVariables, part of strict, forces you to narrow, for example with error instanceof Error, before reading properties.
What does Awaited<T> do that T extends Promise<infer U> ? U : T does not?
Awaited recursively unwraps nested promises and promise-like then-ables, matching what await does at run time, so Awaited<Promise<Promise<number>>> is number.
Senior scenario: OrdersPortal has a generic api.get<T>(url) used in 300 places, and production errors show the backend changed a field name without any compile error. What would you change?
The generic lets each caller assert a response type that nothing verifies. Change get to return Promise<unknown>, or to take a validator or schema as a parameter and return the validated type (get(url, orderSchema)), and generate or share the schemas with the backend contract (for example from its OpenAPI description). Migrate the most critical endpoints first, keeping a deprecated get<T> wrapper that logs validation failures so drift becomes visible before it breaks users.
Related pages
Section titled “Related pages”- Functions and generics: the beginner tutorial for typed functions.
- Utility types:
Parameters,ReturnType,ConstructorParametersandAwaited. - Advanced types: conditional types and
infer, the next step after generics. - Classes and decorators: typing
thisin functions and methods. - Type narrowing: type guards for validating
unknowndata.
Official references
Section titled “Official references”- TypeScript Handbook: Generics
- TypeScript Handbook: More on Functions (overloads, generic functions,
this) - TypeScript 2.1 release notes: downlevel async functions, keyof and lookup types
- TypeScript 2.3 release notes: generic parameter defaults
- TypeScript 4.4 release notes: unknown in catch variables
- TypeScript 4.5 release notes: the Awaited type
- TypeScript 5.0 release notes: const type parameters