Issue
I am using TypeScript, React and Plotly in my project and would like to know if it is possible to pass the plot type specification using a variable. Something like this (which is not a working code example and only used to indicate what I mean)
import Plot from 'react-plotly.js';
var plotType: string = 'bar';
return (
<Plot
data={[{
x: [1,2,3,4],
y: [1,2,3,4],
type: 'bar' // this works
type: plotType // this doesn't
}]}
/>
);
It's not really an issue since I go about the whole 'data' thing using a state property, but I still don't get why it works with the literal string but not with a variable.
The error is something like 'string' cannot be assigned since '"bar"|"scatter"|"line" ...' is expected.
For a working example I can only refer to the react-plotly github repos, where one can use the given quickstart example and try to substitute the string in type: 'scatter'
with a variable.
PS.: I am quiet new to TS or JS in general so I might be using wrong/misleading terms unknowningly.
Solution
It isnt entirely evident in their docs but, this is actually a TS feature that the plotly devs are using.
I can say
type MyType = string;
then if I say
const myVar = '123';
TS will be perfectly happy. On the other hand, I could restrict other devs on what actual values they assign to MyType like
type MyType = 'bar' | 'pie' | 'scatter';
which is exactly what plotly has done. and then if a dev says
<Plot type={'123'} />
TS will throw an error because '123' isnt one of the options.
Now, you say, but my plotType variable IS one of those options. While thats true, you typed it as :string. So, when TS type checks is compares the PlotType type inside Plotly which is a limited set of strings to the string type. Thus, you have a mismatched type. In your case you could have said
var plotType: Plotly.PlotType = 'bar';
since the types now match, this would be acceptable. In fact, in this case you wouldnt even be able to accidently change the value of plotType to something not a part of Plotly.PlotType because TS would complain now.
Answered By - Bastiat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.