microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.42k stars 12.41k forks source link

Fix setTimeout/setInterval/setImmediate functions #19635

Open falsandtru opened 6 years ago

falsandtru commented 6 years ago

Fix too lax typings.

TypeScript Version: master

Expected behavior:

declare function setTimeout(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): number;

Actual behavior:

declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;
declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;
mhegazy commented 6 years ago

I think it allows string too. see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

falsandtru commented 6 years ago

Then this is valid, right?

declare function setTimeout(handler: ((...args: any[]) => void) | string, timeout?: number, ...args: any[]): number;
aluanhaddad commented 6 years ago

Be aware, that if you pass a string it is equivalent to eval.

Douglas Crockford warned of this.

Perhaps this second declaration could go into @RyanCavanaugh's proposed Annex B :wink:

berickson1 commented 5 years ago

Looking at some of the new features that Typescript provides, I'd expect the following to be a better more specific definition

declare function setTimeout<T>(handler: string | ((...args: T[]) => void), timeout?: number , ...params: T[]) => number;

xaviergxf commented 3 years ago

Hi, no news about this?

Jack-Works commented 1 year ago

We hit this problem. TypeScript does not check this code:

function f(x: number) {
  x.toExponential()
}

setTimeout(f, 100)
//         ~ should be an error!