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

Advertisements

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?

>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

Leave a Reply Cancel reply