Overloads and Callbacks

Overloads and Callbacks

Don’t write separate overloads that differ only on callback arity:

/* WRONG */
declare function beforeAll(action: () => void, timeout?: number): void;
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;

Do write a single overload using the maximum arity:

/* OK */
declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;

Why: It’s always legal for a callback to disregard a parameter, so there’s no need for the shorter overload. Providing a shorter callback first allows incorrectly-typed functions to be passed in because they match the first overload.

doc_TypeScript
2016-10-04 19:25:29
Comments
Leave a Comment

Please login to continue.