swan-io / boxed

Essential building-blocks for functional & safe TypeScript code
https://swan-io.github.io/boxed
MIT License
689 stars 23 forks source link

`Result` parsing from interface compatible object #71

Closed github-christophe-oudar closed 6 months ago

github-christophe-oudar commented 7 months ago

Hello,

I've been using boxed for API result validation using BlitzJS and I'm using a small helper as the class is obviously not transferred from backend to frontend through the "magic" link they introduce based on react queries. Therefore to be able to access Result methods, I need to recreate them. To do so, I use:

import { Result } from "@swan-io/boxed"

// util for result from swan-io/boxed
export function dictToResult<T1, T2>(
  d: { tag: "Ok"; value: T1 } | { tag: "Error"; error: T2 },
): Result<T1, T2> {
  if (d.tag === "Ok") {
    return Result.Ok(d.value)
  } else {
    return Result.Error(d.error)
  }
}

It might not be optimal (I'm not a Typescript expert) but it works. I guess it could be useful to have a similar function added as static function to the Result object (like the typeguards etc) to make is accessible to more lib users.

It might be also safer for me as I bumped from 1.X to 2.X and saw that it moved the value to error field 🤫

bloodyowl commented 7 months ago

hi! long time no see 😄

adding https://github.com/swan-io/boxed/pull/72, will add those to the docs later this week

github-christophe-oudar commented 7 months ago

Haha yep it's been a while since meatspace 😅! Say hi to Alix 🙃

I think it should work 👍 I might need to check how to force to use a specific JSON serializer for the framework magic but it looks like the __boxed_type__ metadata field is not mandatory if I plan to use Result.fromJSON at read time 👌

bloodyowl commented 6 months ago

the __boxed_type__ has been removed from the fromJSON/toJSON logic (replaced with a non-iterable symbol), available in 2.2.0!