diff --git a/examples/colors.ts b/examples/colors.ts index 4879840..64d2946 100644 --- a/examples/colors.ts +++ b/examples/colors.ts @@ -11,13 +11,13 @@ const red = pack("Red", 128) //=> const red: Enum const green = pack("Green", 128) //=> const green: Enum const blue = pack("Blue", 128) //=> const blue: Enum -function toRGB(color: Enum) { // returns number[] - match(color, { - Rgb: (x) => x, //=> (property) Rgb: (x: [number, number, number]) => [number, number, number] +function toRGB(color: Colors) { // returns number[] + const a = match(color, { + Rgb: (x) => x, //=> _: (x) => x //=> - }); + }); //=> - return match(color, { + const b = match(color, { Red: (x) => [x, 0, 0], //=> (property) Red: (x: number) => number[] Green: (x) => [0, x, 0], //=> (property) Green: (x: number) => number[] Blue: (x) => [0, 0, x], //=> (property) Blue: (x: number) => number[] diff --git a/src/enum.ts b/src/enum.ts index 58014df..544311c 100644 --- a/src/enum.ts +++ b/src/enum.ts @@ -20,13 +20,43 @@ type PartialArms = { }; // this is the recommended way to create enum instances so you have strong type checking -export const pack = (...entry: EnumChecked) => entry satisfies EnumChecked; +export function pack(...entry: Enum) { + return entry as E // this is disgusting and we are completely just lying to tsc and the user and it works +} -export const match = >( - pattern: Enum, +export function match>( + pattern: E, arms: Fn, -): ReturnType => +): ReturnType { // ^ typescript ABSOLUTELY FREAKS OUT about this BUT it does work so ¯\_(ツ)_/¯ // biome-ignore lint/suspicious/noExplicitAny: return type is handled externally - ((arms[pattern[0]] as any) || (arms as any)._)(pattern[1] as any);; // <- dunno why there are two semicolons here -// typescript REALLY hates this (hence all the `any`) and I really can't blame it \ No newline at end of file + return ((arms[pattern[0]] as any) || (arms as any)._)(pattern[1] as any) as ReturnType; + // typescript REALLY hates this (hence all the `any`) and I really can't blame it +} + +type Color = { + Red: number; + Blue: number; + Green: number; + Rgb: [number, number, number]; +}; + +const red = pack("Red", 128) //=> const red: Enum +const green = pack("Green", 128) //=> const green: Enum +const blue = pack("Blue", 128) //=> const blue: Enum + +function toRGB(color: Color) { // returns number[] + const a = match(color, { + Rgb: (x) => x, //=> + _: (x) => x //=> + }); //=> + + const b = match(color, { + Red: (x) => [x, 0, 0], //=> + Green: (x) => [0, x, 0], //=> + Blue: (x) => [0, 0, x], //=> + Rgb: (x) => x //=> + }); +} + +console.log(toRGB(blue)); // [ 0, 0, 128 ] \ No newline at end of file