Lesson 2 of 11 · 8 min

Typed functions

In TypeScript, a function's parameters and its result can all have types:

function add(a: number, b: number): number {
  return a + b;
}

add(2, 3);      // 5
add(2, "3");    // error: string is not assignable to number

The type after the brackets, : number, is the return type. TypeScript checks that every return matches it, and that callers pass the right things.

Arrow functions work the same way:

const square = (n: number): number => n * n;

Optional and default parameters

A ? makes a parameter optional. Inside the function its type includes undefined, so check before using it:

function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}

A default value is used when the caller leaves the argument out, and also tells TypeScript the type:

function repeat(text: string, times: number = 2): string {
  return text.repeat(times);
}

A function that returns nothing has the return type void.

Your task

  1. Write formatPrice(amount: number, currency: string = "USD"): string returning e.g. "USD 12.50" (always two decimals: amount.toFixed(2)).
  2. Write fullName(first, last, middle?) with proper types, returning "Tariro Moyo" or, with a middle name, "Tariro Grace Moyo".
main.ts
function formatPrice(amount, currency) {
  return "";
}

function fullName(first, last, middle) {
  return "";
}

console.log(formatPrice(12.5));
console.log(fullName("Tariro", "Moyo", "Grace"));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…