我想检查一个角度的类型有问题。
export interface DynamicComponentConfig {
name: string;
component: Type<any>;
}
export class DynamicInputComponent extends DynamicComponentBase {
}
export class DynamicDatePickerComponent extends DynamicComponentBase {
}
export class DynamicComponentBase {
@Input() group: FormGroup;
@Input() form: FormGroupDirective;
}当我创建一个保存引用类型(而不是该类型的实例)的实例时,
let conf: DynamicComponentConfig = {
component: DynamicInputComponent,
name: 'Surname'
};并传递给负责动态创建组件的服务,我需要检查类型,但instanceof不起作用:
if (conf.component instanceof DynamicComponentBase) {
...
}只有当我直接检查它所属的类型时,它才能工作,但是我有几个组件,它们都是从DynamicComponentBase继承的:
if (conf.component === DynamicInputComponent || conf.component === DynamicDatePickerComponent || ...) {
...
}检查config.component.prototype我得到DynamicComponentBase {构造函数:ƒ},但是如果我检查config.component.prototype === DynamicComponentBase,则会得到false
所以我要找的是一种检查他们是否继承了我的基本组件的方法,知道吗?
发布于 2021-09-08 21:25:49
经过研究,我找到了一个解决方案检查原型,它实际上解决了我的问题,即让多个组件(DynamicInputComponent,DynamicDatePickerComponent)继承一个基本组件DynamicInputComponent,这样我就不必只使用Object.getPrototypeOf来检查组件类型是否是一个或其他子类类型:
if (Object.getPrototypeOf(config.component) === DynamicComponentBase) {
// returns true!! :)
}
if (config.component.prototype === DynamicComponentBase) {
// returns false
}我唯一的疑问是为什么第二个表达式返回false
发布于 2021-09-08 00:23:54
conf.component持有一个typeOf DynamicInputComponent,而不是动态实例。
class Bat {
public name?: string;
}
let typeOfBat = Bat;
let obj = new Bat();
console.log(typeOfBat === Bat); // true
console.log(obj === Bat); // false
console.log(typeOfBat instanceof Bat); // false
console.log(obj instanceof Bat); // true在您的编辑/您的问题是下面一行。
组分:类型;
这里您只是允许any类型,所以您被迫检查基是否是DynamicComponentBase,但是如果您编写它的component: typeof DynamicComponentBase;,那么您不必担心它,Typescipt将为您检查它。
class DynamicComponentBase {
group: string = '';
form: number = 0;
}
interface DynamicComponentConfig {
name: string;
component: typeof DynamicComponentBase; // this will either DynamicComponentBase or its child refered
}
class DynamicInputComponent extends DynamicComponentBase {
}
class DynamicDatePickerComponent extends DynamicComponentBase {
}
class NotDynamicComponent {
}
let conf: DynamicComponentConfig = {
component: DynamicInputComponent,
name: 'Surname'
};
/*
let conf1: DynamicComponentConfig = {
component: NotDynamicComponent, // will lead to error
name: 'Surname'
};
*/
if(conf.component === DynamicInputComponent)
{
console.log("DynamicInputComponent");
}
if(conf.component === DynamicDatePickerComponent)
{
console.log("DynamicDatePickerComponent");
}
if(conf.component === NotDynamicComponent) // can never be true
{
console.log("NotDynamicComponent");
}https://stackoverflow.com/questions/69095532
复制相似问题