Unions and literals

string | number

A union type allows a short list of alternatives separated by a vertical bar. The value below may be text or a number, but nothing else:

let id: string | number = "abc"; id = 42; console.log(id);

42

Both assignments compile because both types belong to the union. Storing a boolean would fail, since it appears in neither alternative.

Narrow with typeof

Code can only use the members shared by every alternative until it checks which one arrived. A typeof check narrows the union, unlocking the methods of that branch:

function format(id: string | number): string { if (typeof id === "string") { return id.toUpperCase(); } return String(id); } console.log(format("abc"));

ABC

Inside the if branch, id is proven to be a string, so toUpperCase is safe. Past the branch only the number case remains, and String turns it into text.

Literal types

A literal type pins a value to exact choices instead of a whole type. The direction below can only ever be one of two texts:

let direction: "up" | "down" = "up"; console.log(direction);

up

Any typo such as upward fails the compile at once. Literals shine for modes, states, and options where the valid set is small and fixed.

Enums vs union of literals

An enum also names a fixed set, but it creates a runtime object while a literal union vanishes after compile. Prefer the lighter union unless you need the extra features of an enum:

enum Role { Admin, User } const me: Role = Role.Admin; console.log(me === Role.Admin);

true

The check prints true because me holds the Admin member. For plain string choices the union form from the previous section stays simpler and easier to combine with other types.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the type string | number allow?

    Answer

    A string or a number, and nothing else

    The vertical bar lists the alternatives, so the value must fit exactly one of them.

  2. Why does a typeof check help before calling toUpperCase on a string | number?

    Answer

    It narrows the value to the string branch

    Inside the branch the compiler knows the value is a string, so the method call is checked like any string call.

  3. What does a literal type such as "up" | "down" pin down?

    Answer

    The exact texts the value may hold

    The value must be one of the spelled literals, so any other text is a type error.

  4. What does an enum create that a union of literals does not?

    Answer

    An object that still exists after the compile

    The enum is emitted as an object, while the literal union is erased with the type notes.

  5. What does this program print? let id: string | number = "abc"; id = 42; console.log(id);

    Answer

    42

    Both a string and a number fit the union, so the second assignment is allowed.

  6. What does this program print? function format(id: string | number): string { if (typeof id === "string") { return id.toUpperCase(); } return String(id); } console.log(format("abc"));

    Answer

    ABC

    The argument is a string, so the branch returns the upper case text.

  7. What does this program print? function format(id: string | number): string { if (typeof id === "string") { return id.toUpperCase(); } return String(id); } console.log(format(7));

    Answer

    7

    The number takes the second return, and String turns it into text that prints as 7.

  8. What does the compiler say about this program? let id: string | number = "abc"; id = true; console.log(id);

    Answer

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

    A boolean is neither alternative of the union, so the assignment stops the build.

  9. What does the compiler say about this program? let direction: "up" | "down" = "upward"; console.log(direction);

    Answer

    error TS2322: Type '"upward"' is not assignable to type '"up" | "down"'.

    The literal type lists two exact texts, and upward is not one of them.

  10. What does this program print? enum Role { Admin, User } function isAdmin(role: Role): boolean { return role === Role.Admin; } console.log(isAdmin(Role.User));

    Answer

    false

    The call passes the User member, so the comparison with Admin is false.

Article author: Arthur Isaev