I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass
which contains a map of containers
:
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)
}
}
In another part of my code, I want to utilize it like this:
let someContent: Content = {/* some content */}
let myClass = new MyClass(['first', 'second'])
// I'm encountering a type error here because TypeScript is interpreting it as an attempt to assign Content to Container
myClass.containers['first'] = someContent
I came across a potential solution where I defined
type ContainersMap = { [key: string]: Content }
, but I'm not fully satisfied with this approach as it doesn't accurately represent the intended type of ContainersMap
.
Is there a more appropriate way to implement this?