TypeScript Tutorial · TypeScript Basics · Lesson 10 of 25

TypeScript Functions

Type parameters, return values, optional and default parameters, and function types.

Parameter and return types

Example 1Try it yourself
function add(a: number, b: number): number {
  return a + b;
}
const multiply = (a: number, b: number): number => a * b;
console.log(add(2, 3), multiply(4, 5));

Output

5 20

Optional, default and rest parameters

Example 2Try it yourself
function greet(name: string, greeting = "Hello", punctuation?: string): string {
  return `${greeting}, ${name}${punctuation ?? "!"}`;
}
function total(...prices: number[]): number {
  return prices.reduce((sum, p) => sum + p, 0);
}
console.log(greet("Ada"), greet("Lin", "Hi", "?"));
console.log(total(1, 2, 3.5));

Output

Hello, Ada! Hi, Lin?
6.5

Function types

Describe a function's signature as a type — useful for callbacks:

Example 3Try it yourself
type Comparator<T> = (a: T, b: T) => number;
type Logger = (message: string) => void;

const byLength: Comparator<string> = (a, b) => a.length - b.length;
const log: Logger = (m) => console.log(`[log] ${m}`);

log(["banana", "fig", "apple"].sort(byLength).join(" "));

function fail(message: string): never {
  throw new Error(message);
}
try {
  fail("boom");
} catch (e) {
  log(e instanceof Error ? e.message : String(e));
}

Output

[log] fig apple banana
[log] boom

void and never

  • void — the function returns nothing useful.
  • never — the function never returns (it always throws or loops forever).

Test yourself

Which return type means a function never finishes normally?

  1. void
  2. undefined
  3. never
  4. null
Show answer

Answer: never