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.38k stars 57 forks source link

Discriminated union #85

Closed KhraksMamtsov closed 4 months ago

KhraksMamtsov commented 1 year ago

Add Mach.DiscriminatedUnion for matching over DU by common field

gvergnaud commented 1 year ago

Hey!

Isn't this already doable by combining Union.Map and Match?

import * as H from 'hotscript'

type AorB =
   | {
       type: "a";
       a: "aaa";
     }
   | {
       type: "b";
       b: 123;
     }
    | {
       type: "c";
       c: false;
     };

 type T0 = H.Pipe<AorB, [
//    ^?
    H.Unions.Map<
        H.Match<[
            H.Match.With<{ type: "a", a: H.arg0 }, H.Strings.Uppercase>,
            H.Match.With<{ type: "b", b: H.arg0 }, H.Numbers.Negate>,
            H.Match.With<{ type: "c", c: H.arg0 }, H.Identity>,
        ]>
    >   
 ]> // -123 | 'AAA' | false

Playground

KhraksMamtsov commented 1 year ago

Hi! I found several differences 1) Matching with Map + Match is not exaustive 2) It doesn't cover case from test 3) It is too verbouse

I think main difference: Map + Match manipulates Discrimination Union not as a single entity but as a just simple union