Type-safe JSON.parse() with joi

armenhalajyan

armenhalajyan

Posted on December 7, 2021

Type-safe JSON.parse() with joi

As developers, we often interact with APIs and databases that return a response in JSON format. To parse that JSON response we have to reach for the JSON.parse() method.
By default, JSON.parse() will return the object with type any. This means that we can simply declare the type of our object inline, like this:

interface MyObject {
    key1: string;
    key2?: number;
    key3: boolean;
}

const jsonString = api.get()

const myObject: MyObject = JSON.parse(jsonString)
Enter fullscreen mode Exit fullscreen mode

This would be sufficient if we were absolutely sure that jsonString is assignable to type MyObject. However, if for any reason the API sends us a different response, Typescript will not prevent us from misusing that response and potentially getting runtime errors.

To address this issue we can use a runtime data validator such as joi:

import { ObjectSchema, ValidationError } from 'joi';

export const typedParse = <TSchema>(
    jsonString: string,
    schema: ObjectSchema<TSchema>
): TSchema => {
    const {
        value,
        error,
        warning,
    }: { value: TSchema; error?: ValidationError; warning?: unknown } =
        schema.validate(JSON.parse(jsonString));
    // handle error and warning cases as needed
    if (error) throw error;
    if (warning) console.log(warning);
    return value;
}; 
Enter fullscreen mode Exit fullscreen mode

Now we can import and use this reusable function anywhere we use JSON.parse() by providing the JSON string and the corresponding joi schema:

import Joi from 'joi'
import { typedParse } from './util/typedParse.ts'

interface MyObject {
    key1: string;
    key2?: number;
    key3: boolean;
}

const jsonString = api.get()

const schema = Joi.object<MyObject>()
    .keys({
        key1: Joi.string().required(),
        key2: Joi.number().integer(),
        key3: Joi.boolean()
    })
    .required()

const myObject = typedParse(jsonString, schema)
Enter fullscreen mode Exit fullscreen mode

This allows us to take advantage of all the type safety and autocompletion that Typescript offers when the API request matches what we expect, and at the same time prevents unexpected behavior when the API returns a different response.

💖 💪 🙅 🚩
armenhalajyan
armenhalajyan

Posted on December 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Type-safe JSON.parse() with joi
typescript Type-safe JSON.parse() with joi

December 7, 2021