title: In typescript, is there a way to ensure that a function's return type is exhaustive?
body: <p>If you have a const enum like</p>
  
  <pre><code>enum Color {
    RED,
    GREEN,
    BLUE,
  }
  </code></pre>
  
  <p>You can write a helper and a switch statement,</p>
  
  <pre><code>function assertNever(x: never): never {
      throw new Error(`Unexpected object: ${x}`)
  }
  
  function toString (key: Color): string {
    switch (key) {
      case Color.RED: return 'Red'
      case Color.GREEN: return 'Green'
      case Color.BLUE: return 'Blue'
      default: return assertNever(key)
    }
  }
  </code></pre>
  
  <p>such that if we ever change <code>Color</code>, we must change our <code>toString</code> implementation.</p>
  
  <p>However, if I go the other way,</p>
  
  <pre><code>function fromString (key: string): Color {
    switch (key) {
      case 'Red': return Color.RED
      case 'Green': return Color.GREEN
      case 'Blue': return Color.BLUE
      default: throw new Error(`${key} is not a Color`)
    }
  }
  </code></pre>
  
  <p>It is possible that my fromString implememtation may get out of date with my Color enum. </p>
  
  <p>Is there a way to ensure that there exists some path that returns each kind of <code>Color</code>? Is there are way to ensure that the range of the function is <code>Color</code>?</p>