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

Array element label as string in type

Can an array type element’s label be accessed as string?

I have a labeled array type, and want to create an object type, with the labels as properties:

type A = [a: number, b: string];
type Transform<T> = /* ... */;
type B = Transform<A>; // { a: number, b: string }

The application is having a function, and assuring a data-structure has the same properties as there are arguments:

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

const data: Transform<Parameters<typeof f>>[] = [];
function f(a: number, b: string) { data.push({ a, b }); }

The trivial alternative is writing out the type manually, but such repetition is to be avoided, if possible.

>Solution :

No, this is not possible.

There is no syntax in Typescript that can resolve tuple labels in any useful way. They propagate through to your IDE for informational purposes, but that’s the end of it.

You also can’t go the other way. You cannot create labels dynamically from string types. There’s just no syntax for that.

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