我正在尝试编写一个带有两个 args(obj 数组和搜索词)的泛型函数,但出现错误 - 属性 'toLowerCase' 在类型 'T[keyof T] 上不存在'
这里是函数:
public initFullscreenModal = ():ng.IPromise<any> => this.ModalService
.showModal({
component: 'modalImageFullscreen',
bodyClass: 'angular-modal-service-active',
bindings: {
image: this.image
},
// This method is invoked when `ModalService.closeModals()` is called from within ModalService
preClose: (modal: IDavis.Modal, result: any) => {
// We need this in order to properly close the Bootstrap modal via `.modal('hide')`
modal.element.modal('hide');
}
})
.then( (modal: IDavis.Modal): void => {
// required for Bootstrap Modal
modal.element.modal('show');
})
.catch( (error: any) => {
console.error('imageController.initModal().ModalService.showModal().ERROR', error);
});
这里缺少什么?
答案 0 :(得分:0)
似乎与此问题有关:https://github.com/microsoft/TypeScript/issues/10530
您仍然可以将 obj[value]
拉出到变量中以获得类型推断:
function matchSearchTerm<T>(data: T[], search: string): T[] {
return data.filter((obj) => {
const filteredData = (Object.keys(obj) as Array<keyof typeof obj>).some((value) => {
const val = obj[value];
return (
typeof val === "string" && val.toLowerCase().includes(search.toLowerCase())
);
});
return filteredData;
});
}
答案 1 :(得分:0)
function matchSearchTerm<T extends Record<string, string>>(data: T[], search: string) {
return data.filter((obj) => {
const filteredData = (Object.keys(obj) as Array<keyof T>).some((value) => {
const checkIt = obj[value]
type O = typeof checkIt
return (
typeof obj[value] === "string" && obj[value].toLowerCase().includes(search.toLowerCase())
);
});
return filteredData;
});
}
只需为您的 T
通用参数添加额外的约束:T extends Record<string, string>