gcanti / newtype-ts

Implementation of newtypes in TypeScript
https://gcanti.github.io/newtype-ts/
MIT License
582 stars 14 forks source link

Iso objects as function #28

Open mwisnicki opened 3 years ago

mwisnicki commented 3 years ago

Can you make Iso object extend Function (equivalent to wrap) so it can be used as a constructor of values, such that following computes?

interface EUR extends Newtype<{ readonly EUR: unique symbol }, number> {}
const EUR = iso<EUR>();

const myamount = EUR(0.85);

This looks nicer IMHO.

Proof of concept:

function isoF<S extends AnyNewtype>(): Iso<S, CarrierOf<S>> & ((x:CarrierOf<S>) => S) {
  const tmp = iso<S>();
  function wrap(x: CarrierOf<S>) {
    return tmp.wrap(x);
  }
  Object.assign(wrap, tmp);
  Object.setPrototypeOf(wrap, Object.getPrototypeOf(tmp));
  return wrap as any;
}
sadhu89 commented 1 year ago

This would be nice. Did you end up using this in production @mwisnicki?

george-wilson-rea commented 1 year ago

I would like if there were an easy way to generate a pair of wrap/unwrap functions rather than this combined iso construct. I understand that these two functions witness an isomorphism, but I think it increases the barrier of adoption for newtypes. I think it's reasonable to want to use newtypes without also bringing in optics. Newtypes are far simpler and I consider them some of the "low-hanging fruit" of the modern FP style.