Typescript is a lifesaver when it comes to handling JSON arrays with optional properties. Its assistance is unparalleled

I am working with a typescript object that looks like this:

class myObj {
   public param1,
   public param2,
   public param3
}

In another object, I have an array of that same object

class otherObj {
   public arrayOfMyObj:myObj[]

   constructor(){
       this.arrayOfMyObj = [{param1: "value", param2: "value"}]
   }
}

However, when attempting to run this code, it throws an error because the first item in the JSON array does not exactly match myObj (it is missing param3). Could there be a way to make param3 optional or just skip checking for it altogether? Normally, I would create a new myObj and populate it accordingly. However, in this case, the JSON array is long and hard-coded.

Answer №1

Here is an example of how it might appear:

interface IMyObj {
   property1: string;
   property2: string;
   property3?: any;
}


class AnotherObject {
   public arrayofMyObjects: IMyObj[]

   constructor() {
       this.arrayOfMyObjects = [{ property1: "value", property2: "value" }]
   }
}

Note

All properties in a class are defaulted to public access.

It's recommended to specify variable types. Not specifying a type defaults to "any" which may lead to unexpected errors during type checking.

Answer №2

If you're looking for a solution, consider checking out this helpful answer

Another approach involves utilizing Object.assign to expand a valid typed object by adding only the necessary property (excluding properties a and c in this example)

export class A {
    a:number=1;
    b:number;
    c:string;
    d:string; }

let validA:A = Object.assign(new A(),{
    b:3,
    d:'Lorem ipsum' 
}); 

I personally find this syntax easier to work with as it simplifies object initialization and eliminates the need to create an interface for each model in my application.

Additionally, it's beneficial to set default values in your class definition, even if they are not required in every instance.

An important point to note is that class methods are retained using this method (unlike when casting to {}).

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

Extracting data from multiple web pages with R - An extensive collection of tables

Looking for assistance in extracting data from a website with multiple pages and importing it into R. Can anyone help me with this task? Website: ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

A guide to linking data retrieved from getJSON to state in ReactJS

After numerous attempts, I am still struggling to retrieve data from a JSON file and integrate it into my webpage using ReactJS <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8> <title>Demo Fetch</title ...

The Element is Unfamiliar - Application with Multiple Modules

I seem to be facing an issue with how my modules are structured, as I am unable to use shared components across different modules. Basically, I have a Core module and a Feature module. The Core module contains components that I want to share across multip ...

Using an object hierarchy in Typescript to create an if statement

Currently, I am attempting to create a logical statement using a hierarchy structure as shown below: if ((config.elementConfig.curve[0].dataset[0].splitBy = 'my discrete var')) {..... However, when implementing this statement, I encounter the er ...

extract information from a JavaScript array using regular expressions

After struggling for hours, I decided to seek assistance from the stackoverflow community. While I understand that regex could solve my problem, I lack the necessary expertise and time to learn before my deadline. The challenge lies in extracting the 6-di ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept. This is the route implementation: const router = new Router() router.get('/posts', getPosts) .get('/posts/:id', getPostsById) In the second route, I successfully retriev ...

Using JavaScript to divide an associative array into separate arrays

I am dealing with an array of clubs var clubs =[{ team: {name: "fcb barca", rank: 4}, team: {name: "man utd", rank: 16}, team: {name: "man city", rank: 36}, team: {name: "fcb liverpool", rank: 57} }]; The task at hand is to separate this ...

Ways to package object fields within an array

I am in possession of an object with various properties, ranging from arrays to objects. My goal is to transform the object so that each sub field is encapsulated within an array. For instance: "head": { "text": "Main title", "su ...

Unraveling the mystery of "??=" in Javascript/Typescript code

In a recent TypeScript code snippet, I came across the following: const arrayAA: Record< someSchema['propX'], typeof arrayBB > = {}; for (const varB of arrayBB) { (arrayAA[someStringValue] ??= []).push(varB) } What is ...

Jest came across a token from nestjs that it did not expect

I've hit a roadblock with running my end-to-end tests in Nest.js using Jest. Every time I attempt to execute my e2e test, an error keeps popping up Jest encountered an unexpected token Even though all other test suites ran smoothly, this particular ...

Unable to convert date data for display on D3 line graph

I am attempting to replicate a line graph similar to the one in the following fiddle link: http://jsfiddle.net/wRDXt/2/ In the example, the date is used as new Date(2013, 17, 1). The JSON data I have is structured as shown below, [{ "_id": "bb68d8a2 ...

Is there a way to troubleshoot and correct the Xpath in the Importjson function?

How can I extract a list of algorithms from a JSON response in Google Sheets using the IMPORTJSON command? IMPORTJSON("http://miningpoolhub.com/index.php?page=api&action=getminingandprofitsstatistics", "return/algo") After running the command, I rece ...

Deleting multiple rows in TypeORM with PostgreSQL and Node.js (using TypeScript)

Hey there, I'm looking for a way to efficiently erase rows in one go without having to run a loop. Can't seem to figure it out on my own, any assistance would be greatly appreciated. async remove(ids: DeleteEmployeeAnswerDTO): Promise<boolean& ...

Using Three.js to load blender JSON files

Hey there! I'm currently facing some challenges when it comes to importing models from Blender into three.js. Currently, I am using the latest version of three.js (R71). I have successfully installed the three.js exporter in Blender and it works fine ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

Exploring Json parsing in Python with Django

I am currently using Django for my web application. I am facing an issue where I cannot access Nodes and edges by calling decoded_data['nodes']. Instead, I am encountering the error message: 'NoneType' object is not subscriptable Thi ...

Utilize a vacant implementation of an interface

I have a simple interface called EmployerContact. I'm wondering how I can create an empty object, mockEmployerContact, of type EmployerContact and then assign values to its properties later on. Do I need to start with default values for this object? e ...

Using the Airbnb style guide in conjunction with NextJS

Incorporating the Airbnb style guide into my NextJS 13.4.9 project is a priority for me. When setting up a NextJS application, the prompt to enable ESLint arises. Opting to say "yes" is typically the recommended approach, as it allows for running npm run l ...