Typescript泛型函数类型文字

问题描述 投票:0回答:2

这正在起作用,没问题:

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,但未对通用函数类型文字进行任何说明。

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

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

javascript typescript function generics literals
2个回答
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);

0
投票

问题是T类型不受限制,因此可以是任何东西,您可以在其中传递numberstring等。很明显,您不能像函数那样调用number

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

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

T之上被限制为扩展函数,该函数采用string并且可以返回任何内容。这意味着string->number, string-> boolean, string->object等所有功能均正常。

我们可以走得更远,并进一步限制它(如果需要),并说我们的函数仅为string->string,而这种接口正是由fun类型给定的。因此,让我们扩展fun

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

Playground

© www.soinside.com 2019 - 2024. All rights reserved.