dark版

Typescript 给setTimeout 的返回值定义为 number出错

let scrollTimer: number = setTimeout(function () {})
// 不能将类型“Timer”分配给类型“number”

通过 cmd + 点击定位,发现setTimeout使用的是 Node.js 下的接口定义
@types/node index.d.ts

declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;

通过yarn.lock定位依赖,发现来源于@types/react-dom

@types/react-dom
dependencies @types/node

而在typescript中,window下的setTimeout返回的是number:

interface WindowTimers extends WindowTimersExtension {
    clearInterval(handle?: number): void;
    clearTimeout(handle?: number): void;
    setInterval(handler: (...args: any[]) => void, timeout: number): number;
    setInterval(handler: any, timeout?: any, ...args: any[]): number;
    setTimeout(handler: (...args: any[]) => void, timeout: number): number;
    setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}

解决:

  • 移除对@type/node的依赖(不太可行)
  • 使用window.setTimeout
let scrollTimer: number = window.setTimeout(function () {})

来源:https://github.com/TypeStrong/atom-typescript/issues/1053