Appearance
setTimeout 和 setInterval
问题
代码:
js
const timer = ref(null)
timer = setInterval(() => {
handler()
}, 1000)
错误类型:
js
// error TS2322: Type 'Timeout' is not assignable to type 'number'.
解决方法:
ts
// 接受 setTimeout 类型
type TimeoutHandle = ReturnType<typeof global.setTimeout>
// 接受 setInterval 类型
type IntervalHandle = ReturnType<typeof global.setInterval>
在浏览器环境,我们可以使用
js
const timer = (ref < IntervalHandle) | (null > null)
timer.value = window.setInterval(() => {
handler()
}, 1000)
自己定义
- setTimeout
ts
declare type TimeoutHandle = ReturnType<typeof global.setTimeout>
- setInterval
ts
declare type IntervalHandle = ReturnType<typeof global.setInterval>