【发布时间】:2019-01-25 03:42:16
【问题描述】:
我正在尝试在 typescript 中编写一个通用函数,它基本上是从数组中进行过滤。这是javascript中的等效函数
const filterByProp = function (prop, value) {
return function (item) {
return item[prop] === value;
}
}
const result = people.filter(filterByProp('age', 3))
上面的代码工作正常,同样的东西想转换成打字稿。
下面的打字稿功能工作正常。但内部函数没有任何类型:(
版本 2:
const filterByProp2 = function <T, K extends keyof T>(prop: K, value: T[K]) {
return function (item): boolean {
return item[prop] === value;
}
}
版本 3:
以下代码未按预期运行。在为内部函数应用类型之后。
const filterByProp3 = function <T, K extends keyof T>(prop: K, value: T[K]) {
return function <T>(item: T): boolean {
return item[prop] === value;
}
}
用法:
const result3 = people.filter(filterByProp3<IUser, 'age'>('age', 3)) // Not sure how to pass for inner func <IUser>
我遇到了类似的错误
[ts] Type 'K' cannot be used to index type 'T'.
[ts] This condition will always return 'false' since the types 'T[K]' and 'T[K]' have no overlap.
有人可以帮忙解决这个问题吗?
版本 4:这是可行的,但我更喜欢解决版本 3 的问题。
function filterByProp4<T, K extends keyof T>(
prop: K,
entities: T[],
value: T[K]
) {
return entities.filter(e => e[prop] === value);
}
【问题讨论】:
标签: typescript typescript-generics