我正在寻找与Typescript中的Function.prototype.call等价的单参数类型安全。
这不起作用,因为F缺少适当的约束(可能):
function call<F,A>(f: F, arg: A) {
return f(arg);
}因此,Typescript会抱怨“此表达式不可调用。类型‘未知’没有调用签名。”
如何使F可调用?如何管理call使其返回类型为F
发布于 2020-06-06 22:51:51
正如您所说的,您需要添加一个约束,以便它是可调用的。一个选项可能如下所示:
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定义了一个更严格的约束,即它必须是一个只接受一个参数的函数。然后从该函数中推断出该参数。您也可以使用Parameters<F>[0],因为Parameters是由Typescript提供的实用程序类型。ReturnType是推断F返回类型的另一种实用程序类型,可用作call的返回类型。
https://stackoverflow.com/questions/62233382
复制相似问题