Reactjs 在Typescript中使用setInterval()
我正在尝试将基于React的计时器转换为Typescript 这个班看起来有点像这样:Reactjs 在Typescript中使用setInterval(),reactjs,typescript,timer,Reactjs,Typescript,Timer,我正在尝试将基于React的计时器转换为Typescript 这个班看起来有点像这样: export class Container extends Component<IProps, IState> { private timerID: NodeJS.Timeout | undefined; // stops a warning in DidMount constructor(props: IRevovlingContainerProps) {
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
}
// ...
因此,看起来我正在将一个正确类型的参数传递到clearInterval()中,但它需要一个数字。请问我应该通过什么
编辑:如果我更改了timerID声明,则在componentDidMount()
中的this.timerID
中会出现错误:
React使用JavaScript的vanilla setInterval,它返回一个数字。 检查 但是,您所指的返回类型NodeJS.Timeout是由返回的。这是Node.js特有的
无法将超时分配给一个数字表示您正在将预期类型声明为节点的超时,而实际收到的是一个数字。
NodeJS。超时
用于在节点
环境中运行。由于要使用浏览器API,因此必须使用number
作为timerID
的类型
此外,在您的情况下,内置函数不应从
节点
类型定义解析其类型。如果已安装@types/node
,如果不需要,请卸载它。这可能与您需要使用的类型相冲突。如果您将其定义为任何类型,它应该可以工作
private timerID: any;
明白了,谢谢!人们是否曾经使用过这两种打字方式?如果是这样,他们怎么做?我想你可能需要不同的
tsconfig
s。不过我不确定。欢迎来到SO。这个问题由来已久,已经有了公认的答案。考虑增加一些细节,或者说明为什么你的答案是一个好的(更好的)选择。
private timerID: number | undefined;
Type 'Timeout' is not assignable to type 'number'.
private timerID: any;