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
a: numbergives the parameteraa type. Each parameter gets its own type.): numberafter the closing parenthesis is the return type: the type of the value this function returns, here a number.add("5", 3)is rejected:Argument of type 'string' is not assignable to parameter of type 'number'.(ts(2345)).- If the function body did
return "Hello", the value would not match the return type:Type 'string' is not assignable to type 'number'.(ts(2322)). - A parameter with no type is rejected in strict mode:
Parameter 'a' implicitly has an 'any' type.(ts(7006)).
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
voidmeans "this function's result is not meant to be used". Soresult.lengthis rejected:Property 'length' does not exist on type 'void'.(ts(2339)).- A
voidfunction that returns text is rejected too:Type 'string' is not assignable to type 'void'. - In the opposite case, a function with the return type
stringthat forgetsreturnis rejected:A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.(ts(2355)). undefinedas a return type means the result really is the valueundefined. It's rarely used. For "returns nothing", usevoid.
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
...numbers(three dots, then a name) gathers every argument into one array callednumbers.sum(1, 2, 3)makesnumbers=[1, 2, 3].- Its type is written as an array:
number[].sum(1, "2")is rejected:Argument of type 'string' is not assignable to parameter of type 'number'. - A rest parameter takes every argument the other parameters did not take, so it must be the last parameter:
A rest parameter must be last in a parameter list.(ts(1014)). reducewith the starting value0adds the array's items one by one.totalis the sum so far, andnis the item being read:
| 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?
- Using an optional parameter without checking it. You get
"undefined, Budi!", or the error'greeting' is possibly 'undefined'.Use a default value when there is a fallback. - Using the result of a
voidfunction. There's nothing to use. If you need the result, add areturnfor it and change the return type. - Thinking a TypeScript error stops the code. Types are removed when the code is turned into JavaScript. So
greet("Budi")with a requiredgreetingstill runs and returns"undefined, Budi!". A TypeScript error is a warning: fix it before other people use the code. - Adding with fixed indexes.
numbers[0] + numbers[1] + numbers[2]is only right for three arguments.sum(10, 20)becomesNaN, becausenumbers[2]isundefined. Add up the whole array.
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.