Git Product home page Git Product logo

Comments (3)

gcanti avatar gcanti commented on May 23, 2024

Relevant gcanti/fp-ts#18 (comment)

The gist is

Deserialisation

import * as t from 'io-ts'
import { pathReporterFailure } from 'io-ts/lib/reporters/default'
import { Option, none, some } from 'fp-ts/lib/Option'

// given a runtime type for T returns a runtime type for Option<T>
export function createOption<A>(type: t.Type<A | null | undefined>): t.Type<Option<A>> {
  return t.mapWithName(v => (v === null ? none : some(v)), type, `Option<${type.name}>`)
}

const Id = createOption(t.number)

const T = t.interface({
  id: Id
})

// helper for this demo
function validate<A>(value: any, type: t.Type<A>): A {
  return t.validate(value, type).fold(errors => {
    throw new Error(pathReporterFailure(errors).join('\n'))
  }, x => x)
}

console.log(validate('wrong', T)) // Invalid value "wrong" supplied to : { id: Option<number> }
console.log(validate({}, T)) // Invalid value undefined supplied to : { id: Option<number> }/id: Option<number>
console.log(validate({ id: 'wrong' }, T)) // Invalid value "wrong" supplied to : { id: Option<number> }/id: Option<number>
console.log(validate({ id: 1 }, T)) // { id: Some(1) }

Serialisation

By default you get this output

console.log(JSON.stringify({ id: some(1) })) // {"id":{"value":1,"_tag":"Some"}}

You can add your own serialization logic defining a toJSON method on Option.None / Option.Some (+ module augmentation)

// module augmentation
declare module 'fp-ts/lib/Option' {
  interface None<A> {
    toJSON(): A | null
  }
  interface Some<A> {
    toJSON(): A | null
  }
}

None.prototype.toJSON = () => null
Some.prototype.toJSON = function<A>(this: Some<A>): A {
  return this.value
}

console.log(JSON.stringify({ id: none })) // {"id":null}
console.log(JSON.stringify({ id: some(1) })) // {"id":1}

The following laws hold

serialize(deserialize(x)) ~ x
deserialize(serialize(x)) ~ x
console.log(validate(JSON.parse(JSON.stringify({ id: some(1) })), T)) // { id: Some(1) }

from io-ts.

vegansk avatar vegansk commented on May 23, 2024

Thanks, this is the better approach.

from io-ts.

gcanti avatar gcanti commented on May 23, 2024

Oops, a fix:

-export function createOption<A>(type: t.Type<A | null | undefined>): t.Type<Option<A>> {
+export function createOption<A>(type: t.Type<A>): t.Type<Option<A>> {
-  return t.mapWithName(v => (v === null ? none : some(v)), type, `Option<${type.name}>`)
+  return t.mapWithName(v => (v == null ? none : some(v)), t.union([type, t.undefined, t.null]), `Option<${type.name}>`)
}

from io-ts.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.