Guard your functions with types

INPUT · Slides

Array methods and inferred types

01 / 06

You need not type the parameter you hand over

Run map over a string[] and TypeScript already knows that the function you handed over receives text. So there is no need to type the (f).

This working out is called type inference — types worked out for you.

const fruits: string[] = ["apple", "plum"];const lengths = fruits.map(  (f) => f.length);console.log(lengths);

Result

[5, 4]

02 / 06

You may write it, but do not

Of course you can write (n: number) => n * 2. But it is already settled by the array type, so it reads better without.

Do not write what is already obvious. That is the knack of getting along with types.

const nums: number[] = [1, 2, 3];const doubled = nums.map((n) => n * 2);console.log(doubled);

Result

[2, 4, 6]

03 / 06

The type that comes back is settled too

The type of array map gives back is settled by what the function you handed over returns. Hand a "turn a number into text" function to a number[] and what comes back is a string[].

So writing const labels: string[] = goes through. It agrees with the type that was already settled.

const nums: number[] = [1, 2];const labels: string[] = nums.map(  (n) => n + " pcs");console.log(labels);

Result

["1 pcs", "2 pcs"]

04 / 06

Write a type that does not fit and you are stopped

Go out of your way to write a type other than the settled one and you get an error on that line. What map gives back is an array, so it will not go into a string variable.

Leave it out and it is understood; write it wrongly and you are told. Either way you win.

const fruits: string[] = ["apple"];const lengths: string = fruits.map(  (f) => f.length);

Result

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

05 / 06

filter leaves the contents type alone

filter only picks out what fits the condition, so the contents of the array you get back have the same type as before. The function you hand over returns a boolean.

filter a number[] and what comes out is a number[].

const nums: number[] = [1, 2, 3, 4];const evens = nums.filter((n) => n % 2 === 0);console.log(evens);

Result

[2, 4]

06 / 06

Where to write, and where to leave it

There is one guide for drawing the line: write it at the border with other people.

  • A function's parameters and return are a border, so write them
  • Things settled by a type right next door, like the parameter of a function handed to map, are not worth writing

Types are not "the more you write the better". Writing just enough to get across to whoever reads it is about right. Right, have a go.