Typescript:为其子类指定父类类型



问题

我想创建一个JSON对象,它有3种对象(都来自同一个父对象(作为值。而且,我想指定它们的类型。我想对Intellisense使用父类中的函数来帮助我编写代码。。。

示例:

abstract class Parent{
function do_something() {...}
}
class child_1 extends Parent{}
class child_2 extends Parent{}
class child_3 extends Parent{}
// Now the JSON
const json: {[key: string]: /*WHAT_TO_PUT_HERE*/} = {
'child_1': child_1,
'child_2': child_2,
'child_3': child_3,
}

我假设通过;JSON对象";您的意思是JavaScript对象,因为这就是您的示例代码所包含的内容。我还假设您希望对象中的每个值都是其中一个子类的实例,而不是类本身。

TypeScript应该已经推断出json对象的类型,如果您将编辑器配置为使用TypeScript的语言服务器,您将获得对象中每个值的方法的IntelliSense建议。

以下是您要演示的示例的清理版本:

abstract class Parent {
parentMethod() {}
}
class Child1 extends Parent {
child1Method() {}
}
const children = {
child1: new Child1(),
};
// Both of these methods on `child1` will be suggested by Intellisense
children.child1.parentMethod();
children.child1.child1Method();

如果你想强制对象中的每个值都是Parent,你可以这样键入:

const children: { [index: string]: Parent } = {
child1: new Child1(),
child2: new Child2(),
child3: new Child3(),
};

但是,如果您这样做,您将只能访问child1属性上Parent中的方法,因为您已将该属性键入为Parent而不是Child

如果不想将每个属性的类型扩展为Parent,则必须将索引类型指定为所有可能的子级的并集:

const children: { [index: string]: Child1 | Child2 | Child3 } = {
child1: new Child1(),
child2: new Child2(),
child3: new Child3(),
};

如果使用此表单,则可以在对象的任何属性上从Parent调用方法,但在使用特定于特定子类的任何方法之前,需要使用类型保护来检查每个属性是哪个特定类。

最新更新