Typing Variables and Functions
Tell TypeScript what goes in and what comes out
Functions are where types earn their keep
Variables are a nice warm-up, but functions are where TypeScript really pays off. A function has two places where values cross a boundary: the parameters going in, and the return value coming out. You can type both.
function greet(name: string): string {
return 'Hello, ' + name + '!';
}Reading left to right: greet takes one parameter called name, which must be a string, and the function promises to return a string. The return type goes after the parameter list, using the same colon syntax you already know.
Both directions are protected
With those annotations in place, TypeScript guards the function from two kinds of mistakes. First, callers cannot pass the wrong thing in:
greet(42);That line gets an error, because 42 is not a string. Second, the function body cannot return the wrong thing:
function greet(name: string): string {
return 7;
}This also gets an error, because the function promised a string but tried to hand back a number. The promise cuts both ways, which is exactly what makes it useful.
Functions that return nothing
Plenty of functions do something, like updating the page, without returning a value. For those, the return type is void:
function logVisit(page: string): void {
console.log('Visited: ' + page);
}Arrow functions work too
If you like arrow functions from JavaScript, the annotations go in the same places:
const double = (n: number): number => n * 2;Multiple parameters
Each parameter gets its own annotation, separated by commas:
function addToCart(productId: string, quantity: number, giftWrap: boolean): void {
console.log(productId, quantity, giftWrap);
}
addToCart('mug-01', 2, false);Notice how the signature alone documents the function. You do not need to open the body or hunt for docs to know what to pass. On a team, or on a project you return to after a break, this is a quiet superpower.
Try it in your head: what would happen if you called addToCart('mug-01', 'two', false)? TypeScript would flag the second argument, because 'two' is a string but quantity must be a number.
Quick check
Q1 In function greet(name: string): string, what does the second string mean?
Q2 Which return type fits a function that updates the page but returns no value?
Want to save your progress? It's free.
Create a free account