Lesson 4 of 13 · 0 of 1 exercises solved

Typed Functions

Learn how to type and return values. This is where types help most day to day, because the checks every call before you run anything.

// Function declarations — parameter and return types
function add(a: number, b: number): number {
  return a + b
}

// Arrow functions
const multiply = (a: number, b: number): number => a * b

// Optional parameters — must come after required ones
function greet(name: string, greeting?: string): string {
  return `${greeting ?? "Hello"}, ${name}!`
}

// Default parameters
function createUser(name: string, role: string = "user", active: boolean = true) {
  return { name, role, active }
}

// Rest parameters
function sum(...nums: number[]): number {
  return nums.reduce((acc, n) => acc + n, 0)
}

console.log(sum(1, 2, 3, 4, 5))  // 15

// Function overloads — multiple signatures for one implementation
function format(value: string): string
function format(value: number): string
function format(value: string | number): string {
  if (typeof value === "number") return value.toFixed(2)
  return value.trim()
}

console.log(format(3.14159))  // "3.14"
console.log(format("  hello  "))  // "hello"
TypeScript (compiler loads on first run)Ctrl+Enter runs
// Higher-order functions with types
function map<T, U>(arr: T[], fn: (item: T) => U): U[] {
  return arr.map(fn)
}

const doubled = map([1, 2, 3], n => n * 2)           // number[]
const strings = map([1, 2, 3], n => n.toString())     // string[]

// Callback types
type Predicate<T> = (item: T) => boolean
type Transformer<T, U> = (item: T) => U

function filter<T>(arr: T[], pred: Predicate<T>): T[] {
  return arr.filter(pred)
}

// Type narrowing — TypeScript learns the type from checks
function processValue(val: string | number | null): string {
  if (val === null) return "null"
  if (typeof val === "number") return val.toFixed(2)
  return val.toUpperCase()  // TypeScript knows val is string here
}

// User-defined type guards
interface Cat { meow(): void }
interface Dog { bark(): void }

function isCat(animal: Cat | Dog): animal is Cat {
  return "meow" in animal
}

function makeSound(animal: Cat | Dog): void {
  if (isCat(animal)) {
    animal.meow()   // TypeScript knows it's a Cat
  } else {
    animal.bark()   // TypeScript knows it's a Dog
  }
}
TypeScript (compiler loads on first run)Ctrl+Enter runs

Practice

Write applyDiscount(price: number, percent = 10): number, and a function type alias Formatter = (n: number) => . Then implement money: Formatter that renders 12.5 as "£12.50".

Exercise

Typed functions and function types

4 checks
function applyDiscount(price, percent) {
  return price
}

// type Formatter = ...

const money = n => String(n)

console.log(money(applyDiscount(50)))
console.log(money(applyDiscount(50, 25)))
 
TypeScript (compiler loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.
Finished reading?1 exercise still open. You can come back to it later.

Tip: use the ← and → keys to move between lessons.