eslint-plugin-unicorn: `prefer-global-this` should allow `window.setTimeout()` and `setInterval()`

Description

as it’s a common workaround: 1, 2, for globalThis.setTimeout() and setInterval() returning NodeJS.Timeout in @types/node

Fail

const id: number = window.setTimeout(console.log, 100);
//                 ^^^^^^
// Prefer `globalThis` over `window`. eslint(unicorn/prefer-global-this)

Pass

const id: number = window.setTimeout(console.log, 100);
const id: NodeJS.Timeout | number = globalThis.setTimeout(console.log, 100);

Additional Info

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 17 (1 by maintainers)

Commits related to this issue

Most upvoted comments

window.setTimeout is the one for browser enviorment.

That’s completely irrelevant. This is a type-only issue, window === globalThis in real life.

I’m closing this for now because the discussion is going nowhere. This is a documentation issue/misunderstanding. I’ll open a dedicated issue to improve the DX as described earlier

Indeed, I ran in to no-var as well today.😂 Yeah let’s do a separate issue for those things, I’ll just eslint-disable for now.

@n0099 Yes I do understand Web API and Node.js API and that’s exactly why I’m here. I still think using window.setTimeout is the most clear way, but anyways.

Yes it will work if the only usage is for clearInterval. However my function here requires a number type. image Guess I need to change number to ReturnType<typeof setTimeout>, but that’s just so weird🫠

I’ve tried all the different combinations, it will always default to Node.js’s version🫠 eslint-disable for now I guess image image image

I disagree. The correct way to handle it is:

const id: ReturnType<typeof setTimeout> = window.setTimeout(console.log, 100);

It won’t work. It will always default to NodeJS’s version unless you explicitly specify window.setXxx image image

You don’t need any of that. Just call setTimeout normally.

As for the let, the lint rule is right. This is correct:

let id: ReturnType<typeof setTimeout> | undefined;

// and then

id = setTimeout()
clearTimeout(id)

I disagree. The correct way to handle it is:

const id: ReturnType<typeof setTimeout> = window.setTimeout(console.log, 100);