Exploring the intersection between TypeScript, Ethereum, GraphQL, and other exciting technologies.

Typesafe function for Serializing JSON in TypeScript

22nd Apr 2022

JavaScript has this property that you can use JSON.parse(JSON.stringify(obj)) to deeply clone an object.

The problem is that some data types, like dates, will be converted into strings and not survive the transition.

To solve this we can use this Jsonify function:

type Jsonify<T> = T extends {toJSON(): infer U}
  ? U
  : T extends object
  ? {
      [k in keyof T]: Jsonify<T[k]>;
  : T;

You can pass any type into this type and it will output the type you would have gotten if you took it through JSON.parse(JSON.stringify(obj)).

Hope that was helpful :)

Read more: https://effectivetypescript.com/2020/04/09/jsonify/