Norwegian Pony Master

    ts-unreachable
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.0 • Public • Published

    Unreachable for TypeScript

    Utility function for exhaustiveness checking with TypeScript.

    Installation

    npm install --save ts-unreachable

    Usage

    import unreachable = require('ts-unreachable')
     
    type Shape = 
      | { kind: 'square', size: number }
      | { kind: 'rectangle', width: number, height: number }
      | { kind: 'circle', radius: number }
     
    function area (shape: Shape): number {
      if (shape.kind === 'square') {
        return shape.size ** 2
      }
     
      if (shape.kind === 'rectangle') {
        return shape.height * shape.width
      }
     
      if (shape.kind === 'circle') {
        return Math.PI * shape.radius ** 2
      }
     
      return unreachable(shape) // (1)
    }
    1. Without the final call to unreachable, TypeScript would report the following error:

      Function lacks ending return statement and return type does not include 'undefined'. (2366)

      Calling the function with an invalid kind from JavaScript would also return undefined instead of throwing a TypeError.

    Prior Art

    Install

    npm i ts-unreachable

    DownloadsWeekly Downloads

    51

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    1.74 kB

    Total Files

    4

    Last publish

    Collaborators

    • linusu