我正在尝试转换基于 React 的计时器example到打字稿。
这个类看起来有点像这样:
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
}
// ...
In componentWillUnmount()
this.timerID
有错误:
[ts] 类型为“超时|”的参数undefined' 不可分配给
'number | 类型的参数不明确的'。类型“超时”不是
可分配给键入“数字”。 [2345服]第2345服[双线] 新服
我查过index.d.ts
,它声明clearInterval()
:
declare function clearInterval(intervalId: NodeJS.Timeout): void;
所以看起来我正在将正确类型的参数传递给clearInterval(),但它需要一个数字。请问我应该传递什么?
编辑:如果我更改timerID声明,则会出现错误this.timerID
in componentDidMount()
:
private timerID: number | undefined;
Type 'Timeout' is not assignable to type 'number'.
NodeJS.Timeout
是为了当你在运行时使用node
环境。由于您想使用浏览器 API,因此您必须使用number
作为类型timerID
.
此外,内置函数不应解析其类型node
类型定义,根据您的情况。如果你有@types/node
已安装,如不需要请卸载。这可能与您需要使用的类型相冲突。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)