Guard your functions with types

INPUT · Slides

Hand a function itself around

01 / 05

A function type looks like a function

A function is a value too, so it has a type. The writing looks very like a function itself — inside the brackets are the parameter types, right of the arrow is the return type.

The double below is a variable that holds "a function taking a number and returning a number".

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

Result

12

02 / 05

Take a function as a parameter

Write a function type as a parameter type and you have made a function that takes a function. This is the callback you wrote in the JavaScript course.

The receiving side only calls it. What can be handed over is settled by the type.

function use(  s: string,  decorate: (s: string) => string): void {  console.log(decorate(s));}use("rain", (s) => "-" + s + "-");

Result

-rain-

03 / 05

Name a function type with type

Writing the same function type over and over is a chore. The type you used in chapter 2 works on function types too.

With a name, the row of parameters gets shorter and easier to read.

type Decorate = (s: string) => string;function use(s: string, f: Decorate): void {  console.log(f(s));}use("snow", (s) => "[" + s + "]");

Result

[snow]

04 / 05

A function of the wrong shape will not go in

Where you declared "takes text and returns text", a function returning a number will not go.

The s.length below is a number, so it breaks the promise of Decorate. You are stopped on this line, before it is ever handed over.

type Decorate = (s: string) => string;const decorate: Decorate = (s) => s.length;

Result

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

05 / 05

A function that returns nothing is => void

If you want to take in a function that only shows something, put void to the right of the arrow.

There is only one thing to remember: inside the brackets are the parameters, right of the arrow is the return. Right, have a go at handing functions around.

type Notify = (s: string) => void;function sendAll(  list: string[],  f: Notify): void {  for (const s of list) {    f(s);  }}sendAll(["morning", "night"], (s) => {  console.log(s + " it is");});

Result

morning it is
night it is