Typing functions: parameters, returns, optionals and overloads
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Parameters and return types
A function in TypeScript needs types on its parameters. The return type is usually worked out from the body, but writing it explicitly is good practice for exported functions, because it makes the contract visible and catches accidental changes.
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
// add(2); // Error: Expected 2 arguments, but got 1.
// add(2, "3"); // Error: string is not assignable to number
Unlike JavaScript, TypeScript checks the number of arguments as well. Too few or too many is an error.
Optional and default parameters
Put a ? after a name to make it optional. Its type becomes T | undefined.
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}`;
}
return `Hello, ${name}`;
}
function power(base: number, exponent: number = 2): number {
return base ** exponent;
}
console.log(greet("Ali")); // Hello, Ali
console.log(greet("Ali", "Dr.")); // Hello, Dr. Ali
console.log(power(5)); // 25
console.log(power(2, 10)); // 1024
Optional parameters must come after required ones. A parameter with a default value is automatically optional, and its type is inferred from the default, so you can often skip the annotation.
Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
The rest parameter is typed as an array.
Function types
You can describe the shape of a function, which is how you type callbacks:
type Operation = (a: number, b: number) => number;
const subtract: Operation = (a, b) => a - b;
function applyOperation(a: number, b: number, op: Operation): number {
return op(a, b);
}
console.log(applyOperation(10, 4, subtract)); // 6
console.log(applyOperation(10, 4, (x, y) => x * y)); // 40
Notice (a, b) => a - b has no annotations. TypeScript knows the types from Operation. This is called contextual typing, and it makes callbacks pleasant to write. Array methods use it too: in [1, 2, 3].map(n => n * 2), n is known to be a number.
Returning nothing, or never returning
A function that does not return a value has the return type void. One that always throws has the return type never.
function logAll(items: string[]): void {
for (const item of items) console.log(item);
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
logAll(["a", "b"]);
We will use assertNever in a later lesson for exhaustive checks.
Object parameters
When a function takes more than two or three parameters, pass an object. The type documents each field:
interface EmailOptions {
to: string;
subject: string;
body?: string;
cc?: string[];
}
function sendEmail({ to, subject, body = "", cc = [] }: EmailOptions): string {
return `To ${to} (cc ${cc.length}): ${subject} ${body}`.trim();
}
console.log(sendEmail({ to: "a@example.com", subject: "Hi" }));
Callers see the field names at the call site, and the compiler flags a missing to.
Overloads
Sometimes a function accepts different input and gives a different output type. An overload gives each combination its own signature. You write the signatures first, then one implementation that handles all of them.
function toDate(value: number): Date;
function toDate(year: number, month: number, day: number): Date;
function toDate(valueOrYear: number, month?: number, day?: number): Date {
if (month !== undefined && day !== undefined) {
return new Date(valueOrYear, month - 1, day);
}
return new Date(valueOrYear);
}
console.log(toDate(0).getFullYear()); // 1970
console.log(toDate(2025, 3, 15).getMonth()); // 2 (March, zero based)
// toDate(2025, 3); // Error: no overload takes 2 arguments
Callers only see the two overload signatures. The implementation signature is hidden. Overloads are useful, but I use them rarely. A union type or two separate functions is often simpler.
Declaring this
A function can declare the type of this as a fake first parameter. It is erased at compile time:
interface Counter {
count: number;
}
function increment(this: Counter): void {
this.count++;
}
const counter: Counter & { increment: typeof increment } = { count: 0, increment };
counter.increment();
console.log(counter.count); // 1
You will not need this every day, but it explains some library signatures you will run into.
Common mistakes
- Forgetting the return type annotation and returning mixed types by accident. A function that returns a string on one path and
undefinedon another gets the typestring | undefined. - Putting an optional parameter before a required one. The compiler rejects it.
- **Using
Functionas a type.** It accepts any function and checks nothing. Write the full signature. - Annotating callback parameters that are already inferred. Let contextual typing work.
- Too many overloads. If you have more than three, a different design is likely better.
Try it yourself
- Write
clamp(value: number, min: number, max: number): number. Call it with too few arguments to see the error. - Write
formatNamewith an optionalmiddleparameter. - Define a type
Predicate = (n: number) => booleanand writecountMatching(numbers: number[], test: Predicate): number. - Write an overload
parse(value: string): numberandparse(value: string[]): number[].
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
// add(2); // Error: Expected 2 arguments, but got 1.
// add(2, "3"); // Error: string is not assignable to number
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account