In typedraft 0.2.5
(use draft-dsl-match 0.2.0), we have full support of pattern match as DSL:
import { MatchDSL } from "draft-dsl-match";
type Vector1 = { x: number };
type Vector2 = { x: number; y: number };
type Vector3 = {
x: number;
y: number;
z: number;
};
type Vector = Vector1 | Vector2 | Vector3;
const vector: Vector = { x: 1 };
const result = Λ<string>("match")` ${vector as Vector}
${{ x: 1, y: 1, z: 1 }} -> ${"vector3"}
${{ x: 2, y: 1 }} -> ${"vector2"}
${{ x: 1 }} -> ${"vector1"}
`;
console.log(result); // "vector1"
Λ<string>("match")...
will be translated to MatchDSL...
, behind the scene, ts-pattern provides runtime support for pattern match.
Document for typedraft can be found in typedraft-docs, examples of pattern match: draft-dsl-match, and it's well tested: Test cases as examples.
Have a try in dsl-match-demo! Any feedback is welcome.
Top comments (0)