Functions with Types
Annotate a function's parameters and return value so TypeScript can check every call.
What is it?
A function is a contract: "give me these inputs and I'll give you this output." In plain JavaScript that contract lives only in comments or your head. Nothing stops a caller passing the wrong kind of argument, or too few.
TypeScript writes the contract into the signature. Each parameter gets a type, and so does the return value, so both inputs and output are checked. Mark a parameter optional with ? and callers may leave it out; if they do, its value inside the function is undefined.
Explain like I'm 10
A typed function signature is like a vending machine's coin slot: shaped for one coin size and labeled with what it dispenses. The wrong object simply won't go in, so you find out right away, not after the machine jams.
Examples
Typed parameters and return value
function calculateTotal(price: number, taxRate: number): number {
return price + price * taxRate;
}
calculateTotal(100, 0.07); // 107
calculateTotal("100", 0.07);
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.TypeScript checks the types passed in and the type returned. If the body tried to return "total" instead of a number, that would be an error too.
Optional parameters and default values
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
greet("Mina"); // "Hello, Mina!"
greet("Mina", "Welcome"); // "Welcome, Mina!"
// A default value makes a parameter optional automatically:
function greetWithDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}The ? after greeting lets callers omit it, in which case it's undefined inside the function. A default value also makes a parameter omittable, and supplies a fallback automatically.
How it works
For each call, the compiler matches each argument to its parameter, in order, and flags any type mismatch, including too many or too few arguments. It also checks every return statement against the declared return type.
Optional parameters (?) must come after all required ones, because arguments are matched to parameters by position.
Why does it exist?
Function calls are a common source of bugs: arguments in the wrong order, a missing argument, or assuming a function returns something it doesn't. With an explicit, checkable contract, TypeScript catches these at the call site right away instead of when the function runs with bad data.
When to use it
Type the parameters of almost every function, especially ones used in several places or by other parts of the codebase. Return types are optional (TypeScript can usually infer them), but writing them documents intent and catches a body that accidentally returns the wrong type.
When not to use it
For a small inline callback like array.map(x => x * 2), TypeScript usually infers the parameter type from context, so an annotation is just noise.
Common mistakes
Putting an optional parameter before a required one. TypeScript doesn't allow it; optional parameters come last.
Confusing an optional parameter (
name?: string) with a default value (name: string = "Guest"). The first can beundefinedinside the function; the second never is.Thinking a return type annotation changes what the function returns at runtime. It's only a compile-time check; the function's logic decides the value.
Practice exercises
- Easy:
Write a function
square(n: number): numberthat returnsnsquared. Call it correctly and incorrectly to see the error. - Medium:
Write a function
formatName(first: string, last: string, middle?: string): stringthat combines the names and handles a missingmiddle. - Hard:
Write a function
createUser(name: string, role: string = "member")that returns an object matching aUserinterface you define. Explain whyroledoesn't need a?even though callers can omit it.
Interview questions
What happens if you call a TypeScript function with the wrong number of arguments?
The compiler reports an error at the call site. Too few required arguments and too many are both caught before the code runs.
What's the difference between an optional parameter and one with a default value?
An optional parameter (x?: T) can be omitted and is then undefined inside the function. A parameter with a default (x: T = val) can also be omitted, but then takes the default value instead.
Is a function's return type annotation required?
No. TypeScript can usually infer it from the body. Writing it is optional, but adds clarity and an extra safety check.
Why must optional parameters come after all required ones in a function signature?
Arguments are matched by position, not name. If an optional parameter came first, there'd be no way to tell whether a single argument was meant for the optional slot or the required one after it.
Given `function greet(name: string, greeting?: string) { return greeting ?? "Hi"; }`, what is the declared type of `greeting` inside the function body?
string | undefined. Marking a parameter ? also adds undefined to its type inside the function, which is why greeting ?? "Hi" is needed.
Is `function f(a?: number, b: number) {}` valid TypeScript?
No, it's a compile error. Optional a comes before required b, and optional parameters must come after all required ones.
Can a parameter have both a `?` and a default value, like `function f(x?: number = 5) {}`?
No, it's a compile error. A default already makes the parameter optional, so TypeScript doesn't allow adding ? as well.
How do you type a function that accepts any number of arguments, like `sum(1, 2, 3, 4)`?
With a rest parameter: function sum(...nums: number[]): number. Arguments after any fixed parameters are collected into the nums array, and each is checked against the element type.
How would you type a variable meant to hold a function, rather than a function declaration itself — for example, a variable that should only ever be assigned an operation on two numbers?
With a function type: let op: (a: number, b: number) => number;. Any function assigned to op is checked against those parameters and return type.
Why does TypeScript usually let you skip annotating the parameter type inside a callback like `array.map(x => x * 2)`?
Contextual typing: TypeScript knows the array's element type, so it infers x from context. An annotation would just repeat what it already knows.
If `calculateTotal(price: number, taxRate: number): number` is called as `calculateTotal(100)`, what happens?
A compile error. Every parameter without ? or a default must be supplied, and taxRate is required.
Given `function createUser(name: string, role: string = "member") {}`, does a caller have to know or write anything different from calling a required-parameter function?
No. For callers, role works like an optional parameter, so createUser("Kai") is valid. Inside the function role is plain string, never undefined, because the default always provides a value.
What does annotating a function's return type as `: void` communicate, versus `: undefined`?
void means the return value isn't meant to be used; it's the usual annotation for functions run for side effects. undefined is a narrower claim that the function returns exactly undefined, which is rarely what you mean.
If a function's body has a `return "done";` statement but its signature declares `: number`, what happens?
A compile error on that return, because the value doesn't match the declared return type. The body is checked against its own signature, just as calls are checked against parameter types.
Does an explicit return type annotation change what value a function actually returns at runtime?
No. It only checks at compile time that the return statements match. The function's logic decides the real value; the annotation can't change or coerce it.
You pass an object literal directly into a function parameter typed with an interface, and it has one extra property the interface doesn't list. Does this behave differently than passing a variable holding the same object?
Yes. A fresh object literal at the call site triggers the excess property check and errors on the extra property. A variable holding the same object doesn't, because the stricter check only applies where the literal is written.
Why is a typed function signature sometimes compared to a vending machine's coin slot?
The slot (parameter types) only accepts specific inputs, and what comes out (the return type) is known in advance. The wrong input is rejected immediately instead of causing a jam (a runtime error) later.
Between annotating every function parameter and every function's return type, which matters more for catching call-site mistakes, and why?
Parameters. Most call-site mistakes, like a wrong type or wrong argument count, are caught when arguments are checked against parameter types. Return types can usually be inferred, though writing them still documents intent and catches an accidental wrong-type return.