Skip to content

TypeScript functions: parameters, returns, generics

Functions are where TypeScript’s checking is most useful: every call is checked against the function’s parameter types, and every caller knows what comes back. This second basics tutorial covers typing parameters and callbacks, optional and default parameters, return types (including void and Promise), and generic functions, which work for many types without giving up type safety. It assumes you have done Types and inference.

A small pricing module for the invented OrdersPortal shop: a function that prices a cart with an optional coupon and a configurable rounding rule, a callback-based discount rule, an async function that loads a customer, and two generic helpers, firstMatch and groupCount, that work for orders, customers or anything else.

The same folder as the first tutorial: Node.js 22.18 or later, a package.json with "type": "module", and TypeScript installed (npm install -D typescript; the samples were compiled with TypeScript 7.0.2). Save each sample as pricing.ts, compile it with npx tsc --module nodenext pricing.ts, and run node pricing.js. Compiler errors are quoted as tsc prints them, without the file and position prefix.

Annotate each parameter with a type; the compiler then checks the number and types of the arguments at every call. Arrow functions are annotated the same way. Under strict mode, which is the default, a parameter without an annotation is an error unless TypeScript can infer it from context.

That context is usually a callback: when you pass an arrow function to map, filter or your own function, its parameters take their types from the expected function type, so prices.map((p) => p * 2) needs no annotation. You describe a function type with arrow syntax: (price: number) => number. Give it a name with a type alias when you use it more than once, as with DiscountRule below.

For the JavaScript side of functions, such as arrow functions and this, see the JavaScript functions basics.

type DiscountRule = (subtotal: number) => number;
function applyRule(subtotal: number, rule: DiscountRule): number {
return Math.max(0, subtotal - rule(subtotal));
}
const tenPercent: DiscountRule = (subtotal) => subtotal * 0.1;
const fiveOff = (subtotal: number): number => (subtotal >= 50 ? 5 : 0);
const subtotals = [30, 80];
console.log(subtotals.map((s) => applyRule(s, tenPercent)));
console.log(subtotals.map((s) => applyRule(s, fiveOff)));

Output:

[ 27, 72 ]
[ 30, 75 ]

Calling applyRule("80", tenPercent) fails with error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'., and calling applyRule(80) fails with error TS2554: Expected 2 arguments, but got 1.

Pitfalls:

  • Extra callback parameters are fine, missing arguments are not. A callback may ignore parameters (() => 0 is a valid DiscountRule), but a call must pass every required argument.
  • Prefer a type alias over Function. The Function type accepts any function and checks no arguments.

A parameter followed by ? is optional: callers may leave it out, and inside the function its type includes undefined, so the compiler makes you handle that case. A parameter with a default value, rounding = "cent", is also optional, but inside the function it always has a value; TypeScript infers its type from the default.

Optional and default parameters must come after required ones when you want callers to omit them positionally. When a function has several optional settings, an options object with optional properties reads better at the call site than a row of positional arguments: priceCart(lines, { coupon: "WELCOME10" }) instead of priceCart(lines, undefined, "WELCOME10"). Default values in JavaScript are covered on the default parameters page.

interface Line {
sku: string;
quantity: number;
unitPrice: number;
}
interface PriceOptions {
coupon?: string;
rounding?: "cent" | "none";
}
function priceCart(lines: Line[], { coupon, rounding = "cent" }: PriceOptions = {}): number {
let total = lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
if (coupon !== undefined && coupon.toUpperCase() === "WELCOME10") {
total *= 0.9;
}
return rounding === "cent" ? Math.round(total * 100) / 100 : total;
}
function describeCustomer(customerName: string, email?: string): string {
return email ? `${customerName} <${email}>` : `${customerName} (no email)`;
}
const lines: Line[] = [
{ sku: "SKU-RED-01", quantity: 3, unitPrice: 19.95 },
{ sku: "SKU-BLU-02", quantity: 1, unitPrice: 4.99 },
];
console.log(priceCart(lines));
console.log(priceCart(lines, { coupon: "welcome10" }));
console.log(priceCart(lines, { coupon: "welcome10", rounding: "none" }));
console.log(describeCustomer("Ada Lopez"), "|", describeCustomer("Ben Ortiz", "ben@example.test"));

