[英]How do I define and call a generic function parameter in Typescript?
我在Function.prototype.call
中寻找 Function.prototype.call 的单参数类型安全等效项。
这不起作用,因为F
缺少正确的约束(也许):
function call<F,A>(f: F, arg: A) {
return f(arg);
}
因此,Typescript 抱怨“此表达式不可调用。‘未知’类型没有调用签名。”
如何使F
可调用? 如何管理call
以具有F
的返回类型?
正如您所说,您需要添加一个约束,以便它是可调用的。 一个选项可能如下所示:
function call<F extends Function,A>(f: F, arg: A) {
return f(arg);
}
通用约束: https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints 。
如果您想提供更强的类型安全性,一种方法可能如下所示。
type Parameter<T> = T extends (arg: infer T) => any ? T : never;
function call<F extends (arg: any) => any>(f: F, arg: Parameter<F>): ReturnType<F> {
return f(arg);
}
const fn = (input: number): number => input * 2;
const result = call(fn, 2) // Valid
const result2 = call(fn, "2") // Argument of type '"2"' is not assignable to parameter of type 'number'.(2345)
const result3 = call(fn, false) // Argument of type 'false' is not assignable to parameter of type 'number'.(2345)
const badFn = (input: number, options: {}): number => input * 2;
const result4 = call(badFn, 2) // Argument of type '(input: number, options: {}) => number' is not assignable to parameter of type '(arg: any) => any'.(2345)
这为F
定义了一个更严格的约束,说它必须是一个只接受一个参数的 function。 然后从 function 推断出参数。 您也可以使用Parameters<F>[0]
,因为Parameters
是 Typescript 提供的实用程序类型。 ReturnType
是另一种推断F
的返回类型的实用程序类型,可用作call
的返回类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.