Type 'Timeout' is not assignable to type 'number' 解决

在 TypeScript 中,如果你在一个项目中同时使用 Node.js 和浏览器环境,你可能会遇到 setTimeout 返回值类型不兼容的问题。特别是当你在 Node.js 环境中使用 setTimeout 时,返回一个 Timeout 对象,而在浏览器环境中返回一个 number

要解决这个问题,可以使用条件类型或者类型断言来处理 setTimeout 返回的标识符。以下是几种常见的解决方案:

1. 使用联合类型

使用联合类型来声明 setTimeout 返回的标识符:

let timeoutId: number | NodeJS.Timeout;

timeoutId = setTimeout(() => {
  console.log("This will run after 1 second.");
}, 1000);

2. 指定浏览器 setTimeout

let timeoutId: number;

timeoutId = window.setTimeout(() => {
  console.log("This will run after 1 second.");
}, 1000);

3. 使用类型断言

// 在浏览器环境中
const timeoutId = setTimeout(() => {
  console.log("This will run after 1 second.");
}, 1000) as number;

// 在 Node.js 环境中
const timeoutId = setTimeout(() => {
  console.log("This will run after 1 second.");
}, 1000) as NodeJS.Timeout;
PS:写作不易,如要转裁,请标明转载出处。
%{ comment.page.total }条评论

微信小程序:前端开发宝典

相关笔记
工具操作
  • 内容截图
  • 全屏
登录
注册
回顶部