All Projects → Gozala → unreachable

Gozala / unreachable

Licence: MIT license
Utility function for exhaustiveness checking with typed JS (TS or Flow)

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to unreachable

ExhaustiveMatching
C# Analyzer Adding Exhaustive Checking of Switch Statements and Expressions
Stars: ✭ 60 (+328.57%)
Mutual labels:  discriminated-unions, exhaustiveness-checking
variant
Variant types in TypeScript
Stars: ✭ 147 (+950%)
Mutual labels:  discriminated-unions
FsCodec
F# Event-Union Contract Encoding with versioning tolerant converters supporting System.Text.Json and Newtonsoft.Json
Stars: ✭ 74 (+428.57%)
Mutual labels:  discriminated-unions
results
Discriminated Unions including Maybe (an option type) and Result for javascript with fewer bugs
Stars: ✭ 34 (+142.86%)
Mutual labels:  discriminated-unions
dotvariant
A type-safe and space-efficient sum type for C# (comparable to discriminated unions in C or C++)
Stars: ✭ 52 (+271.43%)
Mutual labels:  discriminated-unions
assert-never
Helper function for exhaustive checks of discriminated unions in TypeScript
Stars: ✭ 32 (+128.57%)
Mutual labels:  discriminated-unions
total
Basic exhaustiveness checking of unions in Elixir
Stars: ✭ 15 (+7.14%)
Mutual labels:  exhaustiveness-checking
tagmeme
Simple tagged unions
Stars: ✭ 21 (+50%)
Mutual labels:  tagged-unions
mir-core
Base software building blocks: Algebraic types (aka sumtype/tagged union/variant), universal reflection API, basic math, and more.
Stars: ✭ 23 (+64.29%)
Mutual labels:  tagged-unions
ftor
ftor enables ML-like type-directed, functional programming with Javascript including reasonable debugging.
Stars: ✭ 44 (+214.29%)
Mutual labels:  tagged-unions

unreachable

travis package downloads styled with prettier

Utility function for exhaustiveness checking with (typed) JS (Be it TypeScript or Flow)

Problem

Exhaustiveness checking for Tagged Unions

Tagged unions are present in both in Flow reffered as Disjoint Unions and in TypeScript referred as Discriminated Unions. Unfortunately both utilize JS switch statements for pattern matching that comes with inherent limitations.

Consider following example that is both flow & typescript code:

type Shape =
  | { kind: "square", size: number }
  | { kind: "rectangle", width: number, height: number }
  | { kind: "circle", radius: number }

const area = (shape: Shape):number => {
  switch (shape.kind) {
    case "square":
      return shape.size * shape.size
    case "rectangle":
      return shape.height * shape.width
    case "circle":
      return Math.PI * shape.radius ** 2
  }
}

Exhaustiveness problem (Flow)

As of this writing Flow (0.49.1) fails to typecheck as it's still unable to detect exhaustive type refinements and there requires default case:

/* @flow */

type Shape =
  | { kind: "square", size: number }
  | { kind: "rectangle", width: number, height: number }
  | { kind: "circle", radius: number }

const area = (shape: Shape):number => {
  switch (shape.kind) {
    case "square":
      return shape.size * shape.size
    case "rectangle":
      return shape.height * shape.width
    case "circle":
      return Math.PI * shape.radius ** 2
    default:
      throw new TypeError(`Unsupported shape was passed: ${JSON.stringify(shape)}`)
  }
}

But that is not ideal as type checker will no longer be able to catch errors if we add variant to our Shape union:

type Shape =
  | { kind: "square", size: number }
  | { kind: "rectangle", width: number, height: number }
  | { kind: "circle", radius: number }
  | { kind: "triangle", a:number, b:number, c:number } // <- added variant

Last version of area function will still type check and accept triangles but type checker will not be able to report an error instead we'll get one at runtime.

JS call site problem

As of this writing TypeScript (2.4) with strictNullChecks has a proper [exhaustiveness checking][] support and there for is free of the [Exhaustiveness problem][#Exhaustiveness_problem_flow] & original code type checkes fine, it also will not type check if more variants are added to Shape union and unless area funciton is also modified to handle that.

Still original code is not ideal if call site (of area) function is not type checked, if say call site is JS like code below:

area({ kind:"circl", radius:7 }) // => undefined

There will be no erros reported by area function it will just return undefined instead of number and likely causing error down the line that is harded to track down. And that is where this library can help, in fact it just provides a function that TypeScript Handbook recommends as a good practice.

Solution

This library provides default export function that takes single argument of the bottom type, which denotes type of the value that can never occur and throws a TypeError with helpful message when invoked. In TypeScript it is referred as never and in Flow it (is not yet documented, but) is referred as empty.

import unreachable from "unreachable"

type Shape =
  | { kind: "square", size: number }
  | { kind: "rectangle", width: number, height: number }
  | { kind: "circle", radius: number }

const area = (shape: Shape):number => {
  switch (shape.kind) {
    case "square":
      return shape.size * shape.size
    case "rectangle":
      return shape.height * shape.width
    case "circle":
      return Math.PI * shape.radius ** 2
    default:
      return unreachable(shape)
  }
}

Above code type checks both in Flow and TypeScript. While following code does not type check:

import unreachable from "unreachable"

type Shape =
  | { kind: "square", size: number }
  | { kind: "rectangle", width: number, height: number }
  | { kind: "circle", radius: number }
  | { kind: "triangle", a:number, b:number, c:number } // <- Added variant

const area = (shape: Shape):number => {
  switch (shape.kind) {
    case "square":
      return shape.size * shape.size
    case "rectangle":
      return shape.height * shape.width
    case "circle":
      return Math.PI * shape.radius ** 2
    default:
      return unreachable(shape)
  }
}

Flow will report that shape:Shape is incompatible with expected empty type. TypeScript will report that { kind: "triangle"; a: number; b: number; c: number; } is incompatible with never.

Obviously type checker won't help with incorrect call from JS call site, but at least it will throw an exception from the shape function with helpful message and stack trace leading to the source of the error:

area({ kind:"circl", radius:7 })
//> TypeError('Internal error: Encountered impossible value: { kind:"circl", radius:7 }')

Install

npm install unreachable

Prior Art

Somewhat inspired by Rust unreachable macro.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].