[英]TypeScript instanceof not working while method argument is not a plain object
我有一个从参数类型已知的两个地方调用的方法。 在此方法中,将检查传入的参数是否为两种类型,但都返回false。 我不明白为什么会这样。 我已经阅读了其他人也发布过同样问题的问题。 但是我的问题有所不同,因为我没有像他那样构造一个普通的对象。 问题可以在这里找到:
这是导致问题的方法:
changeUnitOfValueInput(filter){
console.log((filter === undefined));
let filterType: string;
if (filter instanceof HTMLInputElement)
filterType = (filter as HTMLInputElement).value;
else if (filter instanceof AdvancedFilter){
console.log("its in");
filterType = (filter as AdvancedFilter).advancedFilterSubject;
}
else{
console.log('im out');
return;
}
switch(filterType){
case AdvancedFilterSubject.GROWTH_TEMPERATURE:{
this.unitLabel = (this.filterOptionsForm.controls['measureSystem'].value ==='imperial') ? '°F' : '°C';
break;
}
case AdvancedFilterSubject.GROWTH_DAYS:{
this.unitLabel = 'days'
break;
}
//fall through
case AdvancedFilterSubject.PLANT_HEIGHT:
case AdvancedFilterSubject.PLANT_SPACING:
case AdvancedFilterSubject.ROW_SPACING:
case AdvancedFilterSubject.SOW_DEPTH:
this.unitLabel = (this.filterOptionsForm.controls['measureSystem'].value ==='imperial') ? '″' : '㎝';
}
}
此方法在以下组件方法中调用:
populateFieldsWithSelectedFilterData(existingAdvancedFilter: AdvancedFilter){
this.changeUnitOfValueInput(existingAdvancedFilter);
this.filterOptionsForm.controls['filterType'].setValue(existingAdvancedFilter.advancedFilterSubject);
this.filterOptionsForm.controls['logicalOperator'].setValue(existingAdvancedFilter.logicalOperator);
this.filterOptionsForm.controls['advancedFilterValue'].setValue(existingAdvancedFilter.filterValue);
}
调用它的第二个位置是在前端(html部分):
<p-dropdown #filterType formControlName = "filterType" placeholder="Filter type" [options]="filterTypesList" (onChange)="changeUnitOfValueInput(filterType)" >
</p-dropdown>
由于两个instanceof
条件都返回false,因此该方法会一直过早返回。 谁能告诉我发生了什么事?
编辑:这是在HTML中使用的filterTypeList
的定义
filterTypesList: SelectItem[] = [
{label:'Minimum temperature', value: AdvancedFilterSubject.GROWTH_TEMPERATURE},
{label:'Growth days', value: AdvancedFilterSubject.GROWTH_DAYS},
{label:'Maximum height', value: AdvancedFilterSubject.PLANT_HEIGHT},
{label:'Row spacing', value: AdvancedFilterSubject.ROW_SPACING},
{label:'Plant spacing', value: AdvancedFilterSubject.PLANT_SPACING},
{label:'Sow depth', value: AdvancedFilterSubject.SOW_DEPTH}
];
为了使instanceof
正常工作,您使用的对象的原型必须与构造函数匹配; 在这种情况下为HTMLInputElement
或AdvancedFilter
。 取决于AdvancedFilter
的构造方式,不一定是这种情况。 创建类型保护功能可能会更好:
function isAdvancedFilter(possibleAdvancedFilter: any): possibleAdvancedFilter is AdvancedFilter {
return possibleAdvancedFilter &&
!!(possibleAdvancedFilter as AdvancedFilter).advancedFilterSubject;
}
当然,您可以将此函数更改为需要执行的任何检查,以确保该值可以用作AdvancedFilter。 然后,只需使用isAdvancedFilter(variable)
而不是instanceof variable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.