Tips for checking the type of a string against an object type following JSON parsing

I have defined two types:

export type Ping = {
  kind: 'ping',
  lag?: number
}

export type Message = {
  kind: 'message',
  value: string
}

I am receiving a JSON encoded incoming message string:

let msg = "{kind:'message', value: 3 }",
    ping = "{kind:'ping'}";

Once I parse this string into an object:

let obj = JSON.parse(msg);

I need to validate these messages to ensure they contain the expected properties and then dispatch them accordingly:

export function isMessage(_: any): _ is Message {
  if (typeof _ === 'object') {
    let res = (_ as Message);
    if (res.kind === 'message' && res.value && typeof res.value === 'string') {
      return true;
    }
  }
  return false;
}


export function use(_: any) {
  if (isMessage(_)) {
    console.log('Message: ', _.value);
  }
}

Do I need to manually check every field of each message type like shown above, or is there a simpler method for achieving this?

Answer №1

To simplify the process and ensure cleanliness, consider creating a JSON Schema for your data and validating it using a tool like ajv. Below is an example of how you can validate a Message type:

import Ajv, { JSONSchemaType } from 'ajv';
const ajv = new Ajv();

export interface Message {
  kind: 'message',
  value: string
}

const messageSchema: JSONSchemaType<Message> = {
  type: 'object',
  properties: {
    kind: { type: 'string', const: 'message' },
    value: { type: 'string' }
  },
  required: ['kind', 'value'],
  additionalProperties: false
};

const isMessage = ajv.compile(messageSchema);
export { isMessage };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Potential issue detected in TypeScript relating to the JQuery.html() method

For example: let $div = $("div"); let $p = $("p"); $div.html($p); This is producing the following error message: Supplied parameters do not match any signature of call target. UPDATE: In plain JavaScript/jQuery, the code is working. An equivalent (in f ...

Assigning a unique global variable to every individual row of a parsed JSON dataset

To automate daily reporting, I use an API to retrieve data each day and then transfer this data into a Google sheet. This process runs automatically every day, fetching data from the previous day. The existing code successfully pulls the data and enters i ...

Export CSV file using Angular 5

Currently, I am seeking a solution to generate a CSV file from data in an array and allow the user to download it by simply pushing a button. Which method requires minimal effort and is most suitable for Angular 5? After some research, I came across this ...

Processing each item in a JSON Array one at a time

I found myself in possession of a JSON array that looks like this: [ { "stats": { "callQuality": 5, "audioRecvRemoteMute": false, "audioRecvLocalMute": true, }, "rtpStatsList": [ { "media": 1, "directi ...

Is there a way to dynamically import a JSON file within an ECMAScript module?

Currently, I am attempting the following in my code: let filePath = '../../data/my-file.json' import inputArray from filePath assert { type: 'json' } The outcome of this operation is as follows: file:///.../script.mjs:5 import inputArr ...

Using JSON to transfer inherited objects to a WCF service

In my codebase, I have defined two classes as shown below public Class Vehicle { int wheels { get ; set} } public Class Car:Vehicle { int topspeed { get; set ;} } //This is the container class public Class Message { string ConatinerName { get ...

Ways to dynamically update button properties in Angular 2

Customized Template, <div *ngFor="let item of items" class = "col-sm-12 nopadding"> <a class="button buttonaquacss button-mini button-aqua text-right pull-right" [ngClass]="{activec: isActive}" (click)='updateStatus(item)& ...

What is the best way to iterate through states within an array using React?

Can someone help me create a button that can cycle through different states in the given array? I want the button to change State_1 to State_2, State_2 to State_3, and then back to State_1 for each object. I'm struggling to figure out how to cycle thr ...

Example URL for JSON web service

Currently, I'm in the process of creating an image gallery with jquery and html5. I'm focusing on the frontend development aspect. Does anyone have recommendations for a json webservice that can provide json objects containing imageURLs? Thank y ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Tips for transforming a JSON object into a JavaScript array, and specifically filtering it based on a key

I am receiving a JSON object through an Ajax request with the following keys and values: [{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}] I want to convert this object into a JavaScript array where each App_Name and ID value is c ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Exploring Angular Testing with SpyOn

Apologies for my inexperience with Angular, but I am struggling with using spyOn in a unit test. In my unit test, there is a method on the component that calls service1, which in turn calls another service2. However, when I try to spyOn service1 in order ...

Sending back an error message in JSON format using the IActionResult method

I've created an API controller endpoint that looks something like this: public IHttpActionResult AddItem([FromUri] string name) { try { // call method return this.Ok(); } catch (MyException1 e) { return thi ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

The angular2 error message indicating a property cannot be read if it is

Encountering an issue trying to utilize a method within an angular2 component. Here's the code snippet : import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AgGridModule } from &ap ...

Updating a particular attribute within a JSON object in a JSON Array using MySQL

Currently, my MySQL database includes a table with a JSON column that stores data as shown below: [{"id": 1, "value": 23.4}, {"id": 2, "value": 54.3}, {"id": 3, "value": 4.33}] I am looking to update the value property of all objects in this colum ...

The Codeception method for checking JSON types in responses is not effectively validating fields

Having trouble with API test public function loginAsRegisteredUser(\ApiTester $I) { $I->wantTo('Login as registered user'); $I->sendPOST('/action.php?ap=V4&p=Customer&c=Customer&a=login',['customer&a ...

Calculate the total values across a row of a work schedule, based on specific conditions

I am facing a challenge with my work schedule data, as it is laid out horizontally. I am trying to calculate the total hours in the schedule based on various criteria such as the person's name, their available hours, shift, and the machine they are as ...