[英]Define static indexable object properties in Typescript
I want to code a reusable TypeScript class with an object property, which has indexed, named attributes that can be definied at construction and later modified via their name.我想用一个 object 属性编写一个可重用的 TypeScript class 属性,该属性具有索引,命名属性可以在构造时定义,以后可以通过它们的名称进行修改。 These named attributes could be keys of an interface and my intention is to use this interface to statically check the set function for incorrect keys or iteration, something like:
这些命名属性可能是接口的键,我的意图是使用此接口静态检查集合 function 是否存在不正确的键或迭代,例如:
class Container<T> {
private attributes: {[name: keyof T]: any} = {};
constructor(attributes: {[name: keyof T]: number}) {
Object.entries(attributes).forEach(([name, value]) => {
this.attributes[name] = {value: value, ...}; // 1 I want to add further properites to this object
});
}
set(name: keyof T, value: number) {
this.attributes[name].value = value; // 2
}
}
However the above isn't working because:但是上述方法不起作用,因为:
1: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
1:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”。 No index signature with a parameter of type 'string' was found on type '{}'.
在“{}”类型上找不到带有“字符串”类型参数的索引签名。
2: Type 'keyof T' cannot be used to index type '{}'
2:类型'keyof T'不能用于索引类型'{}'
Does keyof work with generic classes, can I achieve something like that in TypeScript? keyof 是否适用于泛型类,我可以在 TypeScript 中实现类似的功能吗? I'm using TypeScript 3.9.4
我正在使用 TypeScript 3.9.4
To preserve the type of the keys (so they are keyof T
, instead of becoming string
), you can use a for.. in
loop:要保留键的类型(因此它们是
keyof T
,而不是变成string
),您可以使用for.. in
循环:
class Container<T> {
private attributes: {
[name in keyof T]?: any
} = {};
constructor(attributes: {[name in keyof T]: number}) {
for(let key in attributes) {
let value = attributes[key];
this.attributes[key] = { value: value, example: 7 };
}
}
set(name: keyof T, value: number) {
this.attributes[name].value = value; // 2
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.