Error encountered while parsing JSON data due to data type inconsistency

I am currently working on converting JSON data called JsonData that includes time-series of parameters:

[
  [ timestamp1, [ [paramset1, ...], [paramset2, ...], ...] ],
  [ timestamp2, [ [paramset1, ...], [paramset2, ...], ...] ],
  ...
]

into a new structure called ParamPoint

export class ParamPoint{
    constructor(
        public tstamp: number,
        public paramSets: number[][]
    ){}
}

using the following code snippet:

let res = JsonData.map<ParamPoint>((p) => new ParamPoint(p[0], p[1]));

However, I encounter an error message:

error TS2345: Argument of type 'number | number[][]' is not assignable to parameter of type 'number'.
      Type 'number[][]' is not assignable to type 'number'.

I need clarification on what this error signifies and how it can be prevented.

Answer №1

Why not try this alternative approach:

let result = JsonData.map((point: any) => new ParamPoint(point[0], point[1])); 

Give it a shot!

Answer №2

Make sure to specify the type for your jsonData, like this example:

const jsonData: [number, number[][]][] = [
  [1, [[1, 3], [2, 9]]],
  [3, [[1, 7, 3], [2, 9]]],
]

Otherwise, TypeScript will assume that everything in jsonData is of type number | number[][] instead of [number, number[][]]

You can also cast them like this:

jsonData.map<ParamPoint>((p: [number, number[][]]) => new ParamPoint(p[0], p[1]))

Or even better:

jsonData.map<ParamPoint>(([a, b]: [number, number[][]]) => new ParamPoint(a, b))

Check out this Stackblitz example

Also, avoid naming variables with capital letters, as it can be confusing. Reserve capital letters for classes and types.

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

Tips for correctly specifying the types when developing a wrapper hook for useQuery

I've encountered some difficulties while migrating my current react project to typescript, specifically with the useQuery wrappers that are already established. During the migration process, I came across this specific file: import { UseQueryOptions, ...

Destructuring an array of strings for use as parameters

Hey guys, I'm working with an array of keys here Example 1: let keyArray = ['x', 'y', 'z'] I'm trying to find a way to use these keys as parameters without repeating them multiple times. Do you have any suggestions ...

Unlock the Power of Typescript: Using the Browser Console to Access Functions

Scenario Within the file ts/app.ts, the following function exists: function foo() { console.log('Hello Word'); } After successful compilation with Webpack, it generates a file named bundle.js. To load this file, use the following script tag ...

Ways to dynamically display or hide content in Angular 7

>when an English button is clicked, its corresponding div should be shown. If another button is clicked, its div should also show without closing the previous one. I want each div to close only when its respective button is clicked again. >Please not ...

The error message TS2322 in MUI v5 states that the property 'fullWidth' is not found in the type 'IntrinsicAttributes & { theme: Theme; } & { children?: ReactNode; }'

As a user of MUI v5, I have implemented a straightforward FormControl as seen below. It is important to note that the property fullWidth is supported according to the official documentation. import React, { PropsWithChildren } from 'react' import ...

Tips for transforming or changing Partial<T> into T

I have a variable named Partial<T> in my coding project. returnPartial(): Partial<T> {} proceed(param T) {} //<-- the provided input parameter will always be of type T in this function and cannot be changed let object = this.returnPartial( ...

Tips for combining HttpClient's Observables with paramMap to create a dynamically loading component

I am currently working with an HTTPClient 'get' method that returns a JSON array of objects. I also utilize a key from the route params to extract a single object from that array. One interesting aspect of this component is its dynamic nature, w ...

Beneath the Surface: Exploring Visual Studio with NPM and Typescript

Can you explain how Visual Studio (2015) interacts with external tools such as NPM and the Typescript compiler (tsc.exe)? I imagine that during the building of a solution or project, MSBuild is prompted to execute these additional tools. I'm curious a ...

Ensure that you are completely logged out of all browser tabs when one tab has been successfully logged out

Just started working with Angular 4 and have built an application with a login page and home page. Upon successful login, I navigate to the home page. I noticed that if my application is open in multiple tabs and I log out from one tab, clicking on any ot ...

Interacting between two occurrences of the identical Angular component

Within a Razor view, I include an angular component: <my-widget id="myWidget" isfullscreen="false" class="some-class"></my-widget> Upon clicking the 'Popup' button, a popup appears in an iframe and the s ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Angular and Webpack combined to output the build project to the specified output path

In the process of integrating my Angular client-side application with a server-side written in Spring, I am seeking a way to build the UI project and store it in the /target directory within the backend portion for easy installation using Maven. My uncer ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Using both Angular material design and Bootstrap together can provide a seamless

Is it feasible to integrate material design into an Angular app alongside bootstrap without any complications? I am aiming to leverage the grid system of twitter-bootstrap and incorporate the dialogues from material design... ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

Issue with installing angular CLI on Windows 10

Having trouble installing Angular CLI with npm on a Windows 10 system I've exhausted all possible solutions Attempted clearing the cache and re-running the installation command - npm install -g @angular/cli - but encountered new errors every tim ...

What is the best way to incorporate a component template into various modules or components?

I have developed a unique header that I wish to incorporate into various components. Here is an example of the code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: './heade ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

After I subscribe, why do the variables of my object become undefined?

Just starting out with Angular and using Angular9. I attempted to subscribe to an observable in the following code: I have a service that makes an HTTP request and returns an Observable. The subscription appears to be working fine. ngOnInit() { this.in ...