ts-when
JavaScript functional implementation of switch/case written in TypeScript
Note
This is a fork of a great library when-switch which seems no longer maintained.
Usage
You can convert a ts-when use in a functional way, using a single expression:
Strict Equality
const getDrinkPrice =
Assertion Matching
You can return a value when given assertion is correct
.truesomeVariable === true, "some variable is true" .else"some variable is false"
Structural Matching
You can use match
method with any object exposing a test
method.
Regular Expressions
const getCaseStyle =
Custom Type Guard Matcher
.matchCubeSchema, cube.width ** 3 .matchSphereSchema, Math.PI * 3 / 4 * sphere.radius ** 3 .elsenull
match
andis
can both be used in the samewhen
expression.
TypeScript
when
is fully compatible with TypeScript, and will check the types you return in each is
expression:
.is'Coke', 15 .is'Pepsi', 18 .else20
Here the return type of the when
expression will be number
Union types
For each is
or else
expression added to the current when
expression, the type is added as an union to the previous type.
.is'Coke', 15 .is'Pepsi', true .else'Free'
Here the return type of getDrinkPrice
expression will be number | string | boolean