我正在使用TypeScript编写的Node中的应用程序正在工作,我想使用filter()来基于属性过滤对象数组.我有一个公共方法(getValidObjects()),该方法接受一个对象(首选),该对象具有我要匹配的属性.
在当前设置中,我利用thisArg
将回调中的上下文设置为首选对象.
class Sample {
_objects:Object[];
_preferred:Object;
constructor() {
this._objects = [
{
valid: true,
label: 'This is valid'
},
{
valid: false,
label: 'This is invalid'
}
];
}
public getValidObjects(preferred:Object) {
return this._objects.filter(this.filterObjects, preferred);
}
private filterObjects(sample:Object, index:number, array:Object[]) {
// "this" should be the preferred object
return this.valid == sample.valid;
}
}
export = Sample;
该类最终会编译,但最终会引发错误:
错误TS2339:类型“样本”上不存在属性“有效”.
看起来像编译器一样令人窒息,因为它试图以此对类进行类型检查.我不确定这是否是tsc中的错误,并且只是不知道如何处理thisArg,或者是否有另一种方法可以实现此目的.
附加信息
>我正在使用typescript-require来要求我的模块;
>这不是我的确切实现,但是已经足够接近来说明问题了.
TL; DR
使用filter()thisArg参数时,如何使tsc编译类而不抛出错误?
解决方法:
该错误是由于您已经创建了一个类级方法filterObjects()并在另一个上下文中使用它而引起的.
TypeScript编译器不知道此方法的预期用途,它决定您将在Sample上下文中使用它:sample.filterObjects().
您至少有2个不同的选项来解决此错误:
>将此类型转换为数组中的类型:
private filterObjects(sample:Object, index:number, array:Object[]) {
// here, Object is your type, but it can be anything else
// you have to cast to <any> first, because compiler may warn you
// that Sample can not be cast directly to your type
return (<Object><any>this).valid == sample.valid;
}
>将filterObjects()声明移到getValidObjects()中:
public getValidObjects(preferred:Object) {
function filterObjects(sample:Object, index:number, array:Object[]) {
return this.valid == sample.valid;
}
return this._objects.filter(filterObjects, preferred);
}
我建议第二种,从语义上讲更好(如果filterObjects不是Sample的方法,则不应使用它).
原文地址:https://codeday.me/bug/20191120/2042249.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。