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

TypeScript: How do you determine the type of an attribute whose name is set dynamically?

I am looking at typescript and have a question. I am initializing an object which I will later fill with dynamic key value pairs. The object should be of type Clients. The Key(String) Values(number) are created via a forEach(). Thus, when the object has been created, it would look like this:

type Clients = {}; // This line is my question!

const clients: Clients = {};

const htmlElementCollection: HTMLElement = document.querySelectorAll('.clients');

htmlElementCollection.forEach( c => {
  clients[c.getAttribute('data-client-name')] = clients[c.getAttribute('data-client-value')];
});
// Result:
clients = {
  "A": 10.00,
  "B": 20.00,
}
// but also:
clients = {
  "D": 10.00,
  "B": 20.00,
  "E": 30.00
}

Question: Is it possible to assign a type to dynamic keys?

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 :

You can use the Record type and have it assigning the keys to string and the value to number.
So you can set Clients type as follows.

type Clients = Record<string, number>

You can also set a type for the keys instead of assigning it to string.
Check the official docs of TypeScript for Records here

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