23.06.2015 Views

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

TypeScript Language Specification v1.5

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Section 9 describes how programmers can also explicitly assign integers to enum members, and can use<br />

any string to name an enum member.<br />

If all enum members have explicitly assigned literal integers, or if an enum has all members automatically<br />

assigned, the <strong>TypeScript</strong> compiler will emit for an enum member a JavaScript constant corresponding to<br />

that member's assigned value (annotated with a comment). This improves performance on many<br />

JavaScript engines.<br />

For example, the 'compute' function could contain a switch statement like the following.<br />

switch (op) {<br />

case Operator.ADD:<br />

// execute add<br />

break;<br />

case Operator.DIV:<br />

// execute div<br />

break;<br />

// ...<br />

}<br />

For this switch statement, the compiler will generate the following code.<br />

switch (op) {<br />

case 0 /* Operator.ADD */:<br />

// execute add<br />

break;<br />

case 1 /* Operator.DIV */:<br />

// execute div<br />

break;<br />

// ...<br />

}<br />

JavaScript implementations can use these explicit constants to generate efficient code for this switch<br />

statement, for example by building a jump table indexed by case value.<br />

1.8 Overloading on String Parameters<br />

An important goal of <strong>TypeScript</strong> is to provide accurate and straightforward types for existing JavaScript<br />

programming patterns. To that end, <strong>TypeScript</strong> includes generic types, discussed in the next section, and<br />

overloading on string parameters, the topic of this section.<br />

JavaScript programming interfaces often include functions whose behavior is discriminated by a string<br />

constant passed to the function. The Document Object Model makes heavy use of this pattern. For<br />

example, the following screen shot shows that the 'createElement' method of the 'document' object has<br />

multiple signatures, some of which identify the types returned when specific strings are passed into the<br />

method.<br />

11

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!