Typing JSON.stringify / parse in TypeScript
Often we need to pass around stringified objects in TypeScript but they are boxed into a string type and we lose their original type. Wouldn’t it be cool if we could keep it.
Simply create the following file in your project and when you use JSON.stringify
it will return a Stringified<T> which will preserve the original type for you when you call JSON.parse
again.
It works by extending the String type and adding a private __stringified: T
field, only TypeScript can see this (it won’t appear in intellisense) and is not set at runtime but the private field enables T
to be inferred again when we re-parse it.