考虑以下代码:
const timer: number = setTimeout(() => '', 1000);
Run Code Online (Sandbox Code Playgroud)
Typescript会抛出错误:Type 'Timer' is not assignable to type 'number'.
快速查找告诉我setTimeout
返回NodeJS.Timer
.
但是,如果我正在进行基于浏览器的开发,使用NodeJS.Timer
感觉不对.哪个是正确的类型定义或返回类型,setTimeout
无需借助any
声明即可完成工作?
Tit*_*mir 29
最简单的解决方案是允许类型推断工作,而根本不指定任何类型.如果需要指定类型,看到浏览器和节点声明之间的类型不一致,您可以使用ReturnType
指定变量的类型setTimeout
是返回类型的类型:
const timer: ReturnType<typeof setTimeout> = setTimeout(() => '', 1000);
Run Code Online (Sandbox Code Playgroud)
或者,window.setTimeout
也可以使用而不仅仅是setTimeout
.它返回正确的返回类型.
And*_*kyi 10
您可以使用window.setTimeout
它返回的类型number
。
let a: number;
a = window.setTimeout(function() {}, 0);
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为 Typescript 将在下面搜索类型定义 node_modules/@types
如果您将 NodeJS 类型定义(带有许多 npm 包)安装到~/node_modules/@types/node/globals.ts
并且您的项目在~/Projects/myproject
定义中,则会泄漏。
默认情况下,所有可见的“@types”包都包含在您的编译中。任何封闭文件夹的 node_modules/@types 中的包都被认为是可见的;具体来说,这意味着 ./node_modules/@types/、../node_modules/@types/、../../node_modules/@types/ 等中的包。
请参阅:https : //www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types
如果 Typescript 找到自定义类型定义,则其优先于默认类型定义。
解决方案:
"typeRoots":[]
"types": []
归档时间: |
|
查看次数: |
6773 次 |
最近记录: |