[英]Typescript: define the type of a parameter of a function as a function with generics
I have created a compose
function like this我已经像这样创建了一个
compose
function
const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x));
It seems to me that both f
and g
are functions of type fGeneric
which is defined as在我看来,
f
和g
都是fGeneric
类型的函数,定义为
type fGeneric = <T, R>(arg: T) => R;
My problem is that I do not understand if and how I could use the type fGeneric
to specify the type of f
and g
in composedType
.我的问题是我不明白是否以及如何使用类型
fGeneric
来指定f
和g
中的类型composedType
。 To be more clear, if I do like this更清楚地说,如果我喜欢这样
const composeTyped_ = <T, U, R>(f: fGeneric, g: fGeneric) => (x: T) => g(f(x));
the function composeTyped_
is assigned the type (x: T) => unknown
. function
composeTyped_
被分配类型(x: T) => unknown
。 What I would like to obtain though is the type (x: T) => R
.我想获得的是类型
(x: T) => R
。
You need to define fGeneric
so that it accepts generic type arguments:您需要定义
fGeneric
以便它接受泛型类型 arguments:
type fGeneric<T, R> = (arg: T) => R;
Then you can defined composeTyped_
like so:然后你可以像这样定义
composeTyped_
:
const composeTyped_ = <T, U, R>(
f: fGeneric<T, U>,
g: fGeneric<U, R>
) => (x: T) => g(f(x));
This should now work nicely:现在应该可以很好地工作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.