Is there a better way to access interface/class properties using strings?
Consider the following interface:
interface Type {
nestedProperty: {
a: number
b: number
}
}
I want to set nested properties using array iteration:
let myType: Type = ...
["a", "b"].forEach(attributeName => myType.nestedProperty[attributeName] = 123)
However, TypeScript complains that "nestedProperty" doesn't have a string index type. Adding a typeguard like if (attributeName === "a"))
resolves the error, but I want to avoid using multiple if statements.
Additionally, I don't want to use an indexed type:
interface Type<T> {
[index:string]: T
a: T
b: T
}
Since the structure is not dynamic and properties could have different types.
I've searched through documentation, Stack Overflow, and the web, but haven't found an elegant solution. Should I write a custom guard that returns a union type predicate?
(attribute: string): attribute is ('a' | 'b') { ... }