英文:
TypeScript: How do you determine the type of an attribute whose name is set dynamically?
问题
我在看 TypeScript 并有一个问题。我正在初始化一个对象,稍后将填充动态键值对。该对象的类型应为 Clients。键(字符串)值(数字)是通过 forEach() 创建的。因此,当对象被创建后,它将如下所示:
type Clients = {}; // 这一行是我的问题!
const clients: Clients = {};
const htmlElementCollection: HTMLElement = document.querySelectorAll('.clients');
htmlElementCollection.forEach(c => {
clients[c.getAttribute('data-client-name')] = clients[c.getAttribute('data-client-value')];
});
// 结果:
clients = {
"A": 10.00,
"B": 20.00,
}
// 但也可能是:
clients = {
"D": 10.00,
"B": 20.00,
"E": 30.00
}
问题: 是否可以为动态键分配类型?
英文:
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?
答案1
得分: 1
你可以使用 Record
类型,将键分配为 string
类型,将值分配为数字类型。
因此,你可以如下所示设置 Clients 类型。
type Clients = Record<string, number>
你还可以为键设置类型,而不是将其分配为字符串类型。
查看 TypeScript 的官方文档中有关 Records 的信息此处。
英文:
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
答案2
得分: 1
以下是您要的翻译:
"which translates to an object with keys of type string and values of type number"
翻译为:这意味着一个具有字符串类型键和数字类型值的对象。
英文:
The best you can do here is
type Clients = {
[k: string]: number,
};
which translates to an object with keys of type string and values of type number
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论