Grass logo

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/

Hi!

I'm Lars. I write about building scalable systems, software architecture, and programming.

I created Turfemon to be my playground. A place where I can dive into technical topics, share quick insights, and document my learning journey, without contaminating my main site's pristine collection of 'profound' insights.

Working on something exciting? Send me an email: show email