Reputation: 463
I have the following code:
const qn = props.question.question // == question number
const statusLib: { [index: number]: {} } = {
82: ["70%", "0%", "0%", 1, 1],
83: ["70%", "0%", "0%", 1, 2],
84: ["100%", "45%", "0%", 2, 3],
85: ["100%", "70%", "0%", 2, 3],
86: ["100%", "100%", "46%", 3, 3],
}
const s:Array<ReactText> = statusLib[qn] // squiggly under 's'. Should return array
I want to keep it short and sweet. This should be min reproducible example. I tried various permutations, with about the same result.
I never had a problem rendering on local server. It's strictly a typescript enforcement thing.
Type '{}' is missing the following properties from type 'any[]': length, pop, push, concat, and 28 more.ts(2740)
I'm still learning the semantics of TS but my understanding is from this
const statusLib: { [index: number]: {} } = {
you're declaring how the the object should be indexed, and then that it is an object of the most general type.
My assignment s = ...
obviously returns an array. If I wasn't my code wouldn't work at all. Typescript thinks it's an object, so maybe I'm accidentally telling it that. I tried various ways to tell it all the contents are arrays such as :
const statusLib: { [index: number]: {[]} } = {
and
s:any[]
StatusLib is an object indeed but it's children are all arrays. How do I tell TS this?
Upvotes: 1
Views: 1293
Reputation: 1448
You are telling TS that your statusLib is an object {}
with key value pairs of type number: object
but then you actually need them as number: array
this the error that it expects object index: {}
but instead its getting index: []
. Try the following
const statusLib: { [index: number]: Array<string | number> }
Upvotes: 1
Reputation: 66490
You have an array like ["70%", "0%", "0%", 1, 1]
that you typehint as an empty object {}
. You at least need an array []
, which could be any[]
(worst), unknown[]
(still bad), (string|number)[]
(getting close), yet since your array is consistent it seems to be a tuple that you could type in the form of:
type MyTuple = [string, string, string, number, number];
Then your typing should become
const statusLib: { [index: number]: MyTuple }
(You don't need the custom type defintion. It may be useful in the long run.)
Upvotes: 2