String literal types

It’s not uncommon for an API to expect a specific set of strings for certain values.For instance, consider a UI library that can move elements across the screen while controlling the “easing” of the animation.

  1. declare class UIElement {
  2. animate(options: AnimationOptions): void;
  3. }
  4. interface AnimationOptions {
  5. deltaX: number;
  6. deltaY: number;
  7. easing: string; // Can be "ease-in", "ease-out", "ease-in-out"
  8. }

However, this is error prone - there is nothing stopping a user from accidentally misspelling one of the valid easing values:

  1. // No errors
  2. new UIElement().animate({ deltaX: 100, deltaY: 100, easing: "ease-inout" });

With TypeScript 1.8, we’ve introduced string literal types.These types are written the same way string literals are, but in type positions.

Users can now ensure that the type system will catch such errors.Here’s our new AnimationOptions using string literal types:

  1. interface AnimationOptions {
  2. deltaX: number;
  3. deltaY: number;
  4. easing: "ease-in" | "ease-out" | "ease-in-out";
  5. }
  6. // Error: Type '"ease-inout"' is not assignable to type '"ease-in" | "ease-out" | "ease-in-out"'
  7. new UIElement().animate({ deltaX: 100, deltaY: 100, easing: "ease-inout" });