打字稿:将函数的参数类型定义为具有泛型的函数

时间:2021-05-26 13:26:32

标签: typescript typescript-generics

我已经创建了一个像这样的 compose 函数

const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x));

在我看来,fg 都是 fGeneric 类型的函数,定义为

type fGeneric = <T, R>(arg: T) => R;

我的问题是我不明白是否以及如何使用类型 fGeneric 来指定 fgcomposedType 的类型。更清楚地说,如果我喜欢这个

const composeTyped_ = <T, U, R>(f: fGeneric, g: fGeneric) => (x: T) => g(f(x));

函数 composeTyped_ 被分配了类型 (x: T) => unknown。我想获得的是 (x: T) => R 类型。

1 个答案:

答案 0 :(得分:1)

您需要定义 fGeneric 以便它接受泛型类型参数:

type fGeneric<T, R> = (arg: T) => R;

然后你可以像这样定义composeTyped_

const composeTyped_ = <T, U, R>(
  f: fGeneric<T, U>,
  g: fGeneric<U, R>
) => (x: T) => g(f(x));

现在应该可以正常工作了:

declare const f: (str: string) => number

declare const g: (num: number) => null

composeTyped_(f, g)

// Argument of type '(num: number) => null' is not assignable to parameter of type 
//   'fGeneric<number, string>'.
//  Type 'null' is not assignable to type 'string'.
composeTyped_(g, f)