
Specialized overloading signature
We can use a specialized signature to create multiple methods with the same name and number of parameters, but a different return type. To create a specialized signature, we must indicate the type of function parameter using a string. The string literal is used to identify which of the function overloads is invoked:
interface Document { createElement(tagName: "div"): HTMLDivElement; // specialized createElement(tagName: "span"): HTMLSpanElement; // specialized createElement(tagName: "canvas"): HTMLCanvasElement; // specialized createElement(tagName: string): HTMLElement; // non-specialized }
In the preceding example, we have declared three specialized overloaded signatures and one nonspecialized signature for the function named createElement.
When we declare a specialized signature in an object, it must be assignable to at least one nonspecialized signature in the same object. This can be observed in the preceding example, as the createElement property belongs to a type that contains three specialized signatures, all of which are assignable to the nonspecialized signature in the type.
When writing overloaded declarations, we must list the nonspecialized signature last.