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. 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:
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 '{}'. No index signature with a parameter of type 'string' was found on type '{}'.
2: Type 'keyof T' cannot be used to index type '{}'
Does keyof work with generic classes, can I achieve something like that in TypeScript? I'm using TypeScript 3.9.4