What's proper way to access interface/class properties using strings?
I have following interface
interface Type {
nestedProperty: {
a: number
b: number
}
}
I'd like to set nested property using array iteration like that:
let myType:Type = ...
["a", "b"].forEach(attributeName => myType.nestedProperty[attributeName] = 123)
TS complains that "nestedProperty" doesn't have string index type. If I add if typeguard (e.g. if (attributeName === "a")) compiler is happy but I really don't want to go if (...===... || ...===... || ... ) { route.
I also don't want to use indexed type:
interface Type<T> {
[index:string]: <T>
a: <T>
b: <T>
}
Since it's not dynamic structure and properties could have different types.
I'm sure there is some elegant way to do it but can't seem to find it anywhere in documentation/Stack Overflow/web.
Should I write custom guard returning union type predicate for that? Something like that?
(attribute: string): attribute is ('a' | 'b') { ... }
Typeinterface was just a generic example. If it isn't, you can go withinterface Type {nestedProperty: {[key: string]: number};}Typeto be dynamic structure where I can put anything there. I want to stick to set of defined properties. I've edited question to be more preciseinterface Type {nestedProperty: {[key in ('a' | 'b')]: number};}?