Arrow Functions
Arrow functions get their types in the same places. A parameter's type goes after its name, and the return type after the parentheses, before the arrow:
const double = (n: number): number => n * 2;
const describe = (name: string): string => `Hero: ${name}`;
console.log(double(21));
console.log(describe("Kira"));This prints:
42
Hero: KiraRead (n: number): number => as “takes a number n and returns a number”. The rules are the same as for functions written with function. The return type may be left out, and TypeScript works it out. Every call is checked. And a parameter without a type is an error, also when it's written the short way, without parentheses:
const double = (n) => n * 2;
const describe = name => `Hero: ${name}`;main.ts(1,17): error TS7006: Parameter 'n' implicitly has an 'any' type.
main.ts(2,18): error TS7006: Parameter 'name' implicitly has an 'any' type.In JavaScript, an arrow function with one parameter may be written without the parentheses: name => .... With a type, the parentheses are needed: (name: string) => .... Without them, you get errors that don't help much:
const describe = name: string => `Hero: ${name}`;main.ts(1,22): error TS1005: ',' expected.
main.ts(1,31): error TS1005: ';' expected.The return type is especially useful when the body is in curly braces. You know this mistake from the JavaScript course: curly braces without return, so the function returns undefined. With a return type, TypeScript catches it:
const double = (n: number): number => {
n * 2;
};
console.log(double(21));main.ts(1,29): error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.Without the return type, the program would print undefined. With curly braces, you have to write return n * 2;, or leave the braces out: (n: number): number => n * 2.
An arrow function that returns nothing has the return type void, and one without parameters has empty parentheses: const cheer = (): void => console.log("Hooray!");. Default values work too: (health: number, amount: number = 10): number => health + amount.
Instructions
- 1
Give the parameters of the two arrow functions their types:
poweris anumber, andnameis astring. The program then runs, but its second line saysundefined. - 2
Give both arrow functions their return types:
numberforfireballandstringforspellName. TypeScript then reports the bug inspellName. Fix it, so that the function returns the text. The program prints:12 FROST! 45 - 3
Rewrite the function
healas an arrow function stored inconst heal, with the same parameter types and the return typenumber. The program prints the same lines as before. - 4
At the end of the program, print
heal(fireball(2), 4): the result of one arrow function goes straight into another, and TypeScript checks that a number goes where a number is expected. The program prints:12 FROST! 45 10