Sikau

TypeScript · Day 5 · about 25 min

Typing functions

Parameters, return types, optional and callbacks.

A function's promise

A typed function is a contract: "give me these, I'll give you that." TypeScript checks both sides — every caller and the function's own return statements.

Parameters, returns and options

function bill(amount: number, tip = 10, note?: string): string {
  const total = amount + (amount * tip) / 100;
  return note ? `${total} (${note})` : String(total);
}
bill(1000);
bill(1000, 15, "birthday");
bill();

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

The rest of this lesson

  • Function types for callbacksexplain
  • Return types as a safety netexplain
  • Optional, default and rest parametersexplain
  • Is this call OK?predict
  • Type the functionfill
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript