TypeScript · Lesson 11 of 42
Typing function parameters and return values
Annotate function parameters and return types, type arrow functions and object parameters, and see what the compiler checks at each call.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will write fully typed functions: parameters, return values, arrow functions and object parameters. Functions are where type errors are most often caught, because every call is a place where the wrong value can slip in.
Parameters and return types
Add a type after each parameter name, and a return type after the closing parenthesis:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));5The compiler now checks every call, in two ways. It checks the count of arguments and the type of each one:
function add(a: number, b: number): number {
return a + b;
}
add(1);
add(1, "2");
add(1, 2, 3);example.ts(5,1): error TS2554: Expected 2 arguments, but got 1.
example.ts(6,8): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
example.ts(7,11): error TS2554: Expected 2 arguments, but got 3.Each message names the problem exactly: how many arguments were expected, or which type was found. In plain JavaScript, a missing argument becomes undefined and an extra one is silently ignored, which is the source of many subtle bugs.
The return type
The return type tells callers what they get back. You can leave it out, and the compiler infers it from the return statements, but writing it on functions other code depends on has two benefits. It documents the function, and it makes the compiler check the body against your intention:
function average(values: number[]): number {
if (values.length === 0) {
return "none";
}
return values.reduce((sum, v) => sum + v, 0) / values.length;
}example.ts(3,5): error TS2322: Type 'string' is not assignable to type 'number'.Without the annotation, the function would quietly return string | number, and the surprise would show up in whichever code called it. With the annotation, the mistake is flagged at its source. A missing return on some path is also caught when the return type is not void:
function sign(n: number): string {
if (n > 0) {
return "positive";
} else if (n < 0) {
return "negative";
}
}example.ts(1,27): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.Functions that return nothing
When a function does its work for a side effect, such as printing, give it the return type void:
function logTotal(label: string, total: number): void {
console.log(`${label}: ${total}`);
}
logTotal("Cart", 59.97);Cart: 59.97Function expressions and arrow functions
Arrow functions and function expressions are typed exactly like declarations:
const multiply = (a: number, b: number): number => a * b;
const greet = function (name: string): string {
return `Hello, ${name}`;
};
console.log(multiply(4, 5), greet("Asha"));20 Hello, AshaFor short arrows the return type is usually left to inference, because the expression makes it obvious.
Object parameters
Functions often take an object of options. Give the object a type, either inline or with an alias, and destructure it as usual:
type Order = { id: number; items: string[]; express?: boolean };
function summarise({ id, items, express = false }: Order): string {
return `Order ${id}: ${items.length} item(s)${express ? ", express" : ""}`;
}
console.log(summarise({ id: 7, items: ["pen", "ink"] }));
console.log(summarise({ id: 8, items: ["book"], express: true }));Order 7: 2 item(s)
Order 8: 1 item(s), expressThe annotation goes after the whole destructuring pattern, not inside it. Reading it as "the parameter, taken apart like this, has the type Order" makes the syntax easier to remember.
Common mistakes
Leaving parameters unannotated. In strict mode, a parameter with no type and no context is an error. Add the type.
Forgetting that return types are checked. If you annotate : number, every path must return a number.
Using void when you mean to return a value. void tells callers to ignore the result. If the function should return something, name the type.
Annotating destructured fields inside the braces. function f({ id: number }) renames the property to a variable called number. Put the annotation after the pattern.
Relying on inference for public functions. Inference is fine inside a module. For functions other code depends on, an explicit return type is a clear contract.
Exercise
Write function formatPrice(amount: number, currency: string): string that returns text like "USD 19.99" with two decimals. Call it with the wrong argument types and with a missing argument, and read the messages. Then write a function with an object parameter { name: string; age?: number } that returns a greeting, using a default for the missing age.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.