jacob-alford / schemata-ts

An all-inclusive schema engine featuring schemata inspired by io-ts and validators.js. Written for TypeScript with fp-ts
https://schemata.jacob-alford.dev/
MIT License
33 stars 1 forks source link

Question: How do I create an instance of a BigIntString? #297

Closed Industrial closed 10 months ago

Industrial commented 11 months ago

I have this in my Schema:

  minimumReward: S.BigIntFromString,

and get this error:

The types of 'input.minimumReward' are incompatible between these types.
    Type 'string' is not assignable to type 'BigIntString'.
      Type 'string' is not assignable to type 'Tagged<BigIntStringBrand>'.ts(2322)
jacob-alford commented 11 months ago

There are a few of ways to do this.

Most of the time for branded types I know to be valid values, for example, Int's, Floats, SafeDate's, etc I just use unsafeCoerce because there is no concern about getting it wrong. If the source of the type is unknown, i.e. from a network request then you should first .decode() from deriveTranscoder() or .is() from deriveGuard() / deriveInputGuard() to ensure that the type matches the expected type.

jacob-alford commented 11 months ago

Also, to clarify, casting and using unsafeCoerce should only be done when you write the value of the type yourself (or as an escape hatch when you're certain the type coming in is trustworthy).

If the value is coming from a somewhere else, you should lift the function into an Either type and use Transcoders to decode the value first. This will guarantee type safety. And alternatively you can use guard in this context for the same effect.

Industrial commented 10 months ago

Okay, thanks.