funtypes icon indicating copy to clipboard operation
funtypes copied to clipboard

Codec Type

Open ForbesLindesay opened this issue 5 years ago • 2 comments

The types in io-ts are actually "Codecs": https://github.com/gcanti/io-ts/blob/master/index.md#the-idea

What this means is that they support having different runtime types on the "serialized" end (where they are typically of type unknown in TypeScript) and the "parsed" end. This can be useful for:

  • Converting data to and from a more compressed format (e.g. {objectWithLongKeys: number} could become a tuple [number] when serialized)
  • Handling types that don't have a direct representation in JSON (e.g. serializing and parsing Date objects)
  • Upgrading old formats (e.g. you might support {version: 1, size: number} | {version: 2, width: number, height: number} but only want to deal with version 2 in your app)

We're actually in a pretty good place to support this. Our primative Runtype has a validate method with the perfect signature to act as parse.

Requested in https://github.com/pelotom/runtypes/issues/56

ForbesLindesay avatar Sep 06 '20 15:09 ForbesLindesay

Draft implementation: #17

ForbesLindesay avatar Sep 09 '20 02:09 ForbesLindesay

A side effect of this change is that we are also effectively deep cloning everything, which takes care of https://github.com/pelotom/runtypes/issues/132 and https://github.com/pelotom/runtypes/issues/24 (remove unknown keys from validated object). It may be worth looking into supporting a fast path that doesn't clone objects if none of the validations change anything.

ForbesLindesay avatar Sep 11 '20 03:09 ForbesLindesay