Tips for validating object fields in TypeScript using type guards

When handling data in my Typescript backend provided through an HTML form, I perform validations using type guards before writing to the database.

let myObject = { property: parseProperty(property) } 

The expected type for "property" is defined as:

interface PropertyType = { 
    Field1: string; 
    Field2: string; 
  } 

The property object undergoes validation with the following type guard:

const parseProperty = (property: unknown): PropertyType => {
  if (!property || !isPropertyEntry(property)) {
    throw new Error("Incorrect or missing property entry")
  }
  return property; 

A yet incomplete typeguard below is used to validate the fields of the property's objects.

const isPropertyEntry = (property : unknown): property is PropertyType => {
  if( !('Field1' in property) || !('Field2' in property) ) {    
    throw new Error("Incorrect or missing field/s in property");
  } 
  ...
  ...

}

TypeScript flags an error for the statements 'Field1' in property and 'Field2' in property:

Object is of type 'unknown'.ts(2571)

I am seeking guidance on how to properly validate the 'property' object and ensure that Field1 & Field2 exist and are of correct type.

Answer №1

It seems like you're not inclined to use a type guard here. If your intention is to raise an Error when the property is not of type PropertyType, then you may want to consider implementing an assertion function.

function assertIsPropertyEntry(property: any): asserts property is PropertyType {
  if (
    typeof property !== "object" 
    || !property 
    || !('Field1' in property) 
    || !('Field2' in property)
    || typeof property.Field1 !== "string"
    || typeof property.Field2 !== "string"
  ) {
    throw new Error("Incorrect or missing field/s in property");
  } 
}

const parseProperty = (property: unknown): PropertyType => {
  assertIsPropertyEntry(property)
  return property
}

Playground

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

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

What is the best approach for showcasing overflowing text in tables in a manner that is user-friendly?

I am seeking a solution for dynamically loading data in a table, where I want to wrap long text with ellipsis and display the full content elegantly on hover. Currently utilizing HTML and CSS for this purpose, I have encountered an issue. Even when the tex ...

How to Verify if the Second Tab has Fully Loaded in Selenium Testing

Our current automation process involves using selenium. In order to open 2 URLs simultaneously, we have implemented the following approach: I use driver.get to load the first URL, which includes built-in synchronization for page loading. For the second wi ...

Building an AngularJS Service with TypeScript that is Non-Singleton: A Step-by-Step Guide

I need help converting an AngularJS Typescript Service into a Non-Singleton. Can anyone provide guidance on how to achieve this? (Note: This is not the same as other questions that focus on achieving this in JS) I have included some simple pseudo code be ...

Is it advisable to use arrow functions for writing methods within Angular classes?

Although it is technically feasible to write class methods as ES2015 arrow functions in Angular, I have yet to witness anyone actually doing so. Consider this basic component: @Component({ selector: 'sample' }) export class SampleComponent { ...

What is the best way to change data to UTF-8 encoding using Node.js?

Working with node.js and express, I am retrieving data from MongoDB using Mongoose and sending it via res.send(data). However, I am experiencing issues with some requests where the encoding appears to be ANSI instead of utf-8 despite the header indicating ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Error: Trying to access the 'push' method of an undefined object of useHistory

import React from "react"; import { Route, Switch, HashRouter, useHistory } from "react-router-dom"; import Home from "../pages/home/HomeComponent"; import Splash from "../pages/splash/Splash"; import Education from ...

Retrieving data from PHP MySql Query and importing it into JavaScript

Currently, I am in the process of developing a count-up timer for one of our office dashboards that tracks the time since the last incident or reset. There is a page dedicated to allowing senior admins to input a new timestamp. This timestamp then gets up ...

Having trouble with the service connection in Stackblitz?

Objective: I am trying to establish a connection with the Data service in StackBlitz. Issue: Unfortunately, my attempts are not successful. Can anyone pinpoint what I am overlooking? Project Link: https://stackblitz.com/edit/angular-mpy6pr Many th ...

Tips on extracting variables from JMeter Selenium WebDriver

Currently, I am dealing with a token that is being returned in the body of a web page. WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[contains(@name,'RequestVerificationToken')]")).getText(); This token is what I need to extract: ...

Using Vercel for a Next.js Custom Directory Configuration

Seeking guidance on deploying Next.js with Vercel, I have made changes to the structure of my Next.js project: frontend (Current Directory for Next.js) node_modules next.config.js jsconfig.json package-lock.json package.json Contents of package.json scri ...

Is it possible for me to use AJAX to load content from a string? I am attempting to postpone the activation of certain HTML

I need help optimizing my HTML page that includes certain sections with large Javascript files and images, which are initially hidden. Even when set to "display: none," the browser still loads all the content. One solution could be moving those sections in ...

Tips on disregarding events within an html table

I have a see-through table with a width set to 100% that houses various HTML content. I am utilizing the table to properly center a particular element on the screen. However, the table is intercepting mouse events and preventing users from clicking on lin ...

Experiencing trouble with sending the JSON string to the server? The solution might be just a few simple steps away if you're

When using express js, I encountered a strange issue where the server was logging an empty object {} instead of the JSON string that I had sent. This is puzzling to me as I have experience working with other technologies like flask. Here is the code snipp ...

Encountering a problem with the syntax '[checked]= true' in Angular2

I am currently working on a system for managing orders within restaurants using an angular2 application. The code I have is as follows: <md-radio-group> <span *ngFor="let extIng of item.extra_ingredients;"> <md-radio-button *ngIf= ...

Works perfectly in Firefox, experiencing glitches in Chrome

After creating a page that utilizes a simple JSon table and JS/JQ to display data, I noticed a slight bug in Chrome when the files were separated into HTML, CSS, JS, and JSON components. The page works perfectly in both Chrome and FF when hosted together o ...

Leveraging Django template tags in JavaScript

Currently working on a project that does not have a slug field, and this value is created in the template using: {{ n.title|slugify }} I need to incorporate the slug into a jQuery function, but the variable always remains empty: $("select#model").click( ...

Retrieve the height and width of all images within a specified directory using PHP

I'm currently working on an image directory in PHP, and I require the height and width of images in PHP to be used in HTML. I attempted to use JavaScript but it didn't provide the accurate values for the image's height and width. Can you sug ...