Narrow what a value can be

INPUT · Slides

Either type will do

01 / 05

Writing "it could be either"

Every type so far has been "just this one". string means only text, number means only numbers.

But in real life there are places where either one is possible. A queue number that some people hold as 12 and others as "A12", say. That is where a union type comes in — types joined together with |.

let ticket: string | number = 12;console.log(ticket);ticket = "A12";console.log(ticket);

Result

12
A12

02 / 05

Just join them with |

The writing is nothing more than putting a | between two types. It means "either text or a number".

And it does not have to be two. Three or more in a row is fine too.

let value: string | number | boolean;value = true;console.log(value);

Result

true

03 / 05

It does not mean "anything goes"

"Either one" is not the same as "anything". What is allowed is only the types you listed.

Try to put true into a variable you wrote as string | number and it gets turned away, just as before.

let ticket: string | number = 12;ticket = true;

Result

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

04 / 05

Some things you cannot do while it is still undecided

Write a union type and TypeScript changes its attitude. While it does not know which one it is, it will not let you do something only one of them can do.

toUpperCase() is a method on strings. Numbers do not have it, so trying to call it stops you.

function show(m: string | number) {  console.log(m.toUpperCase());}

Result

Type error: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

05 / 05

Anything both can do, you can write straight away

If it is something either of them can do, you can write it without narrowing anything down. Showing a value with console.log works for text and for numbers, so this goes through.

The way to narrow down comes later in this chapter. Start by joining types with |.

function show(m: string | number) {  console.log(m);}show("Yui");show(7);

Result

Yui
7