function on(event: string, listener: Function) {
console.log('on event: ', event, 'typeof listener:', typeof (listener));
listener();
}
function on1(event: string, listener: (...args: any[]) => void) {
console.log('on event: ', event, 'typeof listener:', typeof (listener));
listener();
}
function createCallback(a: number): Function {
let f = (a: number) => {
console.log('return a:', a);
return (a: number) => { return a + 1 };
};
return f(a);
}
let f = createCallback(1);
console.log('type of f', typeof (f));
// on("start", f);
on1("start", f);
In the above code, on("start", f)
works fine but on1("start", f);
returns error
main.ts:22:14 - error TS2345: Argument of type 'Function' is not assignable to parameter of type '(...args: any[]) => void'. Type 'Function' provides no match for the signature '(...args: any[]): void'. 22 on1("start", f); ~
If I remove the Function
type assertion of createCallback
, on1("start", f)
works, isn't Function
a general type to represent closures?
The original question comes from this commit, https://github.com/DefinitelyTyped/DefinitelyTyped/commit/96545154cc6488643a7064a6dc4ec9726c7af12a#diff-7d84e08967cded0b99ed4328aab0a1a8L291
I don't understand why he changes Function
to (...args: any[]) => void
which makes my code break.
on1
requires a more specific type. Just likeAny
is a general type, and can’t be bound to a more specific type (but can itself bind anything). – Konrad Rudolph