Narrow what a value can be

INPUT · Slides

Allow only certain values

01 / 05

A value itself can be a type

What you can write as a type is not only a kind like string. You can write the value itself, like "red", as a type.

Write that and the only thing that can go into the variable is "red". One on its own is not much use, but the next slide puts it to work.

const color: "red" = "red";console.log(color);

Result

red

02 / 05

Line the choices up with |

Line up the possible values with | and you get a type meaning "one of these". This is a union of literal types — types that are the values themselves.

It pins things down far more tightly than writing string. You can say in the type that "there are only these three colours".

let color: "red" | "blue" | "yellow";color = "blue";console.log(color);

Result

blue

03 / 05

Typos stop right there

Here is the good part of literal types. Put in anything other than what you listed and it is turned away before you run it.

Had you written string, it would have gone through, and you would be running it and wondering why the colour never changes.

let color: "red" | "blue";color = "green";

Result

Type error: Type '"green"' is not assignable to type '"red" | "blue"'.

04 / 05

Name it with type and use it again

Writing the same list of choices over and over is a chore. Give it a name with the type you learnt in chapter 2.

Once it has a name you can use the same type on variables and on parameters. And when you add a choice later, there is only one place to change.

type Color = "red" | "blue";const color: Color = "red";console.log(color);

Result

red

05 / 05

Use it on a parameter and the caller is protected

A named type can go on a function parameter too. Then it stops the caller when they get it wrong.

Time to write some. Start by lining the choices up with |.

type Color = "red" | "blue";function paint(c: Color): void {  console.log("paint in " + c);}paint("red");

Result

paint in red