Skip to content
This repository was archived by the owner on Jan 26, 2022. It is now read-only.
This repository was archived by the owner on Jan 26, 2022. It is now read-only.

Request to add: unreachable #21

@Jack-Works

Description

@Jack-Works

Implementation: (maybe Function.unreachable)

function unreachable(_val) {
    throw new TypeError()
}

Usage:

function route(direction) {
    switch (direction) {
        case "up": case "down": return "left";
        case "left": case "right": return "up";
        default: Function.unreachable(direction)
    }
}

The real power of this helper is used with TypeScript. This function should have type signature (val: never) => never

type Direction = 'up' | 'down' | 'left' | 'right'
function route(direction: Direction) {
    switch (direction) {
        case "up": case "down": return "left";
        case "left": case "right": return "up";
        default: Function.unreachable(direction)
    }
}

It will provide an exhaustive matching guard, which means if I'm missing some cases, it will become a compile error.

Let's say I add one new direction to the type Direction

type Direction = 'up' | 'down' | 'left' | 'right' | 'stay'

image

The compiler will tell me that: hey! direction is no longer type never (when you exhaustive all possibilities of a variable), you still have one case to check!

This unreachable function is very useful and I have implemented it in many of my repos.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions