Have a look at this simple example code:
interface EventEmitter<ListenersT>
{
on<EventT extends keyof ListenersT>(event: EventT, listener: ListenersT[EventT]): this;
}
interface MyEvents
{
foo(x: number): void;
bar(): void;
moo(a: string, b: Date): void;
}
interface MyEmitter extends EventEmitter<MyEvents>
{}
const my: MyEmitter = <any> {};
my.on('foo', (x) => x / 4); // Parameter 'x' implicitly has an 'any' type.
my.on('bar', () => 42);
my.on('moo', (a, b) => a + ': ' + b.getFullYear());
I am wondering why in the my.on('foo', ...)
call the compiler fails to infer the type of x
, while it works fine for both arguments in the my.on('moo', ...)
call.
You can go and test this on the Typescript Playground. You can enable the noImplicitAny
flag by pressing the Options button to get the warning I put in the comment or just hover over the x
argument in the code window to see that it failed to infer the number
type.
Bonus: This gets even weirder, if I add another argument to foo()
. In that case it also fails to infer the types for moo
's arguments.
Edit 1
It appears it's only able to infer the types for the function in MyEvents
with the most arguments and only if it's the only one with that amount of arguments.