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.
constjsonString="";constjsonValue=JSON.parse(jsonString)// const jsonValue: any ❌Enter fullscreen modeExit 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.