错误的问题。示例代码工作。
考虑这段代码
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!);
});
}
但是这样做,多态又有什么用呢?