Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 2135

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T02:37:08+00:00 2024-11-26T02:37:08+00:00

Type-safe JSON.parse() with joi

  • 61k

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.

discussshowdevtypescriptwebdev
  • 0 0 Answers
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.