Home > other >  Typescript type check on callback
Typescript type check on callback

Time:08-01

I have recently started learning Typescript and ran into this problem that I do not understand conceptually. Is it wrong to define parameter type for this function?

setTimeout((a: string) => {
    console.log(a); // ==> Prints 5 as a number
}, 1, 5);

Why isn't there type checking performed when calling callback?

How would I go about making typescript throw an error?

What are my solutions in general, when encountering something like this?

CodePudding user response:

This is a known bug in TypeScript, see microsoft/TypeScript#32186. The typings for setTimeout() look like

setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;

which accepts any argument list whatsoever, without caring about the types. And TimerHandler is defined as just

type TimerHandler = string | Function

which uses the unsafe and untyped Function type. So setTimeout() is unfortunately very loosely typed in TypeScript. Often in situations like this you could use declaration merging to add better call signatures, but in this case nothing will stop the compiler from falling back to the unsafe call signature.

This is just a limitation in TS, it seems. The issue is listed as being in the "Backlog", so it's not slated to be addressed anytime soon. You could go to microsoft/TypeScript#32186 and give it a

  • Related