错误的问题。示例代码。
考虑此代码
export interface IParameterType{
name:string,
label:string,
type:string,
defaultValue:number
}
class Object3D{
public static parameterTypes: IParameterType[] = [];
constructor(){
(this.constructor as typeof Object3D).parameterTypes.forEach(paramType => {
console.log(paramType.name);
});
}
}
class Cube extends Object3D{
public static parameterTypes: IParameterType[] = [
{
name: 'width',
label: 'Width',
type: 'integer',
defaultValue: 10,
},
{
name: 'height',
label: 'Height',
type: 'integer',
defaultValue: 10,
},
{
name: 'depth',
label: 'Depth',
type: 'integer',
defaultValue: 10,
},
];
}
class Sphere extends Object3D{
public static parameterTypes: IParameterType[] = [
{
name: 'radius',
label: 'radius',
type: 'integer',
defaultValue: 10,
},
];
}
问题是(this.constructor as typeof Object3D).parameterTypes
并不是多态调用的,我想根据对象实例调用Cube或Sphere的parameterTypes。
在JavaScript中,这很简单:this.constructor.parameterTypes
但TypeScript不允许我这样做-> Property 'parameterTypes' does not exist on type 'Function'
有帮助吗?
我尝试过:
if (this instanceof Cube){
(this.constructor as typeof Cube).parameterTypes.forEach(paramType => {
console.log(paramType.name!);
});
}
但是这样做,多态性有什么用?