在 Typescript React 中使用 setInterval() [英] Using setInterval() in Typescript React
问题描述
我正在尝试转换基于 React 的计时器 示例 到 Typescript.
I'm trying to convert a React based timer example to Typescript.
这个类看起来有点像这样:
The class looks a little like this:
export class Container extends
Component<IProps, IState> {
private timerID: NodeJS.Timeout | undefined; // stops a warning in DidMount
constructor(props: IRevovlingContainerProps) {
super(props);
this.state = { date: new Date() } as any;
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID); // error here on this.timerID
}
// ...
在componentWillUnmount()
this.timerID
中有一个错误:
[ts] 'Timeout | 类型的参数未定义'不可分配给'number | 类型的参数不明确的'.类型超时"不是可分配到类型数字".[2345]
[ts] Argument of type 'Timeout | undefined' is not assignable to parameter of type 'number | undefined'. Type 'Timeout' is not assignable to type 'number'. [2345]
我已经检查了 index.d.ts
,它声明了 clearInterval()
:
I've checked index.d.ts
, which declares clearInterval()
:
declare function clearInterval(intervalId: NodeJS.Timeout): void;
所以看起来我将正确类型的参数传递给 clearInterval() ,但它需要一个数字.请问我应该传递什么?
So it looks like I am passing a correctly typed argument into clearInterval() and yet it expects a number. What should I be passing in please?
如果我更改我的 timerID 声明,则在 componentDidMount()
中的 this.timerID
中会出现错误:
if I change my timerID declaration then an error appears in this.timerID
in componentDidMount()
:
private timerID: number | undefined;
Type 'Timeout' is not assignable to type 'number'.
推荐答案
NodeJS.Timeout
旨在在您在 node
环境中运行时使用.由于您想使用浏览器 API,您必须使用 number
作为 timerID
的类型.
NodeJS.Timeout
is meant to be used when you're running in the node
environment. Since you want to use browser APIs, you'll have to use number
as type for the timerID
.
此外,在您的情况下,内置函数不应从 node
类型定义解析它们的类型.如果你安装了@types/node
,如果不需要请卸载.这可能与您需要使用的类型相冲突.
Also, the built-in functions should not resolve their types from node
type definitions, in your case. If you have @types/node
installed, please uninstall it if it's not required. That may be conflicting with the types that you need to be using.
这篇关于在 Typescript React 中使用 setInterval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!