Functions — TypeScript

Each parameter gets a type (a: number), and the return type (the type of the returned value) goes after the closing parenthesis (): number). TypeScript…

In JavaScript a function never refuses what you send it. greet(name) called with no argument still runs and gives "Hello, undefined!". Send extra arguments, and the extras are quietly dropped. Send a number when you meant text, and that is accepted too.

In TypeScript, every parameter of a function gets a type, and so does the value it returns. It works like a payment counter: paperwork with something missing is refused at the front, and the clerk always gives back a receipt, never something else. The counter is the function, the paperwork is the arguments, and the receipt is the value the function returns. TypeScript checks every call of the function against those types before the code runs.

Types for parameters and the return

The function add below takes two numbers and returns a number:

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

add(2, 3);   // 5
add("5", 3); // error

An arrow function is written the same way: const multiply = (a: number, b: number): number => a * b;. You may leave the return type out, because TypeScript can guess it from the returned value. But if you write it, TypeScript also checks that the returned value matches that return type.

Optional and default parameters

The function greet has a second parameter, greeting. There are three ways to write it, and they behave differently:

Parameter greeting greet("Budi", "Morning") greet("Budi") greet("Budi", "Morning", "!")
greeting: string (required) "Morning, Budi!" error Expected 2 arguments, but got 1. error Expected 2 arguments, but got 3.
greeting?: string (optional) "Morning, Budi!" "undefined, Budi!" error Expected 1-2 arguments, but got 3.
greeting = "Hello" (default) "Morning, Budi!" "Hello, Budi!" error Expected 1-2 arguments, but got 3.

Every wrong-number-of-arguments error has the code ts(2554). This is the second way, an optional parameter:

function greet(name: string, greeting?: string): string {
  return `${greeting}, ${name}!`;
}

greet("Budi"); // "undefined, Budi!"

A ? after a parameter's name makes it optional: it may be left out. Inside the function its type becomes string | undefined. TypeScript lets undefined be printed in a template literal (text between backticks, with ${}), so greet("Budi") returns "undefined, Budi!". TypeScript only reports an error when you call a string method, for example greeting.toUpperCase(): 'greeting' is possibly 'undefined'. (ts(18048)).

For a fallback greeting, use a default value, the value used when the argument is not sent:

function greet(name: string, greeting = "Hello"): string {
  return `${greeting}, ${name}!`;
}

greet("Budi");            // "Hello, Budi!"
greet("Budi", "Morning"); // "Morning, Budi!"

greeting = "Hello" may also be left out. The difference: inside the function greeting is always a string, because the default fills the gap. TypeScript guesses its type from that default, so you don't need to write the type. A parameter with ? must come after the required ones. For example, greet(greeting?: string, name: string) is rejected: A required parameter cannot follow an optional parameter. (ts(1016)).

Return type: void and undefined

A function that only prints, returning nothing, gets the return type void:

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

const result = logMessage("Hello");
result.length; // error

Rest parameter: many arguments in one array

A rest parameter gathers many arguments into one array. The function sum below uses one to add up as many numbers as you send:

function sum(...numbers: number[]): number {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20));  // 30
console.log(sum());        // 0
Round total before n total after
1 0 1 1
2 1 2 3
3 3 3 6

The starting value 0 also makes sum() with no arguments still return 0. Without a starting value, an empty array causes an error when the code runs: Reduce of empty array with no initial value.

⚠️ Why do I get undefined or NaN?

TL;DR: Each parameter gets a type (a: number), and the return type (the type of the returned value) goes after the closing parenthesis (): number). TypeScript rejects an argument of the wrong type or the wrong count (Expected 2 arguments, but got 1.). greeting?: string makes a parameter optional (it may be left out), but it may hold undefined. greeting = "Hello" gives it a default value, used when the argument is not sent. void is for a function that returns nothing, and its result must not be used. The rest parameter ...numbers: number[] gathers every argument into one array. The function sum adds up that array with reduce((total, n) => total + n, 0), so sum(1, 2, 3) = 6 and sum() = 0.

⚡ Types for parameters and the return

Write:

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

add(2, 3);   // 5
add("5", 3); // error

Meaning: Each parameter gets its own type. ): number is the return type: the type of the value this function returns. An argument of the wrong type, or too few or too many arguments, is rejected before the code runs.

⚡ Optional or default

Write:

function greet(name: string, greeting?: string): string {
  return `${greeting}, ${name}!`;
}

greet("Budi");
Guess first: the ? in greeting? means greeting may be left out. What does greet("Budi") give?

"undefined, Budi!". greeting isn't sent, so it holds undefined, and the template literal still prints it.

Meaning: When there's a fallback greeting, use a default value, the value used when the argument is not sent: greeting = "Hello". greet("Budi") then gives "Hello, Budi!", and inside the function greeting is always a string. Optional parameters go after the required ones.

⚡ Rest parameter: many arguments in one array

Write:

function sum(...numbers: number[]): number {
  return numbers.reduce((total, n) => total + n, 0);
}

sum(1, 2, 3); // 6
sum();        // 0

Meaning: ...numbers is a rest parameter. A rest parameter gathers every argument into one array, so its type is number[], and it has to be the last parameter. The starting value 0 in reduce makes sum() with no arguments still give 0.

What you will learn