在 TypeScript 中,如何声明遵循上述规则的函数f?
f是一个函数:
强调“不同的返回类型” ...
我的具体目标是输入我实现的 React Hook,但我的问题与钩子本身无关。相反,它与类型声明有关。
我非常接近解决方案,但仍然缺少一块......基于这个来自不同但相似问题的答案,我能够向正确覆盖参数的函数添加类型提示,但这种方法在于返回类型:
这是我的代码:
import { useRef } from 'react';
export default function useTimeoutDebounce<F extends Function>(callback: F, ms: number): F {
const timeout = useRef<number>();
const timeoutDebounce = (...args: any[]) => {
if (typeof window !== 'undefined') {
window.clearTimeout(timeout.current);
timeout.current = window.setTimeout(() => {
callback(...args)
}, ms);
}
};
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return <any>timeoutDebounce;
}
有了该代码,我就可以像这样使用它:
请注意,TypeScript 成功检查了参数的类型!太棒了!
但是,看看另一个例子,(这是我想要改变的行为):
请注意,钩子的返回类型是boolean
,这是一个谎言。正如您在钩子声明中所见,它是一个空函数。
I am thinking of the long run. Having the type hint lying about the return type of a function will eventually cause problems when maintaining the code.
P.s.: I looked at the Parameters utility type, but I couldn't make it work for my case because it doesn't work with Function.
From the documentation:
type T7 = Parameters<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'.
I guess the solution would look something like this (I have written it as what I believe is a minimal reproducible example for your problem).
在下面的例子中,你可以看到 aToC 函数是从 aToB 函数构造的,它以相同的参数签名但不同的返回值结束。它有一个打字稿游乐场,它显示它可以编译,您可以将鼠标悬停在 aToC 上以从那里检查类型和实验。
type A = "A";
type B = "B";
type C = "C";
function retypeFunction<Params extends any[]>(fun: (...params:Params) =>B) : (...params:Params) =>C {
return (...params:Params) => "C"
}
function aToB(a:A):B{
return "B";
}
const aToC = retypeFunction(aToB);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句