Unions and Narrowing 28 exercises
Problem

Restricting Function Parameters

Here we have a move function that takes in a direction of type string, and a distance of type number:


function move(direction: string, distance: number) {
// Move the specified distance in the given direction
}

The implementation of the function is not important, but the idea is

Loading exercise

Transcript

00:00 In this exercise, we have a move function that takes in a direction, which is typed as string and a distance, which is typed as number. The idea here is we could move up by 10 pixels or move left by 5 pixels, for instance. But we're actually expecting only a certain set of strings here.

00:18 We're not expecting you to be able to call it with up right. Really, the directions that we want are up, left, down or right. And we want to make sure that only those are available and ideally that they would be auto-completable as well. So people using the function could see what types you could pass it.

00:36 So that's your job is to try to find a way to type this direction parameter as something that makes sense in this context. You will need to use a literal type, which we've not seen before, and a union type or rather mash them together and combine them. Good luck.