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

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

Angular is detecting an incorrect value in the mask

Recently, I came across the library found at and decided to create a directive utilizing it. My TypeScript code snippet: initForm() { this.form = this.fb.group({ item_number: [this.service.lpu.item_number, Validators.required], ...

Revamping every Angular component

Looking for a shortcut to upgrade all my Angular components at once. When checking my Angular version with ng v globally in VS Code terminal, results differ between overall and project directory settings: https://i.stack.imgur.com/2iOJx.png https://i.st ...

Angular 6 Subscription Service Does Not Trigger Data Sharing Events

Is there a way to set a value in one component (Component A) and then receive that value in another component (Component B), even if these two components are not directly connected as parent and child? To tackle this issue, I decided to implement a Shared ...

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

The process of retrieving input field values from a table within an Angular reactive form

I am seeking a way to collect all input values found within the table rows inside a reactive form. Below is an explanation of my code. <form [formGroup]="productForm" (ngSubmit)="saveProduct($event)" novalidate> <mat-form-field appearance="outlin ...

Angular module cannot be located

While working on implementing a chat feature for my project using sockJS and STOMP, I encountered several challenges with installing these two libraries. Despite attempting various methods such as installation from index.html, npm install, and manual downl ...

Saving the authenticated user's information from Firebase (including first name, last name, gender, and more) directly to our database

I am utilizing firebase authentication for user registration and login. Upon registration/login, I aim to save additional user details (such as FirstName, LastName, Gender, etc.) in my database. Currently, I have a process in place to achieve this. Howeve ...

Tips for optimizing the performance of an Angular 2 website

I am currently developing a website in Angular 2 and have successfully completed one module which I uploaded to the demo path. However, when I tested it using Google Speed Test, it only received a speed score of 37 on desktop and 32 on mobile. Can anyone ...

An issue with the HTTP GET Request method is that it often sends "?" instead of "/"

I have a general method for interacting with my Swagger API: get<ReturnType>(url: string, params?: HttpParams): Observable<ReturnType> { return this.http.get<ReturnType>(environment.apiUrl + url, { params: params, }); } ...

Struggling with aligning mat-icon in the center using HTML and CSS?

My issue is that the mat-icon in my generated columns is not center aligned. What could be causing this? When using ngFor to generate my datatable columns dynamically, none of them align correctly. The mat-icon inside my DIV defaults to left alignment. ...

Ensure the cursor is continually grabbing while moving items within a list using the @angular/cdk/drag-drop functionality

I have an example on stackblitz where I am using @angular/cdk/drag-drop in my project. I am attempting to change the cursor to cursor:grabb and cursor:grabbing when the cursor is over an element and when I drag a picked element. Here is the CSS line I am ...

Continuously refreshing the information displayed in the Angular view that is linked to a function in the TypeScript file whenever a modification is identified

I am currently working on an ecommerce application using the MEAN stack. In order to make the app real-time, I have integrated pusher-js. To show the quantity of a specific item in the shopping cart, I have implemented a function in the ts file that loops ...

Extending Angular 2 functionality from a parent component

As a continuation of the discussion on Angular2 and class inheritance support here on SO, I have a question: Check out my plunckr example: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview Here is what I am attempting to achieve: I want to implement s ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

Typescript: object containing at least one property with the type T assigned

Is there a method to write the HasNumber interface in Typescript without receiving an error due to the fact that the HasNumberAndString interface includes a property that is not of type number? I am looking for a way to require the HasNumberAndString int ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface: import * as Bluebird from "bluebird"; import { Article } from '../../Domain/Article/Article'; export interface ITextParsingService { parsedArticle : Article; getText(uri : string) : B ...

A Guide to Effectively Managing Express API Responses in Angular 2

When I make an Express API call from my Angular 2 application, I receive a response in the following way. In my component: this.emailService.sendEmail(this.name, this.email, this.message) .subscribe( (res) => ...

Is there a way to reduce the version of npm in a nodejs project?

Despite many attempts made by others, I am still struggling to resolve this issue. I have experimented with the following: npm uninstall -g npm@<version> npm uninstall npm --save npm uninstall -g npm --save However, all my efforts have been unsuc ...