打字稿通用功能类型字面量

时间:2020-04-07 19:28:10

标签: javascript typescript function generics literals

这是正常的,没问题:

type fun = (uid: string) => string 

const abc: fun = value => value

const efg = (callback:fun, value:string) =>callback(value)

console.log(efg(abc, "123"))

但是如果我们选择通用的,就会出错:

type fun = (uid: string) => string 

const abc: fun = value => value

const efg = <T>(callback:T, value:string) =>callback(value)

console.log(efg(abc, "123"))

错误:

该表达式不可调用。类型“未知”没有通话 签名。(2349)

TypeScript Playground demo

我读了https://www.typescriptlang.org/docs/handbook/generics.html,但它没有提及通用函数类型文字。

我需要传递不同的函数作为参数,这就是为什么我需要这样做。

是否有任何变通/破解方法,或者实际上有适当的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

问题在于T类型不受限制,因此可以是任何类型,您可以在此处传递numberstring等。很明显,您无法调用{{1} }它将是函数。

在代码中如何处理number就像使用T参数一样,因此需要给出这种约束。考虑:

string

const efg = <T extends (a: string) => any>(callback: T, value: string) => callback(value) 上方的函数(通过extend关键字)受到约束,该函数采用T并且可以返回任何内容。这意味着string之类的所有功能都可以。

我们可以进一步限制它(如果需要),并说我们的函数只是string->number, string-> boolean, string->object,而这样的接口正是由string->string类型给出的。因此,让我们扩展fun

fun

Playground

答案 1 :(得分:0)

基于rxjs's UnaryFunction的以下内容可能对您有用。

TypeScript Playground demo:

interface Callable<T> {
    (source: T): T;
}

interface CallableInvoker<T> {
    // If the return type also needs to be T, replace any with T
    (callback: Callable<T>, value: T): any
}


function doubleNumber(value: number): number {
    return value * 2;
}

function doubleString(value: string): string {
    return value + value;
}

const efg: Callable<number> = doubleNumber; // Valid
const efg2: Callable<number> = doubleString; // Invalid, doubleString  must match the generic type

const efg3: CallableInvoker<number> = (doubleNumber, value) => doubleNumber(5);