DEV Community

mistlog
mistlog

Posted on

2

TypeDraft: Use Pattern Match DSL

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)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay