1.8 Overloading on String Parameters

An important goal of TypeScript is to provide accurate and straightforward types for existing JavaScript programming patterns. To that end, TypeScript includes generic types, discussed in the next section, and overloading on string parameters, the topic of this section.

JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screenshot shows that the ‘createElement’ method of the ‘document’ object has multiple signatures, some of which identify the types returned when specific strings are passed into the method.

  1.8 Overloading on String Parameters - 图1

The following code fragment uses this feature. Because the ‘span’ variable is inferred to have the type ‘HTMLSpanElement’, the code can reference without static error the ‘isMultiline’ property of ‘span’.

  1. var span = document.createElement("span");
  2. span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property

In the following screenshot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable ‘e’ is ‘MouseEvent’ and that therefore ‘e’ has a ‘clientX’ property.

  1.8 Overloading on String Parameters - 图2

Section 3.9.2.4 provides details on how to use string literals in function signatures.