const jsonString = '{ "title": "Title" }'
const jsonValue = JSON.parse(jsonString)
// { title: 'Title' } ✅
    Enter fullscreen mode
    Exit fullscreen mode

It may seems like a small issue, but guess what? Lots of developers forget to handle it properly!

Now, here's the interesting part...

In TypeScript, JSON.parse() doesn't have any specific type arguments. It just returns any. This means, it comes at the cost of losing the benefits of static typing and type safety.

const jsonString = "";
const jsonValue = JSON.parse(jsonString)
// const jsonValue: any ❌
    Enter fullscreen mode
    Exit fullscreen mode
const safeJsonParse = <T>(str: string) => {
  try {
    const jsonValue: T = JSON.parse(str);
    return jsonValue;
  } catch {
    return undefined;
// const safeJsonParse: <T>(str: string) => T | undefined ✅
    Enter fullscreen mode
    Exit fullscreen mode
const jsonString = '{ "title": "Title" }'
const jsonValue = safeJsonParse<JsonValue>(jsonString) || { "title": "" }
// const jsonValue: JsonValue ✅
    Enter fullscreen mode
    Exit fullscreen mode
          

I would have thought an empty string for jsonString would indicate an error somewhere else, and as such, it's a good thing for it to fail 'loudly'. That way, you can quickly see where the error is by looking at the error callstack in the browser dev tools - and then avoiding the parse for invalid JSON.

I get that you'd want the parsed object typed though, so great thinking on the safeJsonParse function.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2025.