setInterval(
(function func() /* :() => ??? */ {
console.log(`I will be invoked immediately!`);
return func;
})(),
10000
);
问候,我是Typescript的新手。
我以前在JS中以这种方式使用setInterval()
,因此我可以立即调用setInterval()
的回调函数,而不必等初次运行之前等待10秒钟。但是,当我现在搬到TS时,我不知道在这里放置什么作为其返回类型。我曾尝试像any
一样使用() => any
,但似乎可能会违反 @ typescript-eslint 的规则:Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)
。
任何人都可以给我一些建议吗?预先感谢。
p.s。我知道我使用setInterval()
的方式可能不好,但是我只是想摆脱它。
答案 0 :(得分:3)
在任何情况下,我都会避免使用任何强制使用显式类型的lint规则,或者至少在这种情况下,我可能会禁用它。
如果按原样保留该函数,则Ts将正确推断返回类型。
如果要说明,可以使用递归类型:
type Fn = () => Fn;
setInterval(
(function func() : Fn {
console.log(`I will be invoked immediately!`);
return func;
})(),
10000
);
答案 1 :(得分:3)
您可以完全按照TS的定义来定义它:console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
。
typeof func
这显然是说该函数返回具有自己签名的函数,因此它也具有表达力。