Typescript:将函数参数的类型定义为具有泛型的函数

Typescript:将函数参数的类型定义为具有泛型的函数,typescript,typescript-generics,Typescript,Typescript Generics,我创建了这样一个compose函数 const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); const composeTyped_ = <T, U, R>(f: fGeneric, g: fGeneric) => (x: T) => g(f(x)); 我的问题是,我不明白是否以及如何使用typefGeneric在comp

我创建了这样一个
compose
函数

const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x));
const composeTyped_ = <T, U, R>(f: fGeneric, g: fGeneric) => (x: T) => g(f(x));
我的问题是,我不明白是否以及如何使用type
fGeneric
composedType
中指定
f
g
的类型。更清楚地说,如果我喜欢这个

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

函数
composeTyped_uu
被分配类型
(x:T)=>未知
。但是我想获得的是类型
(x:T)=>R

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

type fGeneric<T, R> = (arg: T) => R;
现在应该可以很好地工作了:

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) 
declare const f:(str:string)=>number
声明常量g:(num:number)=>null
复合类型(f,g)
//类型为“(num:number)=>null”的参数不可分配给类型为的参数
//“fGeneric”。
//类型“null”不可分配给类型“string”。
复合类型(g,f)

谢谢,效果很好。我犯了这样定义函数类型的错误
typefgeneric=(arg:T)=>R。顺便说一句,当我定义这样一个类型时,编译器并没有抱怨,但现在,在您的回答之后,我正在努力理解这可能是哪种类型。换句话说,你能解释一下这个类型定义的含义吗:
typefgeneric=(arg:T)=>R
type fGeneric=(arg:T)=>R
仅允许自动推断
T
R
。实际上,这意味着以这种方式定义的
fGeneric
几乎不可能使用。一个简单的例子是
typeidentity=(arg:T)=>T
。该类型只能在定义中使用,如
const-identity:identity=arg=>arg
。但是,如果您将其键入
typeidentity=(arg:T)=>T
,则可以执行类似
const惊叹号:Identity=(str)=>str.concat(!”)
。非常感谢,顺便说一句,在我的博客中,您可以找到一些有关
compose
函数的疯狂键入