TypeScript: 如何确定动态设置属性名称的属性类型?

huangapple go评论71阅读模式
英文:

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&lt;string, number&gt;

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

huangapple
  • 本文由 发表于 2023年3月9日 21:17:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定