1

I want to create a scatter plot in an Angular application using plot.ly .

All the examples on line use non-typed objects, like so:

var trace = {
    x: [1, 2, 3],
    y: [4, 5, 6],
    . . .
}

I can do that, but since I'm using TypeScript, I want to use the types defined in @types/plotly.js . One of them is ScatterData, which is defined as follows (I removed most of the fields, for brevity):

export type Data = Partial<ScatterData>;

export interface ScatterData {
    type: 'bar' | 'scatter' | 'scattergl' | 'scatter3d';
    x: Datum[] | Datum[][];
    y: Datum[] | Datum[][];
    z: Datum[] | Datum[][] | Datum[][][];
    xaxis: string;
    yaxis: string;
    ...
}

Here is something I'm trying to do that fails:

const data: Plotly.Data = {
    type: 'scatter',
    x: [],
    y: [],
};

data.x.push(12);

I get an error on the call to push, TS2349: Cannot invoke an expression whose type lacks a call signature. Trying to place at type guard

if(data.x instanceof Ploty.Datum[]) ...

fails because it says the property Datum does not exist.

I can make everything work by not specifying Plotly.Data, but it's really something I want to resort to.

1 Answer 1

1

That compile error is a bit odd, but I think the issue is that the data.x property is typed to Datum[] | Datum[][], which means it has two different call signatures: push(Datum) and push(Datum[]). Without an assertion or type-guard somewhere, the compiler can't verify that push(12) is correct. If you add an assertion it should work:

(data.x as Plotly.Datum[]).push(12);

Something else to point out, even if you don't annotate data as Plotly.Data, if you assign data to something which is typed to Plotly.Data then the type-checker will make sure it's correct. The only down-side is that you won't get IDE type suggestions when you build your data object, but you'll get compile errors if you build it incorrectly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.