mkl*_*uwe 9 generics typescript
Function.prototype.call我正在寻找与 Typescript等效的单参数类型安全。
这不起作用,因为F缺少适当的约束(也许):
function call<F,A>(f: F, arg: A) {
return f(arg);
}
Run Code Online (Sandbox Code Playgroud)
因此,Typescript 抱怨“这个表达式不可调用。类型‘未知’没有调用签名。”
我如何使F可调用?我如何设法call获得返回类型F?
正如您所说,您需要添加一个约束,以便它可以被调用。一种选择可能如下所示:
function call<F extends Function,A>(f: F, arg: A) {
return f(arg);
}
Run Code Online (Sandbox Code Playgroud)
通用约束: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)
Run Code Online (Sandbox Code Playgroud)
这为 定义了更严格的约束F,表示它必须是一个只接受一个参数的函数。然后从该函数推断出该参数。您还可以使用Parameters<F>[0]sinceParameters是Typescript提供的实用程序类型。ReturnType是另一种实用程序类型,用于推断其返回类型F可以用作 的返回类型call。
| 归档时间: |
|
| 查看次数: |
25569 次 |
| 最近记录: |