I am working with a Container class that accepts a dynamic object through its constructor. This dynamic object contains multiple classes, and I need to assign one or more of those classes to a property in the Container without sacrificing type safety.
Here's what I have attempted so far. The error message I'm encountering is
Property 'bbb1' does not exist on type 'A | B'.
If you want to check out the code and play around with it, feel free to visit this Playground
class A {
aaa1 = "aaa1"
aaa2 = "aaa2"
}
class B {
bbb1 = "bbb1"
bbb2 = "bbb2"
}
class Container<T> {
all: T;
target: T[keyof T];
constructor(resources: T) {
this.all = resources;
this.target = resources["b" as keyof T];
}
}
const obj = { a: new A(), b: new B() };
const container = new Container(obj);
console.log(container.target.bbb1) // Error
If you have any suggestions on how to approach this issue, I would greatly appreciate your input! Thank you.