【问题标题】:How to apply generic type for inner function in typescript如何在打字稿中为内部函数应用泛型类型
【发布时间】: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


    【解决方案1】:

    您只需要在内部函数上指定相同的类型参数。当您将其用作过滤器的参数时,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2023-02-22
      • 2020-07-08
      • 2021-11-26
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多