如何在泛型函数上使用正确的类型函数?
How to use a proper type Function on a generic function?
我正在尝试修复 @typescript-eslint/ban-types
lint 错误:
warning Don't use Function
as a type @typescript-eslint/ban-types
我同意 Function
是一个不安全的类型,应该替换为适当的函数类型,例如 () => void
.
但是我的代码有点复杂,我不知道如何在这里避免它,因为我正在使用 typeof
that returns a Function
.
这是我的代码的简化版本。完整版是here.
function start<T>(args: unknown[], couldBeAFunction: T) {
if (typeof couldBeAFunction === 'function') {
runFunction(args, couldBeAFunction); // couldBeAFunction now is a Function
}
}
function runFunction<T extends Function>(args: unknown[], target: T) {
target.apply(args, args);
}
我不能用 runFunction<T extends (...args: unknown[]) => unknown>
替换 runFunction<T extends Function>
,否则我会在 runFunction
调用时收到以下错误:
Argument of type 'T & Function' is not assignable to parameter of type '(...args: unknown[]) => unknown'.
Type 'Function' provides no match for the signature '(...args: unknown[]): unknown'.ts(2345)
如何解决此 lint 错误?
您可以使用类型保护:
type Fn = (...args: unknown[]) => unknown
const isFn = (fn: unknown): fn is Fn => typeof fn === 'function'
function start<T>(args: unknown[], couldBeAFunction: T) {
if (isFn(couldBeAFunction)) {
runFunction(args, couldBeAFunction); // couldBeAFunction now is a Function
}
}
function runFunction<T extends Fn>(args: unknown[], target: T) {
target.apply(args, args);
}
我正在尝试修复 @typescript-eslint/ban-types
lint 错误:
warning Don't use
Function
as a type @typescript-eslint/ban-types
我同意 Function
是一个不安全的类型,应该替换为适当的函数类型,例如 () => void
.
但是我的代码有点复杂,我不知道如何在这里避免它,因为我正在使用 typeof
that returns a Function
.
这是我的代码的简化版本。完整版是here.
function start<T>(args: unknown[], couldBeAFunction: T) {
if (typeof couldBeAFunction === 'function') {
runFunction(args, couldBeAFunction); // couldBeAFunction now is a Function
}
}
function runFunction<T extends Function>(args: unknown[], target: T) {
target.apply(args, args);
}
我不能用 runFunction<T extends (...args: unknown[]) => unknown>
替换 runFunction<T extends Function>
,否则我会在 runFunction
调用时收到以下错误:
Argument of type 'T & Function' is not assignable to parameter of type '(...args: unknown[]) => unknown'. Type 'Function' provides no match for the signature '(...args: unknown[]): unknown'.ts(2345)
如何解决此 lint 错误?
您可以使用类型保护:
type Fn = (...args: unknown[]) => unknown
const isFn = (fn: unknown): fn is Fn => typeof fn === 'function'
function start<T>(args: unknown[], couldBeAFunction: T) {
if (isFn(couldBeAFunction)) {
runFunction(args, couldBeAFunction); // couldBeAFunction now is a Function
}
}
function runFunction<T extends Fn>(args: unknown[], target: T) {
target.apply(args, args);
}