Explain it simply
Explain it simply
Think of a function as a machine in a factory. Labels on the machine say what goes into each input slot (the parameters) and what comes out (the return value). In TypeScript those labels are type annotations: function add(a: number, b: number): number says "put in two numbers, get one number back".
Because the labels exist, feeding the machine the wrong thing, such as a string or a missing argument, is underlined in red before the code ever runs. And the person writing the function must always return the type that was promised.
Problem → Why → Solution
The problem: JavaScript does not notice wrong arguments
In plain JavaScript you can only guess what a function wants from its parameter names. Calling formatPrice() below with its arguments swapped crashes at runtime. getDiscount() is worse: for an unknown coupon it returns undefined, and the whole price calculation quietly becomes NaN without a single error message.
// Plain JavaScript: no types on parameters or return values
function formatPrice(amount, currency) {
return amount.toFixed(2) + " " + currency;
}
function getDiscount(code) {
if (code === "SAVE10") return 10;
// forgot the other codes: returns undefined
}
formatPrice("USD", 9.5); // TypeError: amount.toFixed is not a function
const finalPrice = 50 - getDiscount("WELCOME"); // NaNWhy do these bugs slip through?
JavaScript checks neither the number nor the type of arguments, and nothing promises what a function returns. In TypeScript, formatPrice(amount: number, currency: string) turns the swapped call into a compile error, and getDiscount(code: string): number makes the compiler flag the path that returns nothing.
Core concept: a signature is a contract
A function's signature is its name, its parameter list and its return type. It is a contract that binds both sides: the caller must pass the right types and the right number of arguments, and the body must return the promised type on every path. Whichever side breaks the contract gets the compile error.
Parameters always need types. In strict mode (noImplicitAny), function add(a, b) is an error, "Parameter 'a' implicitly has an 'any' type", because TypeScript does not guess parameter types from the body. Return types are different: the compiler can infer them from the return statements. For exported functions and important logic it is still worth writing the return type yourself, so a wrong return is reported inside the function instead of at ten call sites.
void means "this function gives back no useful value". Use it for functions that exist for a side effect, such as logging or writing a file. If you try to use the result of a void function as a real value, such as testing it in an if condition or assigning it to a number variable, the compiler reports an error.
The compiler also counts arguments. Passing too many or too few gives an error such as "Expected 2 arguments, but got 1". When an argument is genuinely not required, you make it optional (?) or give it a default value, as the deeper section below shows.
Arrow functions follow the same rules: const double = (n: number): number => n * 2;. Whether you use the function keyword or an arrow, the signature is what TypeScript cares about. Types exist only at compile time and are erased from the emitted JavaScript, so they do not add runtime checks on arguments.
- Caller passes arguments
- Each is checked against its param type
- Body returns the promised type
- Caller receives a typed result
Parameter types police the caller; the return type polices the function body.
General pattern
function name(param: Type, optional?: Type): ReturnType {
return value;
}
const arrowName = (param: Type): ReturnType => value;
type Callback = (param: Type) => ReturnType;Each parameter gets : Type, and the return type follows the parameter list. Arrow functions use the same shape. type Callback = (...) => ... names the shape of a function as a type.
Example: a returning function and a void function
This example has one function of each kind. add() returns a number, while logMessage() only prints, so its return type is void. Notice how the first function's result flows into the second.
// This function takes two numbers and returns a number
function add(a: number, b: number): number {
return a + b;
}
// This function doesn't return anything (void)
function logMessage(message: string): void {
console.log(message);
}
let sum: number = add(5, 10);
logMessage("The sum is " + sum);Code breakdown
- Line 2
function add(a: number, b: number): number {Both a and b must be numbers, and : number after the ) is the return type. A call like add("5", 10) is a compile error.
- Line 3
return a + b;Adding two numbers gives a number, so the promise is kept. Return a string here by mistake and the error appears on this very line.
- Line 7
function logMessage(message: string): void {void says no useful value comes back; the function's whole job is to call console.log().
- Line 11
let sum: number = add(5, 10);add() already returns number, so the : number annotation is optional: const sum = add(5, 10); infers the same type.
- Line 12
logMessage("The sum is " + sum);A string plus a number is a string, which matches message: string. The output is "The sum is 15".
The sum is 15Optional, default and rest parameters
A ? after a parameter name makes it optional, and inside the function its type becomes string | undefined. A default value also makes a parameter optional, but inside the body it can no longer be undefined, and its type is inferred from the default. A rest parameter (...prices: number[]) collects any number of arguments into an array. Optional and rest parameters must come after the required ones.
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
function repeat(text: string, times = 2): string {
return text.repeat(times);
}
function total(...prices: number[]): number {
return prices.reduce((sum, price) => sum + price, 0);
}
console.log(greet("Aye"));
console.log(greet("Aye", "Mingalaba"));
console.log(repeat("ha"));
console.log(total(1.5, 2, 3.5));Function types and callbacks
In JavaScript you can pass functions to other functions like any other value. To type such a callback, use a function type expression like (amount: number) => string. Once Formatter is named, the callbacks do not need to repeat their parameter types: TypeScript knows from context that amount is a number.
type Formatter = (amount: number) => string;
const asDollars: Formatter = (amount) => "$" + amount.toFixed(2);
const asKyat: Formatter = (amount) => `${Math.round(amount)} MMK`;
function printAll(amounts: number[], format: Formatter): void {
for (const amount of amounts) console.log(format(amount));
}
printAll([3.5, 10], asDollars);
printAll([2500.4], asKyat);In real projects
Where this shows up in real projects
In real projects, function signatures become documentation for the whole team. Reading calculateShipping(weightKg: number, zone: string): number tells you how to call it without opening the implementation, and the editor shows that signature on hover and drives autocomplete.
Callback types are everywhere: the functions you pass to array.map() and filter(), an Express route handler (req, res) => void, a React onClick handler, a setTimeout callback. Libraries declare these function types, so TypeScript fills in your callback's parameter types for you. When you refactor, adding a parameter or changing a return type makes the compiler list every call site that must change, which keeps large changes safe. Data that comes from outside the program, such as a form or an API, is still not checked by these types at runtime, so validate it at the boundary before it reaches your typed functions.
Common mistakes
Common mistakes
1. Forgetting a return on one path
function isAdult(age: number): boolean { if (age >= 18) return true; } fails with "Function lacks ending return statement and return type does not include 'undefined'". The return type is what catches it: without it, TypeScript infers boolean | undefined and pushes the problem onto callers. Write return age >= 18; instead.
2. Using an optional parameter without checking
With currency?: string, currency is string | undefined inside the function, so currency.toUpperCase() fails with "'currency' is possibly 'undefined'". Fall back with ?? "USD", or simply use a default value: currency = "USD".
3. Typing a callback as Function or any
onDone: Function can be called with any arguments and returns any. Use a precise function type such as (result: string) => void so both the caller and the callback are checked.
Best practices
Best practices
- Write return types on every exported function; trust inference for small local helpers.
- Replace a run of three or four boolean parameters with an options object, because positional flags are easy to mix up.
- Prefer a default value over an optional parameter plus an undefined check when the default is obvious.
Mini challenge
Mini challenge: price helpers
Write three fully typed price functions for an online shop and combine them.
- priceWithTax(price, taxRate): taxRate defaults to 0.05 and the result is rounded to 2 decimals
- formatPrice(amount, currency?): uses "USD" when currency is missing
- applyAll(price, ...steps): applies (value: number) => number functions in order
- Every parameter and return type is written out; no any
function priceWithTax(/* TODO: price, taxRate with a default */): number {
// TODO: add tax and round to 2 decimal places
}
function formatPrice(/* TODO: amount, optional currency */): string {
// TODO: "21.00 USD"
}
function applyAll(/* TODO: price, ...steps */): number {
// TODO: run every step on the running result
}
// TODO: print priceWithTax(20), a 10% EUR price, and 40 half-off then taxedExpected: 21.00 USD 22.00 EUR 21.00 USD
Show hint
Round to 2 decimals with Math.round(x * 100) / 100. The rest parameter is an array of functions, written ((value: number) => number)[] with parentheses.
Show solution
function priceWithTax(price: number, taxRate = 0.05): number {
return Math.round(price * (1 + taxRate) * 100) / 100;
}
function formatPrice(amount: number, currency?: string): string {
return `${amount.toFixed(2)} ${currency ?? "USD"}`;
}
function applyAll(price: number, ...steps: ((value: number) => number)[]): number {
let result = price;
for (const step of steps) result = step(result);
return result;
}
const halfOff = (value: number): number => value / 2;
console.log(formatPrice(priceWithTax(20)));
console.log(formatPrice(priceWithTax(20, 0.1), "EUR"));
console.log(formatPrice(applyAll(40, halfOff, (v) => priceWithTax(v))));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A signature is a contract: parameter types check the caller, the return type checks the body.
- Always type parameters; let return types be inferred if you like, but write them on exported functions.
- void means no useful return value, and ?, defaults and ... make parameters flexible.
- Type callbacks as (param: Type) => Result, never as Function or any.
TypeScript Handbook — TypeScript