gvergnaud / hotscript

A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know.
3.52k stars 58 forks source link

feat(match): Add pattern matching with destructuring #45

Closed gvergnaud closed 1 year ago

gvergnaud commented 1 year ago
type MatchTest<T> = Eval<
      Match<
        T,
        [
          Match.With<
            { nested: { value: Match.arg0 } },
            Strings.Prepend<"nested.value === ">
          >,
          Match.With<{ x: Match.arg0; y: Match.arg1 }, Numbers.Add>,
          Match.With<
            { x: { y: [1, 2, Match.arg0] } },
            Strings.Prepend<"x.y[2] === ">
          >,
          Match.With<string, Strings.Prepend<"string: ">>,
          Match.With<any, Functions.Constant<"default value">>
        ]
      >
    >;

    type res1 = MatchTest<{ nested: { value: 123 } }>;
    //   ^? "nested.value === 123"
    type res2 = MatchTest<"world">;
    //   ^? "string: world"
    type res3 = MatchTest<1>;
    //   ^? "default value"
    type res4 = MatchTest<{ x: 1; y: 2 }>;
    //   ^? 3
    type res5 = MatchTest<{ x: { y: [1, 2, 3] } }>;
    //   ^? "x.y[2] === 3"

type Transform<xs extends any[]> = Eval<
  Tuples.Map<
    Match<
      [
        Match.With<string, Strings.Replace<"0", "1">>,
        Match.With<number, Numbers.Add<1>>,
        Match.With<boolean, Booleans.Not>
      ]
    >,
    xs
  >
>;

type res1 = Transform<[1, 2, "101", true]>;
//    ^? [2, 3, "111", false]