Tutorials / TypeScript: Beginner to Advanced / Typing functions: parameters, returns, optionals and overloads

Typing functions: parameters, returns, optionals and overloads

15 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. 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 undefined on another gets the type string | undefined.
  • Putting an optional parameter before a required one. The compiler rejects it.
  • **Using Function as 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

  1. Write clamp(value: number, min: number, max: number): number. Call it with too few arguments to see the error.
  2. Write formatName with an optional middle parameter.
  3. Define a type Predicate = (n: number) => boolean and write countMatching(numbers: number[], test: Predicate): number.
  4. Write an overload parse(value: string): number and parse(value: string[]): number[].
typescript
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