“TS2322:“超时"类型不可分配给“数字"类型"运行单元测试时 [英] "TS2322: Type 'Timeout' is not assignable to type 'number'" when running unit tests

查看:111
本文介绍了“TS2322:“超时"类型不可分配给“数字"类型"运行单元测试时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 TypeScript 包,一个包(包 A)依赖于另一个(包 B).每个包都有一个使用 Karma 设置的单元测试.从 NPM 安装所有依赖项后,当我为每个单独运行单元测试时,单元测试运行良好.但是,如果我在包 A 中使用 npm link package-b 并运行包 A 的单元测试,那么我会收到标题中所述的错误:TS2322: Type 'Timeout' is notassignable to type '号码'."

I have two TypeScript packages, and one package (Package A) depends on the other (Package B). Each package has a unit test set up using Karma. When I run unit tests for each individually after installing all dependencies from NPM, the unit tests run fine. However, if I use npm link package-b in Package A and run Package A's unit tests then, I get the error stated in the title: "TS2322: Type 'Timeout' is not assignable to type 'number'."

有问题的行是对 setTimeout 的调用.经过挖掘,我发现在没有 npm link 的情况下单独运行测试时,TypeScript 正确识别了 typescript/lib/lib.dom 中的 setTimeout 签名作为所需的类型,但在使用 npm link 后失败的情况下,它在 @types/node/index 中使用 Node 的 setTimeout 签名.我通过将 setTimeout 上的返回类型更改为 string 并用 string 代替 Timeout 观察到相同的错误来确认这一点代码>.

The line in question is a call to setTimeout. After digging, I found that while running the tests separately without npm link, TypeScript correctly identifies the setTimeout signature in typescript/lib/lib.dom as the desired type, but in the failing case after using npm link it is using using Node's setTimeout signature in @types/node/index. I confirmed this by changing the return type on setTimeout to string and observing the same error with string in the place of Timeout.

我不确定的是为什么 TypeScript 编译器决定在这种特定情况下使用替代定义,以及我如何说服它使用所需的定义.我很高兴发布一些代码,但我不确定在这种情况下什么会有用,因为失败的行是 setTimeout 调用.

What I am not certain of is why the TypeScript compiler has decided to use the alternative definition in this specific case, nor how I can convince it to use the desired definition. I am happy to post some code, but I am not sure what would be useful in this case given all that is on the failing line is the setTimeout call.

推荐答案

您可以尝试使用 window.setTimeout 而不是 setTimeout,这样可以显式使用 typescript

You could try with using window.setTimeout instead of just setTimeout, this way the typescript one will be explicitly used

这篇关于“TS2322:“超时"类型不可分配给“数字"类型"运行单元测试时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