Output (the third line shows why money needs rounding: binary floating point cannot store most decimal fractions exactly):

64.84
58.36
58.355999999999995
Ada Lopez (no email) | Ben Ortiz <ben@example.test>

Writing function describeCustomer(email?: string, customerName: string) fails with error TS1016: A required parameter cannot follow an optional parameter.

Pitfalls:

  • ? is not the same as | undefined. email?: string can be omitted; email: string | undefined must be passed, even if the value is undefined.
  • Check before use. Inside the function, email.toLowerCase() fails with error TS18048: 'email' is possibly 'undefined'. until you check it.

The return type follows the parameter list: function priceCart(...): number. TypeScript infers it when you leave it out, but writing it on exported functions documents the contract and turns an accidental change in the body into an error at the function, not at some distant caller.

Three return types need explanation. void means the function returns no useful value; callers should not use the result. An async function always returns a promise, so its return type is Promise<T>, where T is the type of the value it returns; Promise<Customer>, never just Customer. And never means the function never returns normally, because it always throws. For how async and await behave at run time, see the JavaScript page on async functions.

interface Customer {
id: string;
displayName: string;
}
const customers: Customer[] = [{ id: "C-1", displayName: "Ada Lopez" }];
function logPrice(label: string, amount: number): void {
console.log(`${label}: ${amount.toFixed(2)} EUR`);
}
function findCustomer(id: string): Customer | undefined {
return customers.find((c) => c.id === id);
}
async function loadCustomer(id: string): Promise<Customer> {
await new Promise((resolve) => setTimeout(resolve, 10)); // stands in for a network call
const customer = findCustomer(id);
if (customer === undefined) {
throw new Error(`Customer ${id} not found`);
}
return customer;
}
logPrice("Subtotal", 64.84);
const ada = await loadCustomer("C-1");
console.log(ada.displayName);
await loadCustomer("C-9").catch((error: unknown) => {
console.log(error instanceof Error ? error.message : error);
});

Output:

Subtotal: 64.84 EUR
Ada Lopez
Customer C-9 not found

Declaring async function loadCustomer(id: string): Customer 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<Customer>'?

Pitfalls:

  • Customer | undefined is honest. A lookup that can fail should say so in its return type; the caller then has to handle the missing case.
  • Forgetting await. const c = loadCustomer("C-1"); c.displayName fails with error TS2339: Property 'displayName' does not exist on type 'Promise<Customer>'., which is the compiler reminding you to await.

A generic function has a type parameter, written in angle brackets: function firstMatch<T>(items: T[], ...). Each call fills T in, usually by inference from the arguments, so the same function returns an Order when given orders and a Customer when given customers. The type parameter connects the input type to the output type.

Without generics you would either write one function per type or use any, which loses the connection: a function returning any lets callers do anything with the result, including mistakes. A generic keeps checking on. You can also limit what T may be with a constraint, T extends { id: string }, which lets the function use id on every item. Constraints, defaults and generic classes are covered in Generics and functions.

interface Order {
id: string;
customerId: string;
total: number;
}
function firstMatch<T>(items: T[], predicate: (item: T) => boolean): T | undefined {
for (const item of items) {
if (predicate(item)) return item;
}
return undefined;
}
function groupCount<T>(items: T[], keyOf: (item: T) => string): Map<string, number> {
const counts = new Map<string, number>();
for (const item of items) {
const key = keyOf(item);
counts.set(key, (counts.get(key) ?? 0) + 1);
}
return counts;
}
function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
return firstMatch(items, (item) => item.id === id);
}
const orders: Order[] = [
{ id: "ORD-1", customerId: "C-1", total: 40 },
{ id: "ORD-2", customerId: "C-2", total: 15 },
{ id: "ORD-3", customerId: "C-1", total: 25 },
];
const big = firstMatch(orders, (o) => o.total > 30); // Order | undefined
const firstWord = firstMatch(["gift", "fragile"], (w) => w.startsWith("f")); // string | undefined
console.log(big?.id, firstWord, byId(orders, "ORD-3")?.total);
console.log(groupCount(orders, (o) => o.customerId));

Output:

ORD-1 fragile 25
Map(2) { 'C-1' => 2, 'C-2' => 1 }

Using the result wrongly is caught: firstMatch(orders, (o) => o.total > 30)?.toUpperCase() fails with error TS2339: Property 'toUpperCase' does not exist on type 'Order'. With an any-returning version, the same mistake would compile.

Pitfalls:

  • You rarely need explicit type arguments. Write firstMatch<Order>(...) only when inference cannot work, such as with an empty array literal.
  • A type parameter used once is pointless. function log<T>(value: T): void connects nothing; value: unknown says the same thing more simply.

The pricing module put together:

interface Line {
sku: string;
quantity: number;
unitPrice: number;
}
interface Order {
id: string;
customerId: string;
lines: Line[];
}
type DiscountRule = (subtotal: number) => number;
const rules: Record<string, DiscountRule> = {
WELCOME10: (subtotal) => subtotal * 0.1,
FIVEOFF: (subtotal) => (subtotal >= 50 ? 5 : 0),
};
function subtotal(lines: Line[]): number {
return lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
}
function priceOrder(order: Order, coupon?: string, roundTo = 0.01): number {
const before = subtotal(order.lines);
const rule = coupon === undefined ? undefined : rules[coupon.toUpperCase()];
const after = rule ? Math.max(0, before - rule(before)) : before;
return Math.round(after / roundTo) * roundTo;
}
function firstMatch<T>(items: T[], predicate: (item: T) => boolean): T | undefined {
for (const item of items) if (predicate(item)) return item;
return undefined;
}
function groupCount<T>(items: T[], keyOf: (item: T) => string): Map<string, number> {
const counts = new Map<string, number>();
for (const item of items) counts.set(keyOf(item), (counts.get(keyOf(item)) ?? 0) + 1);
return counts;
}
async function loadOrders(): Promise<Order[]> {
await new Promise((resolve) => setTimeout(resolve, 10));
return [
{ id: "ORD-1", customerId: "C-1", lines: [{ sku: "SKU-RED-01", quantity: 3, unitPrice: 19.95 }] },
{ id: "ORD-2", customerId: "C-2", lines: [{ sku: "SKU-BLU-02", quantity: 2, unitPrice: 4.99 }] },
{ id: "ORD-3", customerId: "C-1", lines: [{ sku: "SKU-BLU-02", quantity: 12, unitPrice: 4.99 }] },
];
}
function report(label: string, value: string): void {
console.log(`${label.padEnd(18)} ${value}`);
}
const orders = await loadOrders();
report("ORD-1 no coupon", priceOrder(orders[0]).toFixed(2));
report("ORD-1 WELCOME10", priceOrder(orders[0], "welcome10").toFixed(2));
report("ORD-3 FIVEOFF", priceOrder(orders[2], "FIVEOFF", 0.05).toFixed(2));
report("First over 50", firstMatch(orders, (o) => subtotal(o.lines) > 50)?.id ?? "none");
report("Orders per customer", JSON.stringify(Object.fromEntries(groupCount(orders, (o) => o.customerId))));

Output:

ORD-1 no coupon 59.85
ORD-1 WELCOME10 53.86
ORD-3 FIVEOFF 54.90
First over 50 ORD-1
Orders per customer {"C-1":2,"C-2":1}
Error What it means Fix
TS2554: Expected 2 arguments, but got 1. A required parameter was not passed. Pass it, or make the parameter optional or give it a default.
TS1016: A required parameter cannot follow an optional parameter. Parameter order is wrong. Move optional and default parameters to the end, or use an options object.
TS18048: 'email' is possibly 'undefined'. An optional value is used without a check. Check it (if (email)), or supply a default with ??.
TS1064: The return type of an async function ... must be the global Promise<T> type. An async function is annotated with a plain type. Write Promise<T>.
TS2339: Property 'x' does not exist on type 'Promise<...>'. A promise is used as if it were the value. Add await.
  1. What is the type of email inside function f(email?: string)?
  2. Why does a callback passed to map usually need no parameter annotations?
  3. What should the return type of an async function that returns a Customer be?
  4. What does the type parameter in firstMatch<T> give you that any does not?

Answers: (1) string | undefined. (2) TypeScript infers the parameter types from the function type that map expects (contextual typing). (3) Promise<Customer>. (4) It links the element type of the input array to the result type, so the compiler still checks how the result is used.

Continue with Objects, interfaces and classes, which names object shapes and models OrdersPortal’s data with interfaces and classes.