Typing JSON.stringify / parse in TypeScript

Jake Ginnivan
1 min readOct 4, 2019

--

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.

@types/index.d.ts

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 Tto be inferred again when we re-parse it.

--

--

Jake Ginnivan
Jake Ginnivan

Written by Jake Ginnivan

Co-Founder featureboard.app | Principal Consultant arkahna.io | Previously Tech Lead Seven West Media WA | International Speaker | OSS | Mentor

No responses yet