When creating a Line chart in TypeScript of type time, values for the x-axis cannot be strings

I'm currently utilizing chart.js along with these libraries/versions in my Vite/React TypeScript project:

  • chart.js: 4.3.0
  • react-chartjs-2: 5.2.0
  • chartjs-adapter-date-fns: 3.0.0
  • chartjs-plugin-datalabels: 2.2.0

I'm facing a dilemma as I aim to use a Line chart with a "time" type, where the datasets' x values are strings (formatted dates) and the datasets' y values are numbers.

I made sure to be clear in how I declared the datasets:

const data: ChartData<"line", StatPointDto[]> = {
        datasets: [
            {
                ...
                data: props.data.ios,
                ...
            },
            {
                ...
                data: props.data.android,
                ...
            },
        ] as ChartDataset<"line", StatPointDto[]>[],
    };

props.data.ios and props.data.android are both StatPointDto[].

The StatPointDto class, which I utilize in my project, is structured as follows:

export class StatPointDto {
    public x: string;
    public y: number;

    constructor(x: string, y: number) {
        this.x = x;
        this.y = y;
    }
}

This is how I've defined my chart, straightforwardly:

<Line
    data={chartData}
    options={chartOptions}
/>

However, with this ChartData arrangement, I encounter a TypeScript type mismatch error:

Types of property 'data' are incompatible.
Type 'StatPointDto[]' is not assignable to type '(number | Point | null)[]'.
Type 'StatPointDto' is not assignable to type 'number | Point | null'.
Type 'StatPointDto' is not assignable to type 'Point'.
Types of property 'x' are incompatible.
Type 'string' is not assignable to type 'number'.

Upon inspection, it appears that Chart.js expects my dataset elements to be either numbers, Points, or nulls. The Chart.js Point definition features x and y as numbers, but as this is a time series, my x values are strings, which leads to the issue.

How can I properly pass my points data with x values as strings (dates) and y values as numbers, without running into TypeScript errors?

Note: this should be supported, as per https://www.chartjs.org/docs/latest/general/data-structures.html#typescript

Thank you in advance!

Answer №1

Oops, the issue wasn't where I thought it was. It turns out the problem stemmed from a different source, specifically within the declaration involving the React useState hook:

const [chartData, setChartData] = useState<ChartData<"line">>({
    datasets: [],
});

There was a missing piece in this code snippet, leading to a mismatch in types within my project. To resolve this, I made the following correction:

const [chartData, setChartData] = useState<ChartData<"line", StatPointDto[]>>({
    datasets: [],
});

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 dynamically insert values into a JSON object?

I'm currently working with a JSON object in Angular and I need to dynamically add values that the user enters. Despite searching extensively, I haven't found a straightforward method to achieve this. I simply want to understand how to append key- ...

Issue with Angular 2 Custom Pipe not Refreshing Unless Object is Saved

I recently created a custom Angular 2 pipe that formats a phone number from a 10-digit string to 'XXX-XXX-XXXX'. The pipe is functioning perfectly, but the issue arises when it fails to update in real-time during keypress; instead, it updates onl ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

Repeatedly view the identical file on HTML

I'm currently working with the following HTML code: <input type="file" style="display: none" #file(change)="processImage($event)" /> <button type="button" class="btn" (click)="file.click()" Browse </button> When I select image1 fr ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

The process of sorting through an array of objects based on their specific types in TypeScript

I am working on a function that filters an array of objects based on their type property: export const retrieveLayoutChangeActions = (data: GetOperations['included']) => data.filter(d => d.type === 'layoutChangeAction') as Layou ...

What is the best way to include a non-data custom attribute in a TSX template without any value?

Currently, I am working on a React component with Typescript. The initial code looks like this.... const NameFormatter = React.createClass({ render() { return ( <div> <div className="dataset-name"> ...

Incorporating ngrx/Store into a current Angular application

Currently, I am working on an Angular 7 project that consists of numerous components communicating with an API to update data. The constant refreshing of the data using setTimeout has made it quite overwhelming as all the components are pulling data from t ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

What is the best way to send an object to an Angular form?

I am facing an issue with my Spring entity, Agent, which includes an Agency object. When adding a new agent, I need to pass the agency as an object in the Angular form. While the backend code is functioning correctly, I am struggling to figure out how to p ...

Develop a customized interface for exporting styled components

I am struggling to figure out how to export an interface that includes both the built-in Styled Components props (such as as) and my custom properties. Scenario I have created a styled component named CustomTypography which allows for adding typographic s ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

The element in the iterator in next.js typescript is lacking a necessary "key" prop

Welcome to my portfolio web application! I have created various components, but I am facing an issue when running 'npm run build'. The error message indicates that a "key" prop is missing for an element in the iterator. I tried adding it, but the ...

The initial rendering of components is not displayed by Vue Storybook

The functionality of the storybook is effective, but initially, it fails to "render" the component. By examining the screenshot, we can deduce that the component-template is being utilized in some way, as otherwise, the basic layout of the component would ...

What exactly does the use of type assertion as any in Typescript entail?

I'm attempting to dissect a portion of code and figure out its functionality. While I've encountered type assertion before, this particular example is proving to be quite baffling for me. (this.whatever as any).something([]); Here's the la ...

Building Dynamic Properties in TypeScript

I have developed a data entry application that utilizes the DataGrid component from DevExpress (devextreme) to allow users to add and remove columns, excluding the key column. The column configuration and user data are both stored in an SQL database. Here ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...

Execute the unknown function parameter

Trying to figure out how to convert an argument into an anonymous function, but struggling to find clear instructions. I know how to cast on variable assignment, but unsure if it's possible and how. Working with lodash where the typings specify the a ...

Tips on setting a value to zero in Angular when there is no input

Is there a way to organize the data and show the PRN entries based on the date, for instance, when the month is January? If there is data for machine 1 with assetCode: PRN, it should be displayed under the header for children. Similarly, if there is data f ...

Is it possible to use static imports with Typescript?

Let's imagine that Object is a module that can be imported and currently we are using Object.getOwnPropertyNames. Is it possible to write the following code instead: import {getOwnPropertyNames} from 'Object'; ...