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?
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.
TypeScript Playground
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With