Functions as Values

A function type describes a callable. type Formatter = (value: number) => string.

This is what you use for callback props, event handlers and anything passed to map. Typing it is where a surprising number of real bugs get caught, because the wrong argument to a callback is exactly the kind of thing nobody notices until it runs.

Try it

Add a second parameter to asMoney that Formatter does not declare, and see what the compiler says. Then remove one that it does declare, and notice that is allowed.

loading editor…

checking…

Notice that asMoney needs no annotation on v. The type of the variable flows into the function, which is called contextual typing and saves a great deal of noise.

◈ Graded Types

Write a function called shelve that takes a title (string) and an optional count (number) which defaults to 1, and returns a string. With a count of 1 it returns "Kindred x1". Then write a function type called Labeler describing a function that takes a string and returns a string, and declare a variable called shout of that type which upper-cases its input. Both must type-check in strict mode.

Checked against the compiler, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…
real tsc, strict mode

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back