You can use dsl-match-demo as template project to get started quickly.
Examples
Data Structure
Support objects, arrays, tuples, Sets, Maps, and all primitive types.
Object
import{MatchDSL}from"draft-dsl-match";
typeVector1={x:number};
typeVector2={x:number;y:number};
typeVector3={
x:number;
y:number;
z:number;
};
typeVector=Vector1|Vector2|Vector3;
constvector:Vector={x:1};
constresult=Λ<string>("match")`${vectorasVector}
${{x:1,y:1,z:1}} -> ${"vector3"}
${{x:2,y:1}} -> ${"vector2"}
${{x:1}} -> ${"vector1"}
`;
console.log(result);// "vector1"
In this example, import { MatchDSL } from "draft-dsl-match" is necessary even MatchDSL is not used because Λ will be translated to MatchDSL.
Λ is unicode U+039B, it resembles caret and is used to introduce a new context where you can apply a DSL, and <string> is used to assert the output type.
"match" is the name of the DSL. You can customize it in typedraft.config.ts.
The syntax is straightforward, you put whatever you want to match in the first ${}, and the ${} at the left of -> is pattern you want to match, the ${} at the right is handler, putting values here implies () => { return <values>; }
It's hard to type Λ, thus we recommend that you can create code snippet in vscode so that you can type it in this way:
The snippet you may want to reuse:
{
"dsl":{
"scope":"javascript,typescript,typescriptreact",
"prefix":"dsl",
"body":["Λ('$1')` $2`"],
"description":"use dsl in typedraft"
}
}
Array
import{MatchDSL,String,__}from"draft-dsl-match";
typeInput={title:string;content:string}[];
letinput:Input=[
{title:"Hello world!",content:"I‘m a very interesting content"},
{title:"Bonjour!",content:"I‘m a very interesting content too"},
];
constresult=Λ("match")`${input}
${[{title:String,content:String}]} -> ${"a list of posts!"}
${__} -> ${"something else"}
`;
console.log(result);// "a list of posts!"
__ will match any value, and String is used to denote the String type.