Lesson 3 of 15

Function Types

Function Types

TypeScript lets you annotate function parameters and return types:

function add(a: number, b: number): number {
    return a + b;
}
  • a: number — parameter a must be a number
  • b: number — parameter b must be a number
  • : number after the parentheses — the function returns a number

TypeScript verifies the return statement matches the declared return type:

function greet(name: string): string {
    return 42;  // Error: 'number' is not assignable to type 'string'
}

void

Functions that do not return a value have return type void:

function log(message: string): void {
    console.log(message);
}

Function Types as Values

Arrow functions can also be typed:

const multiply = (a: number, b: number): number => a * b;

Optional Parameters

Mark a parameter with ? to make it optional. Optional parameters must come after required ones:

function greet(name: string, greeting?: string): string {
    return (greeting || "Hello") + ", " + name;
}
greet("Alice");            // "Hello, Alice"
greet("Alice", "Howdy");   // "Howdy, Alice"

Inside the function, an optional parameter has type T | undefined.

Rest Parameters

Use ...args: T[] to accept any number of arguments of the same type:

function sum(...nums: number[]): number {
    return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3);    // 6
sum(10, 20);     // 30

Rest parameters must be the last parameter and collect all remaining arguments into an array.

Your Task

  1. Write function clamp(n: number, min: number, max: number): number that returns n if it is between min and max, min if it is below, and max if it is above.
  2. Write function joinWords(separator: string, ...words: string[]): string that joins all words using the separator.
TypeScript loading...
Loading...
Click "Run" to execute your code.