I want to type this array:
const arrayToType=[{index:3,value:'foo'}, {amout:4},{total:45, extra:'foo'}]
I know all my arrays will have those keys in those positions in the arrays, the only thing that will change will be the values of each key, not the types.
how can I type a fixed array of objects structure like this?
CodePudding user response:
This can be done simply by declaring a type
for a tuple
type ArrayType = [{index: number, value: string}, {amout: number}, {total: number, extra: string}];
const arrayToType: ArrayType=[{index:3,value:'foo'}, {amout:4},{total:45, extra:'foo'}]
This does require that your array has 3 elements and that they match positionally. There may be other quirks, but this would be the basis to start with.
The way tuples work, you can add more to the end, but those values are not strongly typed. Check out Rest Elements in Tuple Types for some more details.