TypeScriptLesson 4 of 16

Functions: parameters and return types

With a function you type its parameters and its result. TypeScript then checks every call: no missing arguments, no wrong types.

Key points

  • The return type goes after the parentheses: function total(): number.
  • An optional parameter gets a ? and comes after the required ones.
  • A default value makes a parameter optional and sets its type.
  • void means the function returns nothing.
  • Arrow functions are typed the same way: (n: number): number => n * 2.

Example

function formatPrice(amount: number, currency: string = "USD"): string {  return `${amount.toFixed(2)} ${currency}`;} function greet(name: string, title?: string): string {  return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;} const double = (n: number): number => n * 2; function log(message: string): void {  console.log(message);} log(formatPrice(5));log(formatPrice(7.5, "EUR"));log(greet("Lee"));log(greet("Lee", "Dr."));log(`${double(21)}`);// formatPrice("5"); // error: string is not assignable to number

formatPrice(5) falls back to the default currency, and greet works with or without a title. formatPrice("5") fails the check because a number is expected.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Give people in splitBill the default value 2, make tipPercent optional and uncomment the calls. Output: "Each pays 25.00", "Each pays 30.00", "Each pays 27.50".

Output

What your program prints appears here.