Ensure thorough validation of the JSON.parsed data in TypeScript

Currently, I am developing a small module for Angular and I have encountered an issue regarding the condition where I verify my JSON.parsed data.

read(): Position|null {
    try {
        ...
        let parsedData  = JSON.parse(data);
        if (parsedData && parsedData.x && parsedData.y)
            return new Position(parsedData.x, parsedData.y);
    } catch (e) {
        ...
    }
    return null;
}

I find this solution to be suboptimal as it would require me to check for each property if there are more properties in the object that I had previously stringified. Additionally, I am unsure about how to handle cases when the parsed data is null. Are there any alternative solutions for validating the stringified data? Thank you

Answer №1

To transform your json output into a Position instance, all you need to do is cast it in the following manner:

read(): Position|null {
    try {
        return JSON.parse(data) as Position;
    } catch (e) {
        return null;
    }
}

Nevertheless, casting alone does not validate the data structure. It does not verify if the json contains the expected fields of the Position object. To ensure this, manual validation of each field is necessary.

An approach to achieve this could involve maintaining a list of properties within the class and then checking for their existence post-casting:

class Position {
    public x: Number;
    public y: Number;
    public someOtherField: string;
    
    public static PropertyNames: string[] = ["x", "y", "someOtherField"];
    public static isValid(pos: Position): Boolean {
        return Position.PropertyNames.every((i) => pos && pos.hasOwnProperty(i));
    }
}

let obj = new Position();
alert(Position.isValid(obj)); //false

obj.x = null;
obj.y = null;
obj.someOtherField = null;

alert(Position.isValid(obj)); //true

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

Steps for ensuring a prop is required in TypeScript React based on a condition

interface IPerson { name: string; gender: string; vaccinated: 'yes'|'no'; vaccineName?: string } In this interface, the property vaccineName is optional while other properties are required. If the property vaccinated is yes ...

Retrieving Response Status Codes with Angular 4 and Express

When making GET requests to an Express REST API, I am setting res.status to 200 and returning data. However, in Angular, the response contains the data, but response.status always returns undefined. [UPDATE START] After trying Martin Adámek's sugge ...

Firebase login success callback not getting invoked

I have set up routes, the AuthGuard, and Firebase login in my project. I am using callbacks to handle the success and failure of the Firebase login process. successCallback(signInSuccessData) { console.log("Received with Success!"); } errorCallback(e ...

Find out if all attributes of the object are identical

I am trying to create the boolean variable hasMultipleCoverageLines in order to determine whether there are multiple unique values for coverageLineName within the coverageLines items. Is there a more efficient way to write this logic without explicitly c ...

Steps to validate the execution of the ngCopy function in an Angular 6 unit test

While working on one of my angular components, I have implemented the ngCopy module to enable text copying to clipboard. The code snippet below showcases how I have used this module: import {Component, Input, OnInit} from '@angular/core'; import ...

Why is interpolation not allowed in Angular 2 for binding to my child component?

If I plan on assigning the 'src' attribute of an 'image' tag, I have the option to use either <img src='{{heroImageUrl}}'> or <img [src]='heroImageUrl'> However, when dealing with a child component us ...

What is the recommended TypeScript type to be returned from a GraphQL resolver when using ESLint?

Repository Link https://github.com/inspiraller/apollo-typescript The code is functioning correctly, however, Eslint typescript is raising complaints. An eslint error occurs on the following code block: Query: { players: () => players } Miss ...

How to outsmart the TypeScript compiler when integrating a library without type definitions?

Is there a way to deceive the compiler into thinking that certain definitions are being used? My constructor contains: nv.addGraph(()=> {...}) Before my class declaration, I include: public nv:nv; In my model file, I define: export interface nv{ ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

Tips on streamlining two similar TypeScript interfaces with distinct key names

Presented here are two different formats for the same interface: a JSON format with keys separated by low dash, and a JavaScript camelCase format: JSON format: interface MyJsonInterface { key_one: string; key_two: number; } interface MyInterface { ...

How can I transfer the document id from Angular Firestore to a different component?

I'm seeking assistance on how to achieve a specific task related to pulling data from Firestore in my Angular application and displaying it in a list. Everything is working smoothly, including retrieving the document ID. My goal is to have the retrie ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

Typescript error: Cannot assign type to argument

Exploring the world of typescript (2.5.2) and looking for clarity on why the first call works but the second one encounters an error: function printPerson(person: {firstName: string; lastName: string}): void{ console.log(person.firstName + " " + per ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...