2.7 Specialized overloading signature

As we learned in the previous recipe, we can use an overloaded signature to invoke a function with different sets of parameters but the function’s name and return type remain the same. We can use a specialized overloading signature to create functions with the same name and parameters but different return type.

Getting Ready

All you need to be able to use specialized overloading signatures is an installation of TypeScript 2.0 or higher.

How to do it…

Let’s imagine that you have the following function:

function createElement(tagName: string): (HTMLDivElement | HTMLSpanElement | HTMLCanvasElement) {
      switch(tagName) {
        case 'div': return new HTMLDivElement();
        case 'span': return new HTMLDivElement();
        case 'canvas': return new HTMLDivElement();
      }
  }

The function above is actually how the Document.createElement method from the DOM API behaves let’s take a quick look to its interface:

interface Document {
    createElement(tagName: 'div'): HTMLDivElement;
    createElement(tagName: 'span'): HTMLSpanElement;
    createElement(tagName: 'canvas'): HTMLCanvasElement;
    createElement(tagName: string): HTMLElement;
  }

How it works…

The interface declaration above uses specialized overloading signatures to be able to define the behavior of one of the core functions of the DOM API. This allows the TypeScript compiler to identify the type of the return type of a function based on the value (not the type) of one of its arguments:

const document: Document = <Document>{};
const elm1 = document.createElement('div'); // HTMLDivElement
const elm2 = document.createElement('span'); // HTMLSpanElement

Source Code

Specialized overloading signature

See also

When we used a string to specify the types of the variable named tagName we were using a string literal type but we omitted that detail to reduce the complexity of this example. Please refer to the recipe about string literal types in this chapter to learn more about them.


Shiv Kushwaha

Author/Programmer