Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type an array of objects with certain keys in each position?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading