Guard your functions with types

INPUT · Slides

Add types to an arrow function

01 / 05

Types go on an arrow function the same way

Remember the => shape from the JavaScript course. const name = () => { }; — that one.

Where the types go has not changed from a variable or a function. A : and a type after the name of the parameter. That is it.

const call = (name: string) => {  console.log("Hi, " + name);};call("Yui");

Result

Hi, Yui

02 / 05

The return type goes after the brackets

The type of what comes back goes in the same place as with function — a : and a type right after you close the brackets around the parameters.

The only difference is that a => follows it. The order is (parameters): return => { }.

const double = (n: number): number => {  return n * 2;};console.log(double(21));

Result

42

03 / 05

One expression can be written shorter

When the only thing inside the { } is a single return line, you can drop the { } and the return and put the expression straight to the right of the =>.

It means exactly the same as above. You will see this shorter shape a lot in real code.

const double = (n: number): number =>  n * 2;console.log(double(4));

Result

8

04 / 05

Written shorter, still watched

Making the shape shorter does not switch the type checking off. Hand text to a function you said takes a number and it stops you on the line where you called it.

Writing it short and being looked after go together perfectly well.

const double = (n: number): number =>  n * 2;console.log(double("3"));

Result

Type error: Argument of type 'string' is not assignable to parameter of type 'number'.

05 / 05

No parameters, same writing

When there is nothing to take in, leave the () as it is and put the return type after it. If it only shows something, that is void.

There is only one thing to remember: the types go in the same places as with function. Right then, have a go.

const notify = (): void => {  console.log("all ready");};notify();

Result

all ready