When you mention a "JSON object," I assume you are referring to a JavaScript object, as seen in your example code. It appears that each value within the object should be an instance of one of the child classes rather than the class itself.
TypeScript should automatically deduce the type of your json
object. If your editor is configured to use TypeScript's language server, you will receive suggestions for methods on each value in the object through IntelliSense.
Below is a refined version of your example to illustrate this:
abstract class Parent {
parentMethod() {}
}
class Child1 extends Parent {
child1Method() {}
}
const children = {
child1: new Child1(),
};
// You can access both `parentMethod` and `child1Method` using Intellisense
children.child1.parentMethod();
children.child1.child1Method();
If you want to ensure that every value in the object is a type of Parent
, you can define it like this:
const children: { [index: string]: Parent } = {
child1: new Child1(),
child2: new Child2(),
child3: new Child3(),
};
By doing this, you will only have access to the methods from Parent
on the property named child1
. This restricts the properties to being treated as instances of Parent
rather than specific child classes.
If you prefer not to broaden the type of each property to Parent
, you can specify the index type as a union of all possible children:
const children: { [index: string]: Child1 | Child2 | Child3 } = {
child1: new Child1(),
child2: new Child2(),
child3: new Child3(),
};
Using this method allows you to call methods from Parent
on any property of the object. However, you will need to utilize a type guard to determine which specific class each property belongs to before utilizing any methods unique to a particular child class.