Skip to content

Latest commit

 

History

History
37 lines (27 loc) · 1.08 KB

create-union-type-from-constants.md

File metadata and controls

37 lines (27 loc) · 1.08 KB

Create Union Type From Constants

I like to capture what I call magic strings in constants (variables, really) so that I can use them and reuse them with minimal maintenance. Minimal maintenance because if something about the value of the string changes, I only need to make that update in a single place.

I want to extend this reuse to my type system as well.

Let's say I have some constants defined like so:

const UPGRADE = "upgrade";
const DOWNGRADE = "downgrade";

I can create a union type from those values using the typeof operator.

type IntervalChange = typeof UPGRADE | typeof DOWNGRADE;
//=> type IntervalChange = 'upgrade' | 'downgrade'

I can then use both the constants and the type throughout my code with only one place to update.

function checkForUpgrade(interval: string): IntervalChange {
  // some logic
  const result = ...;

  return result ? UPGRADE : DOWNGRADE;
}

source