Make your functions safer by typing their parameters, their return value and their optional parameters.
Open this lesson in KodokonA 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.
function greet(name: string): string {
return "Hello " + name + "!";
}
const message = greet("Karim");
console.log(message); // "Hello Karim!"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.
function logWelcome(name: string): void {
console.log("Welcome, " + name + "!");
}
logWelcome("Fatou"); // prints, but returns nothingJust 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.
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 missingfunction repeat(word: string, times: number = 2) {
return word.repeat(times);
}
console.log(repeat("ha")); // "haha"
console.log(repeat("ha", 3)); // "hahaha"