TypeScript Functions
TypeScript Functions: Parameters, Defaults, and Callbacks
TypeScript lets you type function parameters, return values, optional flags, default values, and callback signatures. Typing function boundaries catches wrong argument orders and missing fields instantly across your codebase.
Every parameter without a default value is required in TypeScript—unlike JavaScript, calling a 2-argument function with only 1 argument triggers a compile error immediately.
Optional, Default, and Rest Parameters
Put optional parameters (?) and parameters with default values after required parameters. Notice you do not need ? when providing a default value like taxRate = 0.08.
type PriceFormatter = (amount: number) => string;
function calculateInvoice(
subtotal: number,
taxRate: number = 0.08,
couponCode?: string,
...fees: number[]
): number {
const extra = fees.reduce((sum, f) => sum + f, 0);
const discount = couponCode === "SAVE10" ? 10 : 0;
return Number(((subtotal - discount) * (1 + taxRate) + extra).toFixed(2));
}
const formatUsd: PriceFormatter = (val) => `$${val.toFixed(2)}`;
console.log(formatUsd(calculateInvoice(100, 0.1, "SAVE10", 5)));
Typing this and Function Overloads
When one function handles distinct input-to-output pairs (for example, string -> string vs number -> number), declare overload signatures above a single shared implementation signature.
Common Mistakes to Avoid
- Writing
couponCode?: string = "NONE": TypeScript forbids combining?and= defaulton the same parameter; usecouponCode: string = "NONE"instead. - Returning
voidvs ignoring callbacks: A callback typed() => voidstill accepts a function that returns a value (likearr.push), meaning the caller promises to ignore any return value. - Writing overly complex function overloads: When a union return or generic works cleanly, prefer it over 5 stacked overload signatures.
Frequently Asked Questions
Should I always write the return type on TypeScript functions?
Yes for exported functions and API helpers, because explicit return types document intent and speed up TypeScript IDE type checking.
How do I type an async function's return value?
Async functions always return a Promise, so write async function loadUser(id: number): Promise<User>.
What does (a: number, b: number) => number represent?
It is a function type alias describing any function that takes two number arguments and returns a number.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.