Specify Exact Values with TypeScript’s Literal Types

Share this video with your friends

Send Tweet

A literal type is a type that represents exactly one value, e.g. one specific string or number. You can combine literal types with union types to model a finite set of valid values for a variable. In this lesson, we explore the all kinds of literal types in TypeScript:

  • String literal types
  • Numeric literal types
  • Boolean literal types
  • Enum literal types
Shobhit
Shobhit
~ 6 years ago

Couldn't enums serve the same purpose?

Marius Schulz
Marius Schulz(instructor)
~ 6 years ago

@Shobhit: Yes, enums and literal types serve similar purposes. Both specify a finite set of allowed value. However, enums are TypeScript-only construct; they don't exist in JavaScript. They're compiled to plain objects. Literal types only exist in the type system. They're completely compiled away and don't exist at runtime at all.

You can use literal types to specify exactly which string/number/boolean values are valid for a given property/parameter/…:

interface ScrollToOptions extends ScrollOptions {
    behavior?: "auto" | "instant" | "smooth";
    left?: number;
    top?: number;
}

declare function scrollTo(options?: ScrollToOptions): void;
Dean
Dean
~ 5 years ago

When you did the example of 2 | 4 | 6 etc... made me think "is there a way to type an 'even' number'.. so, instead of union typing 2|4|6|8|10 etc.... have some type that denotes "even"?

Marius Schulz
Marius Schulz(instructor)
~ 5 years ago

@Dean: There's no even type or anything alike — literal types currently don't support that; you'll have to explicitly list all the values that you want to allow.