Ordering

Ordering

Don’t put more general overloads before more specific overloads:

1
2
3
4
5
6
7
/* WRONG */
declare function fn(x: any): any;
declare function fn(x: HTMLElement): number;
declare function fn(x: HTMLDivElement): string;
 
var myElem: HTMLDivElement;
var x = fn(myElem); // x: any, wat?

Do sort overloads by putting the more general signatures after more specific signatures:

1
2
3
4
5
6
7
/* OK */
declare function fn(x: HTMLDivElement): string;
declare function fn(x: HTMLElement): number;
declare function fn(x: any): any;
 
var myElem: HTMLDivElement;
var x = fn(myElem); // x: string, :)

Why: TypeScript chooses the first matching overload when resolving function calls. When an earlier overload is “more general” than a later one, the later one is effectively hidden and cannot be called.

doc_TypeScript
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.