Kodokon kodokon.com

Typing functions: parameters, return, optionals

Make your functions safer by typing their parameters, their return value and their optional parameters.

9 min · 3 questions

Open this lesson in Kodokon

A function is a reusable mini-program: it receives parameters (its inputs) and can return a value (its output). Typing a function means specifying the type of each parameter, then the type of the returned value, written after the closing parenthesis.

TYPESCRIPT
function greet(name: string): string {
  return "Hello " + name + "!";
}

const message = greet("Karim");
console.log(message); // "Hello Karim!"
Input: a string. Output: a string.

Some functions return nothing: they simply perform an action, such as displaying a message. Their return type is then void, a word that means "empty". TypeScript will warn you if you try to use their result as a value.

TYPESCRIPT
function logWelcome(name: string): void {
  console.log("Welcome, " + name + "!");
}

logWelcome("Fatou"); // prints, but returns nothing
void indicates the absence of a return value.

Just like interface properties, a parameter can be made optional with a ?. The caller can then provide it or not. Inside the function, remember to handle the case where it is missing.

TYPESCRIPT
function makeCoffee(size: string, sugar?: boolean) {
  if (sugar) {
    return "A " + size + " coffee with sugar.";
  }
  return "A " + size + " coffee without sugar.";
}

makeCoffee("large", true); // with sugar
makeCoffee("small");       // sugar is missing
sugar? can be provided... or not.
TYPESCRIPT
function repeat(word: string, times: number = 2) {
  return word.repeat(times);
}

console.log(repeat("ha"));    // "haha"
console.log(repeat("ha", 3)); // "hahaha"
Variant: a default value with the = sign.

Knowledge check

Make sure you remember the key points of this lesson.

  1. In function greet(name: string): string, what does the second string refer to?
    • The type of the name parameter
    • The type of the value returned by the function
    • The name of the function
  2. Which type indicates that a function returns nothing?
    • null
    • empty
    • void
    • zero
  3. Where must an optional parameter be placed in a function?
    • After the required parameters
    • Before the required parameters
    • Anywhere in the list