I'm stuck trying to make Typescript infer types of dynamically created getter and setter. I have a class MyClass with containers map:
type Container = {
get: () => Content
set: (value: Content) => void
}
type ContainersMap = { [key: string]: Container }
class MyClass {
containers: ContainersMap
constructor(names: string[]) {
this.containers = {} as ContainersMap
names.forEach(name => {
Object.defineProperty(this.containers, name, {
get() { return read(name) },
set(value) { write(name, value) }
})
})
Object.freeze(this.containers)
}
}
And next in my code I want to use it like this:
let someContent: Content = {/* some content */}
let myClass = new MyClass(['first', 'second'])
// Getting type error in line below because TS thinks I try assign Content to Container
myClass.containers['first'] = someContent
A possible solution I found is to define type ContainersMap = { [key: string]: Content } but I dislike this solution because in my opinion it doesn't reflect the actual ContainersMap type
Is it a way to implement this properly?
{ [key: string]: Container }means that each key ofthis.containersis an object withgetandsetmethods rather than a property that you can set.