Script Valley
TypeScript: Complete Course from Zero
Functions and Type NarrowingLesson 3.1

How to type function parameters and return types in TypeScript

parameter type annotations, return type annotations, void return type, optional parameters, default parameters, rest parameters

Typing function parameters

Annotate each parameter and the return type:

function greet(name: string, greeting: string): string {
  return `${greeting}, ${name}!`;
}

void and optional parameters

Use void when a function returns nothing. Use ? for optional parameters — they become T | undefined inside the function:

function log(message: string, level?: string): void {
  const prefix = level ?? "INFO";
  console.log(`[${prefix}] ${message}`);
}

Default parameters

function createUser(name: string, role: string = "user") {
  return { name, role };
}
// role is inferred as string; no explicit annotation needed

Rest parameters

function sum(...numbers: number[]): number {
  return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10

Optional parameters must come after required ones. Rest parameters must be last. TypeScript infers the return type in most cases, but annotating it explicitly prevents accidental return of the wrong type — especially useful in larger functions.

Up next

Function overloads in TypeScript how and when to use them

Sign in to track progress