【发布时间】:2021-09-17 20:53:49
【问题描述】:
我正在尝试编写一个钩子,它接受对象的多个键并根据当前应用的过滤器过滤数据。所以,大致是这样的:
interface IFilterable<T,K extends keyof T & string>{
key: K;
customFilter?: (item: T[K], applied: T[K][]) => boolean
//The hook uses some default logic to filter if this function isn't available.
}
function useFilters<T,K extends keyof T & string>(data: T[], filters: IFilterable<T,K>[]): T[]{
//filter out the data, return new dataset.
}
问题是当传入多个过滤器(IFilterable)时,customFilter 函数中的item 和applied 参数成为键类型的并集。或者,在代码中...
useFilters(
[{a: 1, b: "bob"], {a: 2, b: "berry"}],
[{key: "a", customFilter: (item, applied) => {
//Wanted: item has the type number
//Reality: item has the type (string | number)
},
{key: "b", customFilter: (item, applied) => {
//Wanted: item has the type string.
//Reality: item has the type (string | number)
}
}]);
我已经通过将所有内容输入为unknown(或unknown[])“解决”了这个问题,然后创建包装函数,稍后将其转换回正确的类型,但我希望在整个过程中保持强类型如果可能的话。
那么,在这种情况下,有什么办法可以让我传入对象数组,其中一个属性是键,另一个属性是采用T[K] 的函数,以缩小到特定@987654330 的类型@ 而不是联合类型?
谢谢。
【问题讨论】:
-
IFilterable 的接口错误。 TS 没有像 (item: T[K], applied: T[K][])这样的元组类型
-
@captain-yossarian 这是一个返回布尔值的函数......我忘了在那里添加返回类型。更新了原帖。
标签: typescript generics