Is there a way to parse strings as JSON in Typescript.
Example: In JS, we can use JSON.parse(). Is there a similar function in Typescript?
I have a
JSON.parseYou can continue to use JSON.parse, as TS is a JS superset. There is still a problem left: JSON.parse returns any, which undermines type safety. Here are two options for stronger types:
Custom type guards are the simplest solution and often sufficient for external data validation:
// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }
// Validate this value with a custom type guard
function isMyType(o: any): o is MyType {
return "name" in o && "description" in o
}
A JSON.parse wrapper can then take a type guard as input and return the parsed, typed value:
const safeJsonParse = (guard: (o: any) => o is T) => (text: string): ParseResult => {
const parsed = JSON.parse(text)
return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
}
type ParseResult =
| { parsed: T; hasError: false; error?: undefined }
| { parsed?: undefined; hasError: true; error?: unknown }
Usage example:
const json = '{ "name": "Foo", "description": "Bar" }';
const result = safeJsonParse(isMyType)(json) // result: ParseResult
if (result.hasError) {
console.log("error :/") // further error handling here
} else {
console.log(result.parsed.description) // result.parsed now has type `MyType`
}
safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.
Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):
io-tsajv