[英]How to apply generic type for inner function in typescript
我正在嘗試在typescript中編寫泛型函數,它基本上是從數組中進行過濾。 這是javascript中的等效函數
const filterByProp = function (prop, value) {
return function (item) {
return item[prop] === value;
}
}
const result = people.filter(filterByProp('age', 3))
上面的代碼工作正常,同樣的事情想轉換成typescript。
打字稿下面的函數工作正常。 但內部函數沒有任何類型:(
版本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將根據外部函數的預期返回類型推斷T
,因此不需要顯式類型參數:
interface Person {
age: number
}
const filterByProp = function <T, K extends keyof T>(prop: K, value: T[K]) {
return function (item: T): boolean {
return item[prop] === value;
}
}
const people: Person[] = [{ age: 3}, { age: 2}];
const result = people.filter(filterByProp('age', 3))
people.filter(filterByProp('age', "3")) //error
people.filter(filterByProp('Age', 3)) //error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.