JS/TS
  • JavaScript Development
  • JS Principles
    • JS Principles
      • Primitive data types
      • typeof operator
      • Scope
      • Hoisting
      • IIFE
      • Closure
      • Anonymous functions in JS
      • Conditional (ternary) operator
        • Coercion vs Conversion
      • Event-driven programming
      • Factory Function
      • JSON.stringify()
      • Strict mode
      • super() keyword
      • What are memory leaks?
      • Micro-tasks within an event loop (Summary)
      • Macro-tasks within an event loop (Summary)
      • null vs undefined
    • Memory Management
    • Advanced function concepts
      • Impure vs Pure Functions
      • Factory functions
  • JavaScript Objects & Arrays
    • Introducing JavaScript objects
      • Build-in objects
        • isNaN()
      • RegExp
        • RegExp.prototype.test()
      • String
        • String.prototype.split()
        • String.prototype.slice()
      • Objects
        • Object.assign()
        • Object.create()
        • Object.defineProperties()
        • Object.defineProperty()
        • Object.entries()
        • Object.freeze()
        • Object.getOwnPropertyNames()
        • Object.getPrototypeOf()
        • Object.isFrozen()
        • Object.isSealed()
        • Map
      • Standard built-in methods to work with Arrays
        • Array.of()
        • Array.prototype.concat()
        • Array.prototype.every()
        • Array.prototype.filter()
        • Array.prototype.find()
        • Array.prototype.findIndex()
        • Array.prototype.forEach()
        • Array.prototype.join()
        • Array.prototype.map()
        • Array.prototype.pop()
        • Array.prototype.shift()
        • Array.prototype.reverse()
        • Array.prototype.some()
        • Array.prototype.sort()
        • Array.prototype.splice()
        • Array.prototype.unshift()
        • Array.prototype.includes()
        • Array.prototype.flatMap()
      • Prototypal inheritance
        • Inheritance with the prototype chain
        • Inheriting "methods"
  • JavaScript Mid
    • JavaScript & ES
      • Arrow Function
      • Anonymous Function
      • Callbacks
      • Promises
      • var, let, and const
      • Fetch API (function)
      • Fetch API
      • Synchronous vs Asynchronous
      • Encapsulation
      • Destructuring assignment
      • call() - apply() - bind()
      • 'This' keyword
      • Functional Programming
  • Browser
    • Event-driven programming
  • TypeScript
    • The TypeScript Handbook
      • Basic Types
      • Interfaces
      • Functions
      • Literal Types
      • Unions and Intersection Types
      • Classes
      • Enums
      • Generics
      • Implements vs extends
  • Hackerrank Practices
    • Practices and examples
  • JS Math
    • Mathematical
      • JavaScript | Math.E() function
      • Math.abs( ) Method
      • Math.ceil( ) function
      • Math floor()
      • Math.imul( ) Function
      • Math log( ) Method
      • Math max()/min() Method
      • Math pow( ) Method
      • Math.sign( ) Function
      • Math sqrt( ) Method
Powered by GitBook
On this page
  • Literal Narrowing
  • String Literal Types
  • Numeric Literal Types
  • Boolean Literal Types

Was this helpful?

  1. TypeScript
  2. The TypeScript Handbook

Literal Types

A literal is a more concrete sub-type of a collective type. What this means is that "Hello World" is a string, but a string is not "Hello World" inside the type system.

There are three sets of literal types available in TypeScript today: strings, numbers, and booleans; by using literal types you can allow an exact value which a string, number, or boolean must have.

Literal Narrowing

When you declare a variable via var or let, you are telling the compiler that there is the chance that this variable will change its contents. In contrast, using const to declare a variable will inform TypeScript that this object will never change.

// We're making a guarantee that this variable
// helloWorld will never change, by using const.

// So, TypeScript sets the type to be "Hello World", not string
const helloWorld = "Hello World";

// On the other hand, a let can change, and so the compiler declares it a string
let hiWorld = "Hi World";Try

The process of going from an infinite number of potential cases (there are an infinite number of possible string values) to a smaller, finite number of potential case (in helloWorld’s case: 1) is called narrowing.

String Literal Types

In practice string literal types combine nicely with union types, type guards, and type aliases. You can use these features together to get enum-like behavior with strings.

type Easing = "ease-in" | "ease-out" | "ease-in-out";

class UIElement {
  animate(dx: number, dy: number, easing: Easing) {
    if (easing === "ease-in") {
      // ...
    } else if (easing === "ease-out") {
    } else if (easing === "ease-in-out") {
    } else {
      // It's possible that someone could reach this
      // by ignoring your types though.
    }
  }
}

let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy");
Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.Try

You can pass any of the three allowed strings, but any other string will give the error

Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'

String literal types can be used in the same way to distinguish overloads:

function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...
function createElement(tagName: string): Element {
  // ... code goes here ...
}

Numeric Literal Types

TypeScript also has numeric literal types, which act the same as the string literals above.

function rollDice(): 1 | 2 | 3 | 4 | 5 | 6 {
  return (Math.floor(Math.random() * 6) + 1) as 1 | 2 | 3 | 4 | 5 | 6;
}

const result = rollDice();Try

A common case for their use is for describing config values:

interface MapConfig {
  lng: number;
  lat: number;
  tileSize: 8 | 16 | 32;
}

setupMap({ lng: -73.935242, lat: 40.73061, tileSize: 16 });Try

Boolean Literal Types

TypeScript also has boolean literal types. You might use these to constrain object values whose properties are interrelated.

interface ValidationSuccess {
  isValid: true;
  reason: null;
}

interface ValidationFailure {
  isValid: false;
  reason: string;
}

type ValidationResult = ValidationSuccess | ValidationFailure;
PreviousFunctionsNextUnions and Intersection Types

Last updated 4 years ago

Was this helpful?