Dynamic record with value type depending on key suffix
I need to create a list of records for a scatter chart data with error bars. There can be an arbitrary number of datasets in this chart.
The record contains a
x
key representing the x-axis position (value type number
), ${datasetID}_value
key representing the value of the dataset with given id (value type number
) and ${datasetID}_errors
representing the errors of the value at this position (type [number, number]
).
I want to be able to push a valid record into the list without TS errors like so
I'm not sure if this is possible since the prop inside the push() call is being treated as {x: number; [x: string]: number | number[]}
, so I'd love to get help on this, thank you so much. Here is my progress so far: TS PlaygroundSolution:Jump to solution
i think your problem is that
id
needs to be a string literal (not just type string)
``typescript
type DataRecord = {
[key:
${string}_value`]: number...6 Replies
Solution
i think your problem is that
id
needs to be a string literal (not just type string)
this works because typeof key1 and key2 is inferred as literal key1
and key2
(as it's a const assignment). this way ts knows that the same key is not defined twice.yeah it's rough since the id is a dynamic string, so i don't know them beforehand
but your response did allow me to get a bit farther by lying to TS:
for the code i was working at, this is sufficient because i apparently never had to put 2
_value
keys into 1 object at any time, but even then it was still a bit annoying with the as "id"
and as const
.would you mind sharing the code for the real getId function maybe there is some generic magic we could do
there is no real
getId()
function, it's just an id from server response. In actuality, I needed 3 different type of key suffixes, the third one being _trend
for drawing the trendline. My code is something like this:
this is why i said I never had to put 2 _value
in 1 object at a time, since i used a for loop to add one entry to the record at a time. But i needed the as "id"
and as const
hack to add the trendline points to the list, which is annoyingare you in control of what a dataset looks like? going for an array or a map might be a smoother solution than relying on dynamically set keys…
you mean if it is possible for me to change the final shape? at first i had it as nested instead of the weird suffix like this, but i think i ran into some trouble with the chart library :/ Maybe i can dig into deeper to see if it can work, but at this point i feel like its more effort than its worth since everything is working now (even if the
as "id"
and as const
are slightly annoying)
at this point i'm moreso curious about whether this can theoretically be done in TS than needing it for my actual task. I think i'll close the question for now