diff --git a/Jakefile b/Jakefile index da91239d7a589..c66900b68d6d3 100644 --- a/Jakefile +++ b/Jakefile @@ -294,7 +294,7 @@ compileFile(word2mdJs, file(specMd, [word2mdJs, specWord], function () { jake.cpR(headerMd, specMd, {silent: true}); var specWordFullPath = path.resolve(specWord); - var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" >>' + specMd; + var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + specMd; console.log(cmd); child_process.exec(cmd, function () { complete(); diff --git a/doc/TypeScript Language Specification.docx b/doc/TypeScript Language Specification.docx index 18ce8396a5b58..93536e02aee59 100644 Binary files a/doc/TypeScript Language Specification.docx and b/doc/TypeScript Language Specification.docx differ diff --git a/doc/TypeScript Language Specification.pdf b/doc/TypeScript Language Specification.pdf index 4d483ed4e55fa..4a122d9e1486e 100644 Binary files a/doc/TypeScript Language Specification.pdf and b/doc/TypeScript Language Specification.pdf differ diff --git a/doc/spec.md b/doc/spec.md index 0a802bd868577..0f26275eb3a61 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -6,7 +6,7 @@ October, 2014
-Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 (“OWF 1.0”) as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0. +Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0. TypeScript is a trademark of Microsoft Corporation. @@ -103,13 +103,13 @@ TypeScript is a trademark of Microsoft Corporation. * [4.13 Type Assertions](#4.13) * [4.14 Unary Operators](#4.14) * [4.14.1 The ++ and -- operators](#4.14.1) - * [4.14.2 The +, –, and ~ operators](#4.14.2) + * [4.14.2 The +, –, and ~ operators](#4.14.2) * [4.14.3 The ! operator](#4.14.3) * [4.14.4 The delete Operator](#4.14.4) * [4.14.5 The void Operator](#4.14.5) * [4.14.6 The typeof Operator](#4.14.6) * [4.15 Binary Operators](#4.15) - * [4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.15.1) + * [4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.15.1) * [4.15.2 The + operator](#4.15.2) * [4.15.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.15.3) * [4.15.4 The instanceof operator](#4.15.4) @@ -212,7 +212,7 @@ TypeScript is a trademark of Microsoft Corporation. # 1 Introduction -JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript’s optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring. +JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring. TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of Ecmascript 5 (ES5) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development. @@ -220,7 +220,7 @@ TypeScript syntax includes several proposed features of Ecmascript 6 (ES6), incl TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables. -The TypeScript type system enables programmers to express limits on the capabilities of JavaScript objects, and to use tools that enforce these limits. To minimize the number of annotations needed for tools to become useful, the TypeScript type system makes extensive use of type inference. For example, from the following statement, TypeScript will infer that the variable ‘i’ has the type number. +The TypeScript type system enables programmers to express limits on the capabilities of JavaScript objects, and to use tools that enforce these limits. To minimize the number of annotations needed for tools to become useful, the TypeScript type system makes extensive use of type inference. For example, from the following statement, TypeScript will infer that the variable 'i' has the type number. ```TypeScript var i = 0; @@ -249,7 +249,7 @@ f({}); // Error f("hello"); // Ok ``` -This optional type annotation on the parameter ‘s’ lets the TypeScript type checker know that the programmer expects parameter ‘s’ to be of type ‘string’. Within the body of function ‘f’, tools can assume ‘s’ is of type ‘string’ and provide operator type checking and member completion consistent with this assumption. Tools can also signal an error on the first call to ‘f’, because ‘f’ expects a string, not an object, as its parameter. For the function ‘f’, the TypeScript compiler will emit the following JavaScript code: +This optional type annotation on the parameter 's' lets the TypeScript type checker know that the programmer expects parameter 's' to be of type 'string'. Within the body of function 'f', tools can assume 's' is of type 'string' and provide operator type checking and member completion consistent with this assumption. Tools can also signal an error on the first call to 'f', because 'f' expects a string, not an object, as its parameter. For the function 'f', the TypeScript compiler will emit the following JavaScript code: ```TypeScript function f(s) { @@ -261,14 +261,14 @@ In the JavaScript output, all type annotations have been erased. In general, Typ ## 1.1 Ambient Declarations -An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations. The following example declares the ‘document’ object supplied by browsers. Because the declaration does not specify a type, the type ‘any’ is inferred. The type ‘any’ means that a tool can assume nothing about the shape or behavior of the document object. Some of the examples below will illustrate how programmers can use types to further characterize the expected behavior of an object. +An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations. The following example declares the 'document' object supplied by browsers. Because the declaration does not specify a type, the type 'any' is inferred. The type 'any' means that a tool can assume nothing about the shape or behavior of the document object. Some of the examples below will illustrate how programmers can use types to further characterize the expected behavior of an object. ```TypeScript declare var document; document.title = "Hello"; // Ok because document has been declared ``` -In the case of ‘document’, the TypeScript compiler automatically supplies a declaration, because TypeScript by default includes a file ‘lib.d.ts’ that provides interface declarations for the built-in JavaScript library as well as the Document Object Model. +In the case of 'document', the TypeScript compiler automatically supplies a declaration, because TypeScript by default includes a file 'lib.d.ts' that provides interface declarations for the built-in JavaScript library as well as the Document Object Model. The TypeScript compiler does not include by default an interface for jQuery, so to use jQuery, a programmer could supply a declaration such as: @@ -280,7 +280,7 @@ Section [1.3](#1.3) provides a more extensive example of how a programmer can ad ## 1.2 Function Types -Function expressions are a powerful feature of JavaScript. They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function’s definition. Closures are currently JavaScript’s only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function. +Function expressions are a powerful feature of JavaScript. They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function's definition. Closures are currently JavaScript's only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function. TypeScript function types make it possible for programmers to express the expected *signature* of a function. A function signature is a sequence of parameter types plus a return type. The following example uses function types to express the callback signature requirements of an asynchronous voting mechanism. @@ -298,19 +298,19 @@ vote("BigPig", ); ``` -In this example, the second parameter to ‘vote’ has the function type +In this example, the second parameter to 'vote' has the function type ```TypeScript (result: string) => any ``` -which means the second parameter is a function returning type ‘any’ that has a single parameter of type ‘string’ named ‘result’. +which means the second parameter is a function returning type 'any' that has a single parameter of type 'string' named 'result'. Section [3.7.2](#3.7.2) provides additional information about function types. ## 1.3 Object Types -TypeScript programmers use *object types* to declare their expectations of object behavior. The following code uses an *object type literal* to specify the return type of the ‘MakePoint’ function. +TypeScript programmers use *object types* to declare their expectations of object behavior. The following code uses an *object type literal* to specify the return type of the 'MakePoint' function. ```TypeScript var MakePoint: () => { @@ -335,7 +335,7 @@ add({ favoriteColor: "blue" }); // Error, name required add({ name: "Jill", favoriteColor: "green" }); // Ok ``` -TypeScript object types model the diversity of behaviors that a JavaScript object can exhibit. For example, the jQuery library defines an object, ‘$’, that has methods, such as ‘get’ (which sends an Ajax message), and fields, such as ‘browser’ (which gives browser vendor information). However, jQuery clients can also call ‘$’ as a function. The behavior of this function depends on the type of parameters passed to the function. +TypeScript object types model the diversity of behaviors that a JavaScript object can exhibit. For example, the jQuery library defines an object, '$', that has methods, such as 'get' (which sends an Ajax message), and fields, such as 'browser' (which gives browser vendor information). However, jQuery clients can also call '$' as a function. The behavior of this function depends on the type of parameters passed to the function. The following code fragment captures a small subset of jQuery behavior, just enough to use jQuery in a simple way. @@ -358,9 +358,9 @@ $.get("http://mysite.org/divContent", ); ``` -The ‘JQueryStatic’ interface references another interface: ‘JQuery’. This interface represents a collection of one or more DOM elements. The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the ‘text’ method. The ‘JQueryStatic’ interface also contains a method, ‘get’, that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response. +The 'JQueryStatic' interface references another interface: 'JQuery'. This interface represents a collection of one or more DOM elements. The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the 'text' method. The 'JQueryStatic' interface also contains a method, 'get', that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response. -Finally, the ‘JQueryStatic’ interface contains a bare function signature +Finally, the 'JQueryStatic' interface contains a bare function signature ```TypeScript (query: string): JQuery; @@ -374,13 +374,13 @@ var sameType: () => string = f; // Ok var nope: () => number = sameType; // Error: type mismatch ``` -We mentioned above that the ‘$’ function behaves differently depending on the type of its parameter. So far, our jQuery typing only captures one of these behaviors: return an object of type ‘JQuery’ when passed a string. To specify multiple behaviors, TypeScript supports *overloading* of function signatures in object types. For example, we can add an additional call signature to the ‘JQueryStatic’ interface. +We mentioned above that the '$' function behaves differently depending on the type of its parameter. So far, our jQuery typing only captures one of these behaviors: return an object of type 'JQuery' when passed a string. To specify multiple behaviors, TypeScript supports *overloading* of function signatures in object types. For example, we can add an additional call signature to the 'JQueryStatic' interface. ```TypeScript (ready: () => any): any; ``` -This signature denotes that a function may be passed as the parameter of the ‘$’ function. When a function is passed to ‘$’, the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature. +This signature denotes that a function may be passed as the parameter of the '$' function. When a function is passed to '$', the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature. A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot. @@ -390,7 +390,7 @@ Section [3.3](#3.3) provides additional information about object types. ## 1.4 Structural Subtyping -Object types are compared *structurally*. For example, in the code fragment below, class ‘CPoint’ matches interface ‘Point’ because ‘CPoint’ has all of the required members of ‘Point’. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members. +Object types are compared *structurally*. For example, in the code fragment below, class 'CPoint' matches interface 'Point' because 'CPoint' has all of the required members of 'Point'. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members. ```TypeScript interface Point { @@ -422,7 +422,7 @@ See section [3.8](#3.8) for more information about type comparisons. ## 1.5 Contextual Typing -Ordinarily, TypeScript type inference proceeds “bottom-up”: from the leaves of an expression tree to its root. In the following example, TypeScript infers ‘number’ as the return type of the function ‘mul’ by flowing type information bottom up in the return expression. +Ordinarily, TypeScript type inference proceeds "bottom-up": from the leaves of an expression tree to its root. In the following example, TypeScript infers 'number' as the return type of the function 'mul' by flowing type information bottom up in the return expression. ```TypeScript function mul(a: number, b: number) { @@ -430,9 +430,9 @@ function mul(a: number, b: number) { } ``` -For variables and parameters without a type annotation or a default value, TypeScript infers type ‘any’, ensuring that compilers do not need non-local information about a function’s call sites to infer the function’s return type. Generally, this bottom-up approach provides programmers with a clear intuition about the flow of type information. +For variables and parameters without a type annotation or a default value, TypeScript infers type 'any', ensuring that compilers do not need non-local information about a function's call sites to infer the function's return type. Generally, this bottom-up approach provides programmers with a clear intuition about the flow of type information. -However, in some limited contexts, inference proceeds “top-down” from the context of an expression. Where this happens, it is called contextual typing. Contextual typing helps tools provide excellent information when a programmer is using a type but may not know all of the details of the type. For example, in the jQuery example, above, the programmer supplies a function expression as the second parameter to the ‘get’ method. During typing of that expression, tools can assume that the type of the function expression is as given in the ‘get’ signature and can provide a template that includes parameter names and types. +However, in some limited contexts, inference proceeds "top-down" from the context of an expression. Where this happens, it is called contextual typing. Contextual typing helps tools provide excellent information when a programmer is using a type but may not know all of the details of the type. For example, in the jQuery example, above, the programmer supplies a function expression as the second parameter to the 'get' method. During typing of that expression, tools can assume that the type of the function expression is as given in the 'get' signature and can provide a template that includes parameter names and types. ```TypeScript $.get("http://mysite.org/divContent", @@ -448,9 +448,9 @@ Section [4.19](#4.19) provides additional information about contextually typed e ## 1.6 Classes -JavaScript practice has at least two common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as ‘prototype.js’ are typical of this practice. +JavaScript practice has at least two common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. -This section and the module section below will show how TypeScript emits consistent, idiomatic JavaScript code to implement classes and modules that are closely aligned with the current ES6 proposal. The goal of TypeScript’s translation is to emit exactly what a programmer would type when implementing a class or module unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We’ll start with a simple BankAccount class. +This section and the module section below will show how TypeScript emits consistent, idiomatic JavaScript code to implement classes and modules that are closely aligned with the current ES6 proposal. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or module unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class. ```TypeScript class BankAccount { @@ -477,7 +477,7 @@ var BankAccount = (function () { })(); ``` -This TypeScript class declaration creates a variable named ‘BankAccount’ whose value is the constructor function for ‘BankAccount’ instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following. +This TypeScript class declaration creates a variable named 'BankAccount' whose value is the constructor function for 'BankAccount' instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following. ```TypeScript interface BankAccount { @@ -486,15 +486,15 @@ interface BankAccount { } ``` -If we were to write out the function type declaration for the ‘BankAccount’ constructor variable, it would have the following form. +If we were to write out the function type declaration for the 'BankAccount' constructor variable, it would have the following form. ```TypeScript var BankAccount: new() => BankAccount; ``` -The function signature is prefixed with the keyword ‘new’ indicating that the ‘BankAccount’ function must be called as a constructor. It is possible for a function’s type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures. +The function signature is prefixed with the keyword 'new' indicating that the 'BankAccount' function must be called as a constructor. It is possible for a function's type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures. -If we want to start our bank account with an initial balance, we can add to the ‘BankAccount’ class a constructor declaration. +If we want to start our bank account with an initial balance, we can add to the 'BankAccount' class a constructor declaration. ```TypeScript class BankAccount { @@ -509,7 +509,7 @@ class BankAccount { } ``` -This version of the ‘BankAccount’ class requires us to introduce a constructor parameter and then assign it to the ‘balance’ field. To simplify this common case, TypeScript accepts the following shorthand syntax. +This version of the 'BankAccount' class requires us to introduce a constructor parameter and then assign it to the 'balance' field. To simplify this common case, TypeScript accepts the following shorthand syntax. ```TypeScript class BankAccount { @@ -522,7 +522,7 @@ class BankAccount { } ``` -The ‘public’ keyword denotes that the constructor parameter is to be retained as a field. Public is the default accessibility for class members, but a programmer can also specify private or protected accessibility for a class member. Accessibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement. +The 'public' keyword denotes that the constructor parameter is to be retained as a field. Public is the default accessibility for class members, but a programmer can also specify private or protected accessibility for a class member. Accessibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement. TypeScript classes also support inheritance, as in the following example.* * @@ -537,7 +537,7 @@ class CheckingAccount extends BankAccount { } ``` -In this example, the class ‘CheckingAccount’ *derives* from class ‘BankAccount’. The constructor for ‘CheckingAccount’ calls the constructor for class ‘BankAccount’ using the ‘super’ keyword. In the emitted JavaScript code, the prototype of ‘CheckingAccount’ will chain to the prototype of ‘BankingAccount’. +In this example, the class 'CheckingAccount' *derives* from class 'BankAccount'. The constructor for 'CheckingAccount' calls the constructor for class 'BankAccount' using the 'super' keyword. In the emitted JavaScript code, the prototype of 'CheckingAccount' will chain to the prototype of 'BankingAccount'. TypeScript classes may also specify static members. Static class members become properties of the class constructor. @@ -561,11 +561,11 @@ function compute(op: Operator, a: number, b: number) { } ``` -In this example, the compute function logs the operator ‘op’ using a feature of enum types: reverse mapping from the enum value (‘op’) to the string corresponding to that value. For example, the declaration of ‘Operator’ automatically assigns integers, starting from zero, to the listed enum members. Section [9](#9) describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member. +In this example, the compute function logs the operator 'op' using a feature of enum types: reverse mapping from the enum value ('op') to the string corresponding to that value. For example, the declaration of 'Operator' automatically assigns integers, starting from zero, to the listed enum members. Section [9](#9) describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member. -If all enum members have explicitly assigned literal integers, or if an enum has all members automatically assigned, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member’s assigned value (annotated with a comment). This improves performance on many JavaScript engines. +If all enum members have explicitly assigned literal integers, or if an enum has all members automatically assigned, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member's assigned value (annotated with a comment). This improves performance on many JavaScript engines. -For example, the ‘compute’ function could contain a switch statement like the following. +For example, the 'compute' function could contain a switch statement like the following. ```TypeScript switch (op) { @@ -599,18 +599,18 @@ JavaScript implementations can use these explicit constants to generate efficien 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 screen shot 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. +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 screen shot 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. / -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’. +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'. ```TypeScript var span = document.createElement("span"); span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property ``` -In the following screen shot, 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. +In the following screen shot, 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. / @@ -620,7 +620,7 @@ Section [3.7.2.4](#3.7.2.4) provides details on how to use string literals in fu Like overloading on string parameters, *generic types* make it easier for TypeScript to accurately capture the behavior of JavaScript libraries. Because they enable type information to flow from client code, through library code, and back into client code, generic types may do more than any other TypeScript feature to support detailed API descriptions. -To illustrate this, let’s take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the ‘lib.d.ts’ file that accompanies a TypeScript distribution. +To illustrate this, let's take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the 'lib.d.ts' file that accompanies a TypeScript distribution. ```TypeScript interface Array { @@ -630,17 +630,17 @@ interface Array { } ``` -Interface definitions, like the one above, can have one or more *type parameters*. In this case the ‘Array’ interface has a single parameter, ‘T’, that defines the element type for the array. The ‘reverse’ method returns an array with the same element type. The sort method takes an optional parameter, ‘compareFn’, whose type is a function that takes two parameters of type ‘T’ and returns a number. Finally, sort returns an array with element type ‘T’. +Interface definitions, like the one above, can have one or more *type parameters*. In this case the 'Array' interface has a single parameter, 'T', that defines the element type for the array. The 'reverse' method returns an array with the same element type. The sort method takes an optional parameter, 'compareFn', whose type is a function that takes two parameters of type 'T' and returns a number. Finally, sort returns an array with element type 'T'. -Functions can also have generic parameters. For example, the array interface contains a ‘map’ method, defined as follows: +Functions can also have generic parameters. For example, the array interface contains a 'map' method, defined as follows: ```TypeScript map(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; ``` -The map method, invoked on an array ‘a’ with element type ‘T’, will apply function ‘func’ to each element of ‘a’, returning a value of type ‘U’. +The map method, invoked on an array 'a' with element type 'T', will apply function 'func' to each element of 'a', returning a value of type 'U'. -The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter ‘U’ of the map method has type ‘string’, because the function passed to map returns a string. +The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter 'U' of the map method has type 'string', because the function passed to map returns a string. ```TypeScript function numberToString(a: number[]) { @@ -649,9 +649,9 @@ function numberToString(a: number[]) { } ``` -The compiler infers in this example that the ‘numberToString’ function returns an array of strings. +The compiler infers in this example that the 'numberToString' function returns an array of strings. -In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type ‘T’. This code illustrates how programmers can *constrain* type parameters to extend a specific type. In this case, the items on the list must extend the type ‘NamedItem’. This enables the programmer to implement the ‘log’ function, which logs the name of the item. +In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type 'T'. This code illustrates how programmers can *constrain* type parameters to extend a specific type. In this case, the items on the list must extend the type 'NamedItem'. This enables the programmer to implement the 'log' function, which logs the name of the item. ```TypeScript interface NamedItem { @@ -682,7 +682,7 @@ Section [3.5](#3.5) provides further information about generic types. ## 1.10 Modules -Classes and interfaces support large-scale JavaScript development by providing a mechanism for describing how to use a software component that can be separated from that component’s implementation. TypeScript enforces *encapsulation* of implementation in classes at design time (by restricting use of private and protected members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide *private names* which would enable runtime enforcement of private and protected members. +Classes and interfaces support large-scale JavaScript development by providing a mechanism for describing how to use a software component that can be separated from that component's implementation. TypeScript enforces *encapsulation* of implementation in classes at design time (by restricting use of private and protected members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide *private names* which would enable runtime enforcement of private and protected members. In the current version of JavaScript, the only way to enforce encapsulation at runtime is to use the module pattern: encapsulate private fields and methods using closure variables. The module pattern is a natural way to provide organizational structure and dynamic loading options by drawing a boundary around a software component. A module can also provide the ability to introduce namespaces, avoiding use of the global namespace for most software components. @@ -698,9 +698,9 @@ The following example illustrates the JavaScript module pattern. })(MessageModule); ``` -This example illustrates the two essential elements of the module pattern: a *module closure* and a *module* *object*. The module closure is a function that encapsulates the module’s implementation, in this case the variable ‘key’ and the function ‘sendMessage’. The module object contains the exported variables and functions of the module. Simple modules may create and return the module object. The module above takes the module object as a parameter, ‘exports’, and adds the ‘sendMessage’ property to the module object. This *augmentation* approach simplifies dynamic loading of modules and also supports separation of module code into multiple files. +This example illustrates the two essential elements of the module pattern: a *module closure* and a *module* *object*. The module closure is a function that encapsulates the module's implementation, in this case the variable 'key' and the function 'sendMessage'. The module object contains the exported variables and functions of the module. Simple modules may create and return the module object. The module above takes the module object as a parameter, 'exports', and adds the 'sendMessage' property to the module object. This *augmentation* approach simplifies dynamic loading of modules and also supports separation of module code into multiple files. -The example assumes that an outer lexical scope defines the functions ‘generateSecretKey’ and ‘sendSecureMessage’; it also assumes that the outer scope has assigned the module object to the variable ‘MessageModule’. +The example assumes that an outer lexical scope defines the functions 'generateSecretKey' and 'sendSecureMessage'; it also assumes that the outer scope has assigned the module object to the variable 'MessageModule'. TypeScript modules provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting modules and classes within an outer module. @@ -718,7 +718,7 @@ M.f(); M.s; // Error, s is not exported ``` -In this example, variable ‘s’ is a private feature of the module, but function ‘f’ is exported from the module and accessible to code outside of the module. If we were to describe the effect of module ‘M’ in terms of interfaces and variables, we would write +In this example, variable 's' is a private feature of the module, but function 'f' is exported from the module and accessible to code outside of the module. If we were to describe the effect of module 'M' in terms of interfaces and variables, we would write ```TypeScript interface M { @@ -728,9 +728,9 @@ interface M { var M: M; ``` -The interface ‘M’ summarizes the externally visible behavior of module ‘M’. In this example, we can use the same name for the interface as for the initialized variable because in TypeScript type names and variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see section [2.3](#2.3) for more details). +The interface 'M' summarizes the externally visible behavior of module 'M'. In this example, we can use the same name for the interface as for the initialized variable because in TypeScript type names and variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see section [2.3](#2.3) for more details). -Module ‘M’ is an example of an *internal* module, because it is nested within the *global* module (see section [10](#10) for more details). The TypeScript compiler emits the following JavaScript code for this module. +Module 'M' is an example of an *internal* module, because it is nested within the *global* module (see section [10](#10) for more details). The TypeScript compiler emits the following JavaScript code for this module. ```TypeScript var M; @@ -743,7 +743,7 @@ var M; })(M || (M = {})); ``` -In this case, the compiler assumes that the module object resides in global variable ‘M’, which may or may not have been initialized to the desired module object. +In this case, the compiler assumes that the module object resides in global variable 'M', which may or may not have been initialized to the desired module object. TypeScript also supports *external* modules, which are files that contain top-level *export* and *import *directives. For this type of module the TypeScript compiler will emit code whose module closure and module object implementation vary according to the specified dynamic loading system, for example, the Asynchronous Module Definition system. @@ -758,13 +758,13 @@ The remainder of this document is the formal specification of the TypeScript pro The syntactic grammar added by TypeScript language is specified throughout this document using the existing conventions and production names of the ECMAScript grammar. In places where TypeScript augments an existing grammar production it is so noted. For example:   *CallExpression:* *( Modified )* -   … +   …    `super` `(` *ArgumentListopt* `)`    `super` `.` *IdentifierName* -The ‘*( Modified )*’ annotation indicates that an existing grammar production is being replaced, and the ‘…’ references the contents of the original grammar production. +The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production. -Similar to the ECMAScript grammar, if the phrase “*[no LineTerminator here]*” appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position. +Similar to the ECMAScript grammar, if the phrase "*[no LineTerminator here]*" appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position. ## 2.2 Namespaces and Named Types @@ -779,7 +779,7 @@ module X { } ``` -declares two interface types with the qualified names ‘X.Y.Z’ and ‘X.Y’ relative to the root module in which ‘X’ is declared. +declares two interface types with the qualified names 'X.Y.Z' and 'X.Y' relative to the root module in which 'X' is declared. In a qualified type name all identifiers but the last one refer to namespaces and the last identifier refers to a named type. Named type and namespace names are in separate declaration spaces and it is therefore possible for a named type and a namespace to have the same name, as in the example above. @@ -793,23 +793,23 @@ module A { } ``` -introduces a named type with the qualified name ‘A.B.C’ and also introduces a constructor function that can be accessed using the expression ‘A.B.C’. Thus, in the example +introduces a named type with the qualified name 'A.B.C' and also introduces a constructor function that can be accessed using the expression 'A.B.C'. Thus, in the example ```TypeScript var c: A.B.C = new A.B.C(); ``` -the two occurrences of ‘A.B.C’ in fact refer to different entities. It is the context of the occurrences that determines whether ‘A.B.C’ is processed as a type name or an expression. +the two occurrences of 'A.B.C' in fact refer to different entities. It is the context of the occurrences that determines whether 'A.B.C' is processed as a type name or an expression. ## 2.3 Declarations Declarations introduce names in the ***declaration spaces*** to which they belong. It is an error to have two names with same spelling in the same declaration space. Declaration spaces exist as follows: * The global module and each external or internal module has a declaration space for variables (including functions, modules, class constructor functions, and enum objects), a declaration space for named types (classes, interfaces, and enums), and a declaration space for namespaces (containers of named types). Every declaration (whether local or exported) in a module contributes to one or more of these declaration spaces. -* Each external or internal module has a declaration space for exported members, a declaration space for exported named types, and a declaration space for exported namespaces. All export declarations in the module contribute to these declaration spaces. Each internal module’s export declaration spaces are shared with other internal modules that have the same root module and the same qualified name starting from that root module. +* Each external or internal module has a declaration space for exported members, a declaration space for exported named types, and a declaration space for exported namespaces. All export declarations in the module contribute to these declaration spaces. Each internal module's export declaration spaces are shared with other internal modules that have the same root module and the same qualified name starting from that root module. * Each class declaration has a declaration space for instance members, a declaration space for static members, and a declaration space for type parameters. -* Each interface declaration has a declaration space for members and a declaration space for type parameters. An interface’s declaration space is shared with other interfaces that have the same root module and the same qualified name starting from that root module. -* Each enum declaration has a declaration space for its enum members. An enum’s declaration space is shared with other enums that have the same root module and the same qualified name starting from that root module. +* Each interface declaration has a declaration space for members and a declaration space for type parameters. An interface's declaration space is shared with other interfaces that have the same root module and the same qualified name starting from that root module. +* Each enum declaration has a declaration space for its enum members. An enum's declaration space is shared with other enums that have the same root module and the same qualified name starting from that root module. * Each function declaration (including constructor, member function, and member accessor declarations) and each function expression has a declaration space for variables (parameters, local variables, and local functions) and a declaration space for type parameters. * Each object literal has a declaration space for its properties. * Each object type literal has a declaration space for its members. @@ -827,14 +827,14 @@ The ***parent module*** of an entity is defined as follows: The ***root module*** of an entity is defined as follows: -* The root module of a non-exported entity is the entity’s parent module. -* The root module of an exported entity is the root module of the entity’s parent module. +* The root module of a non-exported entity is the entity's parent module. +* The root module of an exported entity is the root module of the entity's parent module. Intuitively, the root module of an entity is the outermost module body from within which the entity is reachable. -Interfaces, enums, and internal modules are “open ended,” meaning that interface, enum, and internal module declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [7.2](#7.2), [9.3](#9.3), and [10.5](#10.5). +Interfaces, enums, and internal modules are "open ended," meaning that interface, enum, and internal module declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [7.2](#7.2), [9.3](#9.3), and [10.5](#10.5). -Namespace, type, and member names exist in separate declaration spaces. Furthermore, declarations of non-instantiated modules (modules that contain only interfaces or modules at all levels of nesting) do not introduce a member name in their containing declaration space. This means that the following is permitted, provided module ‘X’ contains only interface or module declarations at all levels of nesting: +Namespace, type, and member names exist in separate declaration spaces. Furthermore, declarations of non-instantiated modules (modules that contain only interfaces or modules at all levels of nesting) do not introduce a member name in their containing declaration space. This means that the following is permitted, provided module 'X' contains only interface or module declarations at all levels of nesting: ```TypeScript module M { @@ -844,7 +844,7 @@ module M { } ``` -If module ‘X’ above was an instantiated module (section [10.1](#10.1)) it would cause a member ‘X’ to be introduced in ‘M’. This member would conflict with the variable ‘X’ and thus cause an error. +If module 'X' above was an instantiated module (section [10.1](#10.1)) it would cause a member 'X' to be introduced in 'M'. This member would conflict with the variable 'X' and thus cause an error. Instance and static members in a class are likewise in separate declaration spaces. Thus the following is permitted: @@ -876,7 +876,7 @@ When an identifier is resolved as a *ModuleName* (section [3.6.2](#3.6.2)), only When an identifier is resolved as a *PrimaryExpression* (section [4.3](#4.3)), only instantiated modules (section [10.1](#10.1)), classes, enums, functions, variables, and parameters are considered and other entities in scope are ignored. -Note that class and enum members are never directly in scope—they can only be accessed by applying the dot (‘.’) operator to a class instance or enum object. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. +Note that class and enum members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class instance or enum object. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. As the rules above imply, locally declared entities in an internal module are closer in scope than exported entities declared in other module declarations for the same internal module. For example: @@ -899,11 +899,11 @@ module M { # 3 Types -TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript’s *static* compile-time type system closely models the *dynamic* run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript’s type analysis occurs entirely at compile-time and adds no run-time overhead to program execution. +TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript's *static* compile-time type system closely models the *dynamic* run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to program execution. All types in TypeScript are subtypes of a single top type called the Any type. The `any` keyword references this type. The Any type is the one type that can represent *any* JavaScript value with no constraints. All other types are categorized as ***primitive types***, ***object types***, or ***type parameters***. These types introduce various static constraints on their values. -The primitive types are the Number, Boolean, String, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, and `void` keywords reference the Number, Boolean, String, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only *values* of those types can be referenced, using the `null` and `undefined` literals. +The primitive types are the Number, Boolean, String, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, and `void` keywords reference the Number, Boolean, String, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only *values* of those types can be referenced, using the `null` and `undefined` literals. The object types are all class, interface, array, and literal types. Class and interface types are introduced through class and interface declarations and are referenced by the name given to them in their declarations. Class and interface types may be ***generic types*** which have one or more type parameters. Literal types are written as object, array, function, or constructor type literals and are used to compose new types from other types. @@ -919,7 +919,7 @@ or through implicit ***type inference***, as in var x = 1; ``` -which infers the type of ‘x’ to be the Number primitive type because that is the type of the value used to initialize ‘x’. +which infers the type of 'x' to be the Number primitive type because that is the type of the value used to initialize 'x'. ## 3.1 The Any Type @@ -951,7 +951,7 @@ The Number primitive type corresponds to the similarly named JavaScript primitiv The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type. -For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the Number primitive type behaves as an object type with the same properties as the global interface type ‘Number’. +For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. Some examples: @@ -968,7 +968,7 @@ The Boolean primitive type corresponds to the similarly named JavaScript primiti The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values. -For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the Boolean primitive type behaves as an object type with the same properties as the global interface type ‘Boolean’. +For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. Some examples: @@ -984,7 +984,7 @@ The String primitive type corresponds to the similarly named JavaScript primitiv The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type. -For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the String primitive type behaves as an object type with the same properties as the global interface type ‘String’. +For purposes of determining type relationships (section [3.8](#3.8)) and accessing properties (section [4.10](#4.10)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. Some examples: @@ -1071,9 +1071,9 @@ Type references (section [3.6.2](#3.6.2)) to class and interface types are class ### 3.3.2 Array Types -***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type ‘Array’ in the global module with the array element type as a type argument. Array type literals (section [3.6.4](#3.6.4)) provide a shorthand notation for creating such references. +***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type 'Array' in the global module with the array element type as a type argument. Array type literals (section [3.6.4](#3.6.4)) provide a shorthand notation for creating such references. -The declaration of the ‘Array’ interface includes a property ‘length’ and a numeric index signature for the element type, along with other members: +The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members: ```TypeScript interface Array { @@ -1126,7 +1126,7 @@ var x = t[i]; // Type of x is number | string ***Union types*** represent values that may have one of several disjoint representations. A value of a union type *A* | *B* is a value that is *either* of type *A* or type *B*. Union types are written using union type literals (section [3.6.6](#3.6.6)). -A union type encompasses an unordered set of unrelated types (that is, types that aren’t subtypes of each other). The following rules govern union types: +A union type encompasses an unordered set of unrelated types (that is, types that aren't subtypes of each other). The following rules govern union types: * *A* | *B* is equivalent to *A* if *B* is a subtype of *A*. * *A* | *B* is equivalent to *B* | *A*. @@ -1176,7 +1176,7 @@ x = test ? 5 : "five"; // Ok x = test ? 0 : false; // Error, number | boolean not asssignable ``` -it is possible to assign ‘x’ a value of type string, number, or the union type string | number, but not any other type. To access a value in ‘x’, a type guard can be used to first narrow the type of ‘x’ to either string or number: +it is possible to assign 'x' a value of type string, number, or the union type string | number, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either string or number: ```TypeScript var n = typeof x === "string" ? x.length : x; // Type of n is number @@ -1202,7 +1202,7 @@ var b = x.b; // b has type number var c = x.c; // Error, no property c in union type ``` -Note that ‘x.a’ has a union type because the type of ‘a’ is different in ‘A’ and ‘B’, whereas ‘x.b’ simply has type number because that is the type of ‘b’ in both ‘A’ and ‘B’. Also note that there is no property ‘x.c’ because only ‘A’ has a property ‘c’. +Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'A' has a property 'c'. ### 3.3.5 Function Types @@ -1259,9 +1259,9 @@ Each type parameter has an associated type parameter ***constraint*** that estab The ***base constraint*** of a type parameter *T* is defined as follows: -* If *T* has no declared constraint, *T*’s base constraint is the empty object type `{}`. -* If *T*’s declared constraint is a type parameter, *T*’s base constraint is that of the type parameter. -* Otherwise, *T*’s base constraint is *T*’s declared constraint. +* If *T* has no declared constraint, *T*'s base constraint is the empty object type `{}`. +* If *T*'s declared constraint is a type parameter, *T*'s base constraint is that of the type parameter. +* Otherwise, *T*'s base constraint is *T*'s declared constraint. In the example @@ -1271,7 +1271,7 @@ interface G { } ``` -the base constraint of ‘T’ is the empty object type, and the base constraint of ‘U’ and ‘V’ is ‘Function’. +the base constraint of 'T' is the empty object type, and the base constraint of 'U' and 'V' is 'Function'. For purposes of determining type relationships (section [3.8](#3.8)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)), type parameters appear to have the members of their base constraint, but no other members. @@ -1297,7 +1297,7 @@ Given the declaration interface G { } ``` -a type reference of the form ‘G<A, B>’ places no requirements on ‘A’ but requires ‘B’ to be assignable to ‘Function’. +a type reference of the form 'G<A, B>' places no requirements on 'A' but requires 'B' to be assignable to 'Function'. The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters. @@ -1305,11 +1305,11 @@ The process of substituting type arguments for type parameters in a generic type Class, interface, and enum types are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), and enum declarations ([9.1](#9.1)). Class and interface types may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***. -Interface declarations only introduce named types, whereas class declarations introduce named types *and* constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can’t declare optional members and interfaces can’t declare private or protected members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations. +Interface declarations only introduce named types, whereas class declarations introduce named types *and* constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can't declare optional members and interfaces can't declare private or protected members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations. Named types are referenced through ***type references*** (section [3.6.2](#3.6.2)) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type. -Named types are technically not types—only *references* to named types are. This distinction is particularly evident with generic types: Generic types are “templates” from which multiple *actual* types can be created by writing type references that supply type arguments to substitute in place of the generic type’s type parameters. This substitution process is known as ***instantiating*** a generic type. Only once a generic type is instantiated does it denote an actual type. +Named types are technically not types—only *references* to named types are. This distinction is particularly evident with generic types: Generic types are "templates" from which multiple *actual* types can be created by writing type references that supply type arguments to substitute in place of the generic type's type parameters. This substitution process is known as ***instantiating*** a generic type. Only once a generic type is instantiated does it denote an actual type. TypeScript has a structural type system, and therefore an instantiation of a generic type is indistinguishable from an equivalent manually written expansion. For example, given the declaration @@ -1331,7 +1331,7 @@ is indistinguishable from the type ### 3.5.1 Instance Types -Each named type has an associated actual type known as the ***instance type***. For a non-generic type, the instance type is simply a type reference to the non-generic type. For a generic type, the instance type is an instantiation of the generic type where each of the type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the generic type. Within the constructor and instance member functions of a class, the type of `this` is the instance type of the class. +Each named type has an associated actual type known as the ***instance type***. For a non-generic type, the instance type is simply a type reference to the non-generic type. For a generic type, the instance type is an instantiation of the generic type where each of the type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the generic type. Within the constructor and instance member functions of a class, the type of `this` is the instance type of the class. The following example illustrates the concept of an instance type: @@ -1422,9 +1422,9 @@ var v6: G; // Error, wrong number of arguments var v7: G; // Error, no arguments ``` -A type argument is simply a *Type* and may itself be a type reference to a generic type, as demonstrated by ‘v4’ in the example above. +A type argument is simply a *Type* and may itself be a type reference to a generic type, as demonstrated by 'v4' in the example above. -As described in section [3.5](#3.5), a type reference to a generic type *G* designates a type wherein all occurrences of *G*’s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of ‘v1’ above is equivalent to: +As described in section [3.5](#3.5), a type reference to a generic type *G* designates a type wherein all occurrences of *G*'s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of 'v1' above is equivalent to: ```TypeScript var v1: { @@ -1471,15 +1471,15 @@ An array type literal is written as an element type followed by an open and clos    *TupleType*    *TypeQuery* -An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type ‘Array’ in the global module with the element type as a type argument. +An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type 'Array' in the global module with the element type as a type argument. -In order to avoid grammar ambiguities, array type literals permit only a restricted set of notations for the element type. Specifically, an *ArrayType* cannot start with a *UnionType*, *FunctionType* or *ConstructorType*. To use one of those forms for the element type, an array type must be written using the ‘Array<T>’ notation. For example, the type +In order to avoid grammar ambiguities, array type literals permit only a restricted set of notations for the element type. Specifically, an *ArrayType* cannot start with a *UnionType*, *FunctionType* or *ConstructorType*. To use one of those forms for the element type, an array type must be written using the 'Array<T>' notation. For example, the type ```TypeScript () => string[] ``` -denotes a function returning a string array, not an array of functions returning string. The latter can be expressed using ‘Array<T>’ notation +denotes a function returning a string array, not an array of functions returning string. The latter can be expressed using 'Array<T>' notation ```TypeScript Array<() => string> @@ -1596,7 +1596,7 @@ var a = { x: 10, y: 20 }; var b: typeof a; ``` -Above, ‘b’ is given the same type as ‘a’, namely ‘{ x: number; y: number; }’. +Above, 'b' is given the same type as 'a', namely '{ x: number; y: number; }'. If a declaration includes a type annotation that references the entity being declared through a circular path of type queries or type references containing type queries, the resulting type is the Any type. For example, all of the following variables are given the type Any: @@ -1614,7 +1614,7 @@ var g: { x: typeof g; }; var h: () => typeof h; ``` -Here, ‘g’ and ‘g.x’ have the same recursive type, and likewise ‘h’ and ‘h()’ have the same recursive type. +Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type. ## 3.7 Specifying Members @@ -1673,7 +1673,7 @@ A function taking two values of the same type, returning an array of that type: (x: T, y: T): T[] ``` -A function taking two arguments of different types, returning an object with properties ‘x’ and ‘y’ of those types: +A function taking two arguments of different types, returning an object with properties 'x' and 'y' of those types: ```TypeScript (x: T, y: U): { x: T; y: U; } @@ -1687,7 +1687,7 @@ A function taking an array of one type and a function argument, returning an arr #### 3.7.2.2 Parameter List -A signature’s parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter. +A signature's parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter.   *ParameterList:*    *RequiredParameterList* @@ -1737,7 +1737,7 @@ A parameter can be marked optional by following its name with a question mark (` #### 3.7.2.3 Return Type -If present, a call signature’s return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value. +If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value. When a call signature with no return type annotation occurs in a context without a function body, the return type is assumed to be the Any type. @@ -1756,11 +1756,11 @@ interface Document { } ``` -states that calls to ‘createElement’ with the string literals “div”, “span”, and “canvas” return values of type ‘HTMLDivElement’, ‘HTMLSpanElement’, and ‘HTMLCanvasElement’ respectively, and that calls with all other string expressions return values of type ‘HTMLElement’. +states that calls to 'createElement' with the string literals "div", "span", and "canvas" return values of type 'HTMLDivElement', 'HTMLSpanElement', and 'HTMLCanvasElement' respectively, and that calls with all other string expressions return values of type 'HTMLElement'. When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section [4.12.1](#4.12.1)) processes the candidates in declaration order and picks the first one that matches. -Every specialized call or construct signature in an object type must be assignable to at least one non-specialized call or construct signature in the same object type (where a call signature *A* is considered assignable to another call signature *B* if an object type containing only *A* would be assignable to an object type containing only *B*). For example, the ‘createElement’ property in the example above is of a type that contains three specialized signatures, all of which are assignable to the non-specialized signature in the type. +Every specialized call or construct signature in an object type must be assignable to at least one non-specialized call or construct signature in the same object type (where a call signature *A* is considered assignable to another call signature *B* if an object type containing only *A* would be assignable to an object type containing only *B*). For example, the 'createElement' property in the example above is of a type that contains three specialized signatures, all of which are assignable to the non-specialized signature in the type. ### 3.7.3 Construct Signatures @@ -1841,7 +1841,7 @@ In the following example of an object type } ``` -the properties ‘func1’, ‘func2’, and ‘func3’ are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type +the properties 'func1', 'func2', and 'func3' are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type ```TypeScript { @@ -1854,29 +1854,29 @@ the properties } ``` -the properties ‘func4’ and ‘func5’ are of the same type, namely an object type with two call signatures taking and returning number and string respectively. +the properties 'func4' and 'func5' are of the same type, namely an object type with two call signatures taking and returning number and string respectively. ## 3.8 Type Relationships Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections. -For purposes of determining type relationships, all object types appear to have the members of the ‘Object’ interface unless those members are hidden by members with the same name in the object types, and object types with one or more call or construct signatures appear to have the members of the ‘Function’ interface unless those members are hidden by members with the same name in the object types. Apparent types (section [3.8.1](#3.8.1)) that are object types appear to have these extra members as well. +For purposes of determining type relationships, all object types appear to have the members of the 'Object' interface unless those members are hidden by members with the same name in the object types, and object types with one or more call or construct signatures appear to have the members of the 'Function' interface unless those members are hidden by members with the same name in the object types. Apparent types (section [3.8.1](#3.8.1)) that are object types appear to have these extra members as well. ### 3.8.1 Apparent Type -In certain contexts a type appears to have the characteristics of a related type called the type’s ***apparent type***. Specifically, a type’s apparent type is used when determining subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)). +In certain contexts a type appears to have the characteristics of a related type called the type's ***apparent type***. Specifically, a type's apparent type is used when determining subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)). The apparent type of a type *T* is defined as follows: -* If *T* is the primitive type Number, Boolean, or String, the apparent type of *T* is the augmented form (as defined below) of the global interface type ‘Number’, ‘Boolean’, or ‘String’. -* if *T* is an enum type, the apparent type of *T* is the augmented form of the global interface type ‘Number’. +* If *T* is the primitive type Number, Boolean, or String, the apparent type of *T* is the augmented form (as defined below) of the global interface type 'Number', 'Boolean', or 'String'. +* if *T* is an enum type, the apparent type of *T* is the augmented form of the global interface type 'Number'. * If *T* is an object type, the apparent type of *T* is the augmented form of *T*. -* If *T* is a type parameter, the apparent type of *T* is the apparent type of *T*’s base constraint (section [3.4.1](#3.4.1)). +* If *T* is a type parameter, the apparent type of *T* is the apparent type of *T*'s base constraint (section [3.4.1](#3.4.1)). * Otherwise, the apparent type of *T* is *T* itself. -The augmented form of an object type *T* adds to *T* those properties of the global interface type ‘Object’ that aren’t hidden by properties in *T*. Furthermore, if *T* has one or more call or construct signatures, the augmented form of *T* adds to *T* the properties of the global interface type ‘Function’ that aren’t hidden by properties in *T*. Properties in *T* hide ‘Object’ or ‘Function’ interface properties with the same name. +The augmented form of an object type *T* adds to *T* those properties of the global interface type 'Object' that aren't hidden by properties in *T*. Furthermore, if *T* has one or more call or construct signatures, the augmented form of *T* adds to *T* the properties of the global interface type 'Function' that aren't hidden by properties in *T*. Properties in *T* hide 'Object' or 'Function' interface properties with the same name. -In effect, a type’s apparent type is a subtype of the ‘Object’ or ‘Function’ interface unless the type defines members that are incompatible with those of the ‘Object’ or ‘Function’ interface—which, for example, occurs if the type defines a property with the same name as a property in the ‘Object’ or ‘Function’ interface but with a type that isn’t a subtype of that in the ‘Object’ or ‘Function’ interface. +In effect, a type's apparent type is a subtype of the 'Object' or 'Function' interface unless the type defines members that are incompatible with those of the 'Object' or 'Function' interface—which, for example, occurs if the type defines a property with the same name as a property in the 'Object' or 'Function' interface but with a type that isn't a subtype of that in the 'Object' or 'Function' interface. Some examples: @@ -1886,7 +1886,7 @@ var f: Function = (x: number) => x * x; // Ok var err: Object = { toString: 0 }; // Error ``` -The last assignment is an error because the apparent type of the object literal has a ‘toString’ method that isn’t compatible with that of ‘Object’. +The last assignment is an error because the apparent type of the object literal has a 'toString' method that isn't compatible with that of 'Object'. ### 3.8.2 Type and Member Identity @@ -1923,11 +1923,11 @@ var a: C; var b: C; ``` -the variables ‘a’ and ‘b’ are of identical types because the two type references to ‘C’ create types with a private member ‘x’ that originates in the same declaration, and because the two private ‘x’ members have types with identical sets of members once the type arguments ‘X’ and ‘Y’ are substituted. +the variables 'a' and 'b' are of identical types because the two type references to 'C' create types with a private member 'x' that originates in the same declaration, and because the two private 'x' members have types with identical sets of members once the type arguments 'X' and 'Y' are substituted. ### 3.8.3 Subtypes and Supertypes -*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if one of the following is true, where *S*’ denotes the apparent type (section [3.8.1](#3.8.1)) of *S*: +*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if one of the following is true, where *S*' denotes the apparent type (section [3.8.1](#3.8.1)) of *S*: * *S* and *T* are identical types. * *T* is the Any type. @@ -1938,20 +1938,20 @@ the variables * *S* and *T* are type parameters, and *S* is directly or indirectly constrained to *T*. * *S* is a union type and each constituent type of *S* is a subtype of *T*. * *T* is a union type and *S* is a subtype of at least one constituent type of *T*. -* *S’* and *T* are object types and, for each member *M* in *T*, one of the following is true: - * *M* is a property and *S’* contains a property *N* where +* *S'* and *T* are object types and, for each member *M* in *T*, one of the following is true: + * *M* is a property and *S'* contains a property *N* where * *M* and *N* have the same name, * the type of *N* is a subtype of that of *M*, * if *M* is a required property, *N* is also a required property, and * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. - * *M* is an optional property and *S’* contains no property of the same name as *M*. - * *M* is a non-specialized call or construct signature and *S*’ contains a call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), + * *M* is an optional property and *S'* contains no property of the same name as *M*. + * *M* is a non-specialized call or construct signature and *S*' contains a call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), * the signatures are of the same kind (call or construct), * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, * for parameter positions that are present in both signatures, each parameter type in *N* is a subtype or supertype of the corresponding parameter type in *M*, and * the result type of *M* is Void, or the result type of *N* is a subtype of that of *M*. - * *M* is a string index signature of type *U* and *S’* contains a string index signature of a type that is a subtype of *U*. - * *M* is a numeric index signature of type *U* and *S’* contains a string or numeric index signature of a type that is a subtype of *U*. + * *M* is a string index signature of type *U* and *S'* contains a string index signature of a type that is a subtype of *U*. + * *M* is a numeric index signature of type *U* and *S'* contains a string or numeric index signature of a type that is a subtype of *U*. When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. @@ -1963,7 +1963,7 @@ Also note that type parameters are not considered object types. Thus, the only s Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls. -*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if one of the following is true, where *S*’ denotes the apparent type (section [3.8.1](#3.8.1)) of *S*: +*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if one of the following is true, where *S*' denotes the apparent type (section [3.8.1](#3.8.1)) of *S*: * *S* and *T* are identical types. * *S* or *T* is the Any type. @@ -1974,20 +1974,20 @@ Types are required to be assignment compatible in certain circumstances, such as * *S* and *T* are type parameters, and *S* is directly or indirectly constrained to *T*. * *S* is a union type and each constituent type of *S* is assignable to *T*. * *T* is a union type and *S* is assignable to at least one constituent type of *T*. -* *S’* and *T* are object types and, for each member *M* in *T*, one of the following is true: - * *M* is a property and *S’* contains a property *N* where +* *S'* and *T* are object types and, for each member *M* in *T*, one of the following is true: + * *M* is a property and *S'* contains a property *N* where * *M* and *N* have the same name, * the type of *N* is assignable to that of *M*, * if *M* is a required property, *N* is also a required property, and * *M* and *N* are both public, *M* and *N* are both private and originate in the same declaration, *M* and *N* are both protected and originate in the same declaration, or *M* is protected and *N* is declared in a class derived from the class in which *M* is declared. - * *M* is an optional property and *S’* contains no property of the same name as *M*. - * *M* is a non-specialized call or construct signature and *S*’ contains a call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), + * *M* is an optional property and *S'* contains no property of the same name as *M*. + * *M* is a non-specialized call or construct signature and *S*' contains a call or construct signature *N* where, when *M* and *N* are instantiated using type Any as the type argument for all type parameters declared by *M* and *N* (if any), * the signatures are of the same kind (call or construct), * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, * for parameter positions that are present in both signatures, each parameter type in *N* is assignable to or from the corresponding parameter type in *M*, and * the result type of *M* is Void, or the result type of *N* is assignable to that of *M*. - * *M* is a string index signature of type *U* and *S’* contains a string index signature of a type that is assignable to *U*. - * *M* is a numeric index signature of type *U* and *S’* contains a string or numeric index signature of a type that is assignable to *U*. + * *M* is a string index signature of type *U* and *S'* contains a string index signature of a type that is assignable to *U*. + * *M* is a numeric index signature of type *U* and *S'* contains a string or numeric index signature of a type that is assignable to *U*. When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. @@ -2013,7 +2013,7 @@ foo({ name: "hello" }); // Error, id required but missing During type argument inference in a function call (section [4.12.2](#4.12.2)) it is in certain circumstances necessary to instantiate a generic call signature of an argument expression in the context of a non-generic call signature of a parameter such that further inferences can be made. A generic call signature *A* is ***instantiated in the context of*** non-generic call signature *B* as follows: -* Using the process described in [3.8.6](#3.8.6), inferences for *A*’s type parameters are made from each parameter type in *B* to the corresponding parameter type in *A* for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. +* Using the process described in [3.8.6](#3.8.6), inferences for *A*'s type parameters are made from each parameter type in *B* to the corresponding parameter type in *A* for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. * The inferred type argument for each type parameter is the union type of the set of inferences made for that type parameter. However, if the union type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint. ### 3.8.6 Type Inference @@ -2023,7 +2023,7 @@ In certain contexts, inferences for a given set of type parameters are made *fro * If *T* is one of the type parameters for which inferences are being made, *S* is added to the set of inferences for that type parameter. * Otherwise, if *S* and *T* are references to the same generic type, inferences are made from each type argument in *S* to each corresponding type argument in *T*. * Otherwise, if *T* is a union type: - * First, inferences are made from *S* to each constituent type in *T* that isn’t simply one of the type parameters for which inferences are being made. + * First, inferences are made from *S* to each constituent type in *T* that isn't simply one of the type parameters for which inferences are being made. * If the first step produced no inferences and exactly one constituent type in *T* is simply a type parameter for which inferences are being made, inferences are made from *S* to that type parameter. * Otherwise, if *S* is a union type, inferences are made from each constituent type in *S* to *T*. * Otherwise, if *S* and *T* are object types, then for each member *M* in *T*: @@ -2044,7 +2044,7 @@ Classes and interfaces can reference themselves in their internal structure, in interface A { next: A; } ``` -contains an infinitely nested sequence of ‘next’ properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing types *S* and *T* for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of the same *S* and the same *T* (where same means originating in the same declaration and, if applicable, having identical type arguments). For example, consider the identity relationship between ‘A’ above and ‘B’ below: +contains an infinitely nested sequence of 'next' properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing types *S* and *T* for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of the same *S* and the same *T* (where same means originating in the same declaration and, if applicable, having identical type arguments). For example, consider the identity relationship between 'A' above and 'B' below: ```TypeScript interface B { next: C; } @@ -2054,7 +2054,7 @@ interface C { next: D; } interface D { next: B; } ``` -To determine whether ‘A’ and ‘B’ are identical, first the ‘next’ properties of type ‘A’ and ‘C’ are compared. That leads to comparing the ‘next’ properties of type ‘A’ and ‘D’, which leads to comparing the ‘next’ properties of type ‘A’ and ‘B’. Since ‘A’ and ‘B’ are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true. +To determine whether 'A' and 'B' are identical, first the 'next' properties of type 'A' and 'C' are compared. That leads to comparing the 'next' properties of type 'A' and 'D', which leads to comparing the 'next' properties of type 'A' and 'B'. Since 'A' and 'B' are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true. When this same technique is used to compare generic type references, two type references are considered the same when they originate in the same declaration and have identical type arguments. @@ -2068,7 +2068,7 @@ interface List { } ``` -‘List<T>’ has a member ‘owner’ of type ‘List<List<T>>’, which has a member ‘owner’ of type ‘List<List<List<T>>>’, which has a member ‘owner’ of type ‘List<List<List<List<T>>>>’ and so on, ad infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to their full depth, in order to determine type relationships involving infinitely expanding generic types it may be necessary for the compiler to terminate the recursion at some point with the assumption that no further exploration will change the outcome. +'List<T>' has a member 'owner' of type 'List<List<T>>', which has a member 'owner' of type 'List<List<List<T>>>', which has a member 'owner' of type 'List<List<List<List<T>>>>' and so on, ad infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to their full depth, in order to determine type relationships involving infinitely expanding generic types it may be necessary for the compiler to terminate the recursion at some point with the assumption that no further exploration will change the outcome. ## 3.9 Widened Types @@ -2078,7 +2078,7 @@ In several situations TypeScript infers types from context, alleviating the need var name = "Steve"; ``` -infers the type of ‘name’ to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the ***widened*** form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type `any`. +infers the type of 'name' to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the ***widened*** form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type `any`. The following example shows the results of widening types to produce inferred variable types. @@ -2093,9 +2093,9 @@ var d = [ null, undefined ]; // var d: any[] # 4 Expressions -This chapter describes the manner in which TypeScript provides type inference and type checking for JavaScript expressions. TypeScript’s type analysis occurs entirely at compile-time and adds no run-time overhead to expression evaluation. +This chapter describes the manner in which TypeScript provides type inference and type checking for JavaScript expressions. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to expression evaluation. -TypeScript’s typing rules define a type for every expression construct. For example, the type of the literal 123 is the Number primitive type, and the type of the object literal { a: 10, b: "hello" } is { a: number; b: string; }. The sections in this chapter describe these rules in detail. +TypeScript's typing rules define a type for every expression construct. For example, the type of the literal 123 is the Number primitive type, and the type of the object literal { a: 10, b: "hello" } is { a: number; b: string; }. The sections in this chapter describe these rules in detail. In addition to type inference and type checking, TypeScript augments JavaScript expressions with the following constructs: @@ -2145,7 +2145,7 @@ Literals are typed as follows: * The type of the literals `true` and `false` is the Boolean primitive type. * The type of numeric literals is the Number primitive type. * The type of string literals is the String primitive type. -* The type of regular expression literals is the global interface type ‘RegExp’. +* The type of regular expression literals is the global interface type 'RegExp'. ## 4.5 Object Literals @@ -2215,7 +2215,7 @@ Each element expression in a non-empty array literal is processed as follows: The resulting type an array literal expression is determined as follows: * If the array literal is empty, the resulting type is an array type with the element type Undefined. -* Otherwise, if the array literal is contextually typed by a type that has a property with the numeric name ‘0’, the resulting type is a tuple type constructed from the types of the element expressions. +* Otherwise, if the array literal is contextually typed by a type that has a property with the numeric name '0', the resulting type is a tuple type constructed from the types of the element expressions. * Otherwise, the resulting type is an array type with an element type that is the union of the types of the element expressions. The rules above mean that an array literal is always of an array type, unless it is contextually typed by a type with numerically named properties (such as a tuple type). For example @@ -2241,7 +2241,7 @@ has the same type and classification as the contained expression itself. Specifi The `super` keyword can be used in expressions to reference base class properties and the base class constructor.   *CallExpression:* *( Modified )* -   … +   …    `super` `(` *ArgumentListopt* `)`    `super` `.` *IdentifierName* @@ -2276,7 +2276,7 @@ Function expressions are extended from JavaScript to optionally include paramete    `function` *Identifieropt* *CallSignature* `{` *FunctionBody* `}`   *AssignmentExpression:* *( Modified )* -   … +   …    *ArrowFunctionExpression*   *ArrowFunctionExpression:* @@ -2289,7 +2289,7 @@ Function expressions are extended from JavaScript to optionally include paramete The terms ***standard function expression*** and ***arrow function expression*** are used to refer to the *FunctionExpression* and *ArrowFunctionExpression* forms respectively. When referring to either, the generic term ***function expression*** is used. -The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression’s signature and body. +The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression's signature and body. The descriptions of function declarations provided in section [6.1](#6.1) apply to function expressions as well, except that function expressions do not support overloading. @@ -2354,7 +2354,7 @@ var messenger = new Messenger(); messenger.start(); ``` -the use of an arrow function expression causes the callback to have the same `this` as the surrounding ‘start’ method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding `this`, for example by copying it into a local variable: +the use of an arrow function expression causes the callback to have the same `this` as the surrounding 'start' method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding `this`, for example by copying it into a local variable: ```TypeScript class Messenger { @@ -2389,13 +2389,13 @@ Function expressions with no type parameters and no parameter type annotations ( When a function expression is contextually typed by a function type *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *T*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *T*, the additional parameters in *T* are ignored. If the function expression has more parameters than *T*, the additional parameters are all considered to have type Any. -Furthermore, when a function expression has no return type annotation and is contextually typed by a function type *T*, expressions in contained return statements (section [5.7](#5.7)) are contextually typed by *T*’s return type. +Furthermore, when a function expression has no return type annotation and is contextually typed by a function type *T*, expressions in contained return statements (section [5.7](#5.7)) are contextually typed by *T*'s return type. ## 4.10 Property Access A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference. -A property access uses an object’s apparent type (section [3.8.1](#3.8.1)) to determine its properties. Furthermore, in a property access, an object’s apparent type includes the properties that originate in the ‘Object’ or ‘Function’ global interface types, as described in section [3.3](#3.3). +A property access uses an object's apparent type (section [3.8.1](#3.8.1)) to determine its properties. Furthermore, in a property access, an object's apparent type includes the properties that originate in the 'Object' or 'Function' global interface types, as described in section [3.3](#3.3). A dot notation property access of the form @@ -2417,9 +2417,9 @@ object [ index ] where *object* and *index* are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time: -* If *index* is a string literal or a numeric literal and *object*’s apparent type has a property with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property. -* Otherwise, if *object*’s apparent type has a numeric index signature and *index* is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature. -* Otherwise, if *object*’s apparent type has a string index signature and *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature. +* If *index* is a string literal or a numeric literal and *object*'s apparent type has a property with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property. +* Otherwise, if *object*'s apparent type has a numeric index signature and *index* is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature. +* Otherwise, if *object*'s apparent type has a string index signature and *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature. * Otherwise, if *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. * Otherwise, the property access is invalid and a compile-time error occurs. @@ -2456,8 +2456,8 @@ new C < ... > ( ... ) where *C* is an expression. The first form is equivalent to supplying an empty argument list. *C* must be of type Any or of an object type with one or more construct or call signatures. The operation is processed as follows at compile-time: * If *C* is of type Any, any argument list is permitted and the result of the operation is of type Any. -* If *C*’s apparent type (section [3.8.1](#3.8.1)) is an object type with one or more construct signatures, the expression is processed in the same manner as a function call, but using the construct signatures as the initial set of candidate signatures for overload resolution. The result type of the function call becomes the result type of the operation. -* If *C*’s apparent type is an object type with no construct signatures but one or more call signatures, the expression is processed as a function call. A compile-time error occurs if the result of the function call is not Void. The type of the result of the operation is Any. +* If *C*'s apparent type (section [3.8.1](#3.8.1)) is an object type with one or more construct signatures, the expression is processed in the same manner as a function call, but using the construct signatures as the initial set of candidate signatures for overload resolution. The result type of the function call becomes the result type of the operation. +* If *C*'s apparent type is an object type with no construct signatures but one or more call signatures, the expression is processed as a function call. A compile-time error occurs if the result of the function call is not Void. The type of the result of the operation is Any. ## 4.12 Function Calls @@ -2477,11 +2477,11 @@ where *func* is an expression of a function type or of type Any. The function ex If *func* is of type Any, or of an object type that has no call or construct signatures but is a subtype of the Function interface, the call is an ***untyped function call***. In an untyped function call no type arguments are permitted, argument expressions can be of any type and number, no contextual types are provided for the argument expressions, and the result is always of type Any. -If *func*’s apparent type (section [3.8.1](#3.8.1)) is a function type, the call is a ***typed function call***. TypeScript employs ***overload resolution*** in typed function calls in order to support functions with multiple call signatures. Furthermore, TypeScript may perform ***type argument inference*** to automatically determine type arguments in generic function calls. +If *func*'s apparent type (section [3.8.1](#3.8.1)) is a function type, the call is a ***typed function call***. TypeScript employs ***overload resolution*** in typed function calls in order to support functions with multiple call signatures. Furthermore, TypeScript may perform ***type argument inference*** to automatically determine type arguments in generic function calls. ### 4.12.1 Overload Resolution -The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn’t support function overloading, all that matters at run-time is the name of the function. +The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn't support function overloading, all that matters at run-time is the name of the function. The compile-time processing of a typed function call consists of the following steps: @@ -2508,12 +2508,12 @@ A signature is said to be an ***applicable signature*** with respect to an argum ### 4.12.2 Type Argument Inference -Given a signature < *T1* , *T2* , … , *Tn* > ( *p1* : *P1* , *p2* : *P2* , … , *pm* : *Pm* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e1* , *e2* , … , *em* ), the task of type argument inference is to find a set of type arguments *A1*…*An* to substitute for *T1*…*Tn* such that the argument list becomes an applicable signature. +Given a signature < *T1* , *T2* , … , *Tn* > ( *p1* : *P1* , *p2* : *P2* , … , *pm* : *Pm* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e1* , *e2* , … , *em* ), the task of type argument inference is to find a set of type arguments *A1*…*An* to substitute for *T1*…*Tn* such that the argument list becomes an applicable signature. Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows: -* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*’s constraint. -* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the first such candidate type. If *C* satisfies *T*’s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*’s constraint. +* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint. +* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint. * Otherwise, if no candidate type is a supertype of all of the other candidate types, type inference has fails and no type argument is inferred for *T*. In order to compute candidate types, the argument list is processed as follows: @@ -2525,7 +2525,7 @@ The process of inferentially typing an expression *e* by a type *T* is the same * Where expressions contained within *e* would be contextually typed, they are instead inferentially typed. * When a function expression is inferentially typed (section [4.9.3](#4.9.3)) and a type assigned to a parameter in that expression references type parameters for which inferences are being made, the corresponding inferred type arguments to become ***fixed*** and no further candidate inferences are made for them. -* If *e* is an expression of a function type that contains exactly one generic call signature and no other members, and *T* is a function type with exactly one non-generic call signature and no other members, then any inferences made for type parameters referenced by the parameters of *T*’s call signature are ***fixed***, and *e*’s type is changed to a function type with *e*’s call signature instantiated in the context of *T*’s call signature (section [3.8.5](#3.8.5)). +* If *e* is an expression of a function type that contains exactly one generic call signature and no other members, and *T* is a function type with exactly one non-generic call signature and no other members, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are ***fixed***, and *e*'s type is changed to a function type with *e*'s call signature instantiated in the context of *T*'s call signature (section [3.8.5](#3.8.5)). An example: @@ -2538,13 +2538,13 @@ var x = choose(10, 20); // Ok, x of type number var y = choose("Five", 5); // Error ``` -In the first call to ‘choose’, two inferences are made from ‘number’ to ‘T’, one for each parameter. Thus, ‘number’ is inferred for ‘T’ and the call is equivalent to +In the first call to 'choose', two inferences are made from 'number' to 'T', one for each parameter. Thus, 'number' is inferred for 'T' and the call is equivalent to ```TypeScript var x = choose(10, 20); ``` -In the second call to ‘choose’, an inference is made from type ‘string’ to ‘T’ for the first parameter and an inference is made from type ‘number’ to ‘T’ for the second parameter. Since neither ‘string’ nor ‘number’ is a supertype of the other, type inference fails. That in turn means there are no applicable signatures and the function call is an error. +In the second call to 'choose', an inference is made from type 'string' to 'T' for the first parameter and an inference is made from type 'number' to 'T' for the second parameter. Since neither 'string' nor 'number' is a supertype of the other, type inference fails. That in turn means there are no applicable signatures and the function call is an error. In the example @@ -2559,13 +2559,13 @@ var names = ["Peter", "Paul", "Mary"]; var lengths = map(names, s => s.length); ``` -inferences for ‘T’ and ‘U’ in the call to ‘map’ are made as follows: For the first parameter, inferences are made from the type ‘string[]’ (the type of ‘names’) to the type ‘T[]’, inferring ‘string’ for ‘T’. For the second parameter, inferential typing of the arrow expression ‘s => s.length’ causes ‘T’ to become fixed such that the inferred type ‘string’ can be used for the parameter ‘s’. The return type of the arrow expression can then be determined, and inferences are made from the type ‘(s: string) => number’ to the type ‘(x: T) => U’, inferring ‘number’ for ‘U’. Thus the call to ‘map’ is equivalent to +inferences for 'T' and 'U' in the call to 'map' are made as follows: For the first parameter, inferences are made from the type 'string[]' (the type of 'names') to the type 'T[]', inferring 'string' for 'T'. For the second parameter, inferential typing of the arrow expression 's => s.length' causes 'T' to become fixed such that the inferred type 'string' can be used for the parameter 's'. The return type of the arrow expression can then be determined, and inferences are made from the type '(s: string) => number' to the type '(x: T) => U', inferring 'number' for 'U'. Thus the call to 'map' is equivalent to ```TypeScript var lengths = map(names, s => s.length); ``` -and the resulting type of ‘lengths’ is therefore ‘number[]’. +and the resulting type of 'lengths' is therefore 'number[]'. In the example @@ -2582,14 +2582,14 @@ var ages = [7, 9, 12]; var pairs = zip(names, ages, s => n => ({ name: s, age: n })); ``` -inferences for ‘S’, ‘T’ and ‘U’ in the call to ‘zip’ are made as follows: Using the first two parameters, inferences of ‘string’ for ‘S’ and ‘number’ for ‘T’ are made. For the third parameter, inferential typing of the outer arrow expression causes ‘S’ to become fixed such that the inferred type ‘string’ can be used for the parameter ‘s’. When a function expression is inferentially typed, its return expression(s) are also inferentially typed. Thus, the inner arrow function is inferentially typed, causing ‘T’ to become fixed such that the inferred type ‘number’ can be used for the parameter ‘n’. The return type of the inner arrow function can then be determined, which in turn determines the return type of the function returned from the outer arrow function, and inferences are made from the type ‘(s: string) => (n: number) => { name: string; age: number }’ to the type ‘(x: S) => (y: T) => R’, inferring ‘{ name: string; age: number }’ for ‘R’. Thus the call to ‘zip’ is equivalent to +inferences for 'S', 'T' and 'U' in the call to 'zip' are made as follows: Using the first two parameters, inferences of 'string' for 'S' and 'number' for 'T' are made. For the third parameter, inferential typing of the outer arrow expression causes 'S' to become fixed such that the inferred type 'string' can be used for the parameter 's'. When a function expression is inferentially typed, its return expression(s) are also inferentially typed. Thus, the inner arrow function is inferentially typed, causing 'T' to become fixed such that the inferred type 'number' can be used for the parameter 'n'. The return type of the inner arrow function can then be determined, which in turn determines the return type of the function returned from the outer arrow function, and inferences are made from the type '(s: string) => (n: number) => { name: string; age: number }' to the type '(x: S) => (y: T) => R', inferring '{ name: string; age: number }' for 'R'. Thus the call to 'zip' is equivalent to ```TypeScript var pairs = zip( names, ages, s => n => ({ name: s, age: n })); ``` -and the resulting type of ‘pairs’ is therefore ‘{ name: string; age: number }[]’. +and the resulting type of 'pairs' is therefore '{ name: string; age: number }[]'. ### 4.12.3 Grammar Ambiguities @@ -2599,32 +2599,32 @@ The inclusion of type arguments in the *Arguments* production (section [4.12](#4 f(g(7)); ``` -could be interpreted as a call to ‘f’ with two arguments, ‘g < A’ and ‘B > (7)’. Alternatively, it could be interpreted as a call to ‘f’ with one argument, which is a call to a generic function ‘g’ with two type arguments and one regular argument. +could be interpreted as a call to 'f' with two arguments, 'g < A' and 'B > (7)'. Alternatively, it could be interpreted as a call to 'f' with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. -The grammar ambiguity is resolved as follows: In a context where one possible interpretation of a sequence of tokens is an *Arguments* production, if the initial sequence of tokens forms a syntactically correct *TypeArguments* production and is followed by a ‘`(`‘ token, then the sequence of tokens is processed an *Arguments* production, and any other possible interpretation is discarded. Otherwise, the sequence of tokens is not considered an *Arguments* production. +The grammar ambiguity is resolved as follows: In a context where one possible interpretation of a sequence of tokens is an *Arguments* production, if the initial sequence of tokens forms a syntactically correct *TypeArguments* production and is followed by a '`(`' token, then the sequence of tokens is processed an *Arguments* production, and any other possible interpretation is discarded. Otherwise, the sequence of tokens is not considered an *Arguments* production. -This rule means that the call to ‘f’ above is interpreted as a call with one argument, which is a call to a generic function ‘g’ with two type arguments and one regular argument. However, the statements +This rule means that the call to 'f' above is interpreted as a call with one argument, which is a call to a generic function 'g' with two type arguments and one regular argument. However, the statements ```TypeScript f(g < A, B > 7); f(g < A, B > +(7)); ``` -are both interpreted as calls to ‘f’ with two arguments. +are both interpreted as calls to 'f' with two arguments. ## 4.13 Type Assertions TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression:   *UnaryExpression:* *( Modified )* -   … +   …    `<` *Type* `>` *UnaryExpression* A type assertion expression consists of a type enclosed in `<` and `>` followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are *not* checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing `<` and `>` are simply removed from the generated code. In a type assertion expression of the form `<` *T* `>` *e*, *e* is contextually typed (section [4.19](#4.19)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*. -Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren’t *known* to be correct. In the example +Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren't *known* to be correct. In the example ```TypeScript class Shape { ... } @@ -2639,7 +2639,7 @@ function createShape(kind: string): Shape { var circle = createShape("circle"); ``` -the type annotations indicate that the ‘createShape’ function *might* return a ‘Circle’ (because ‘Circle’ is a subtype of ‘Shape’), but isn’t *known* to do so (because its return type is ‘Shape’). Therefore, a type assertion is needed to treat the result as a ‘Circle’. +the type annotations indicate that the 'createShape' function *might* return a 'Circle' (because 'Circle' is a subtype of 'Shape'), but isn't *known* to do so (because its return type is 'Shape'). Therefore, a type assertion is needed to treat the result as a 'Circle'. As mentioned above, type assertions are not checked at run-time and it is up to the programmer to guard against errors, for example using the `instanceof` operator: @@ -2659,7 +2659,7 @@ The subsections that follow specify the compile-time processing rules of the una These operators, in prefix or postfix form, require their operand to be of type Any, the Number primitive type, or an enum type, and classified as a reference (section [4.1](#4.1)). They produce a result of the Number primitive type. -### 4.14.2 The +, –, and ~ operators +### 4.14.2 The +, –, and ~ operators These operators permit their operand to be of any type and produce a result of the Number primitive type. @@ -2671,7 +2671,7 @@ function getValue() { ... } var n = +getValue(); ``` -The example above converts the result of ‘getValue()’ to a number if it isn’t a number already. The type inferred for ‘n’ is the Number primitive type regardless of the return type of ‘getValue’. +The example above converts the result of 'getValue()' to a number if it isn't a number already. The type inferred for 'n' is the Number primitive type regardless of the return type of 'getValue'. ### 4.14.3 The ! operator @@ -2685,19 +2685,19 @@ function getValue() { ... } var b = !!getValue(); ``` -The example above converts the result of ‘getValue()’ to a Boolean if it isn’t a Boolean already. The type inferred for ‘b’ is the Boolean primitive type regardless of the return type of ‘getValue’. +The example above converts the result of 'getValue()' to a Boolean if it isn't a Boolean already. The type inferred for 'b' is the Boolean primitive type regardless of the return type of 'getValue'. ### 4.14.4 The delete Operator -The ‘delete’ operator takes an operand of any type and produces a result of the Boolean primitive type. +The 'delete' operator takes an operand of any type and produces a result of the Boolean primitive type. ### 4.14.5 The void Operator -The ‘void’ operator takes an operand of any type and produces the value ‘undefined’. The type of the result is the Undefined type ([3.2.6](#3.2.6)). +The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.6](#3.2.6)). ### 4.14.6 The typeof Operator -The ‘typeof’ operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, ‘typeof’ can also be used in a type query (section [3.6.9](#3.6.9)) to produce the type of an expression. +The 'typeof' operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, 'typeof' can also be used in a type query (section [3.6.9](#3.6.9)) to produce the type of an expression. ```TypeScript var x = 5; @@ -2705,13 +2705,13 @@ var y = typeof x; // Use in an expression var z: typeof x; // Use in a type query ``` -In the example above, ‘x’ is of type ‘number’, ‘y’ is of type ‘string’ because when used in an expression, ‘typeof’ produces a value of type string (in this case the string “number”), and ‘z’ is of type ‘number’ because when used in a type query, ‘typeof’ obtains the type of an expression. +In the example above, 'x' is of type 'number', 'y' is of type 'string' because when used in an expression, 'typeof' produces a value of type string (in this case the string "number"), and 'z' is of type 'number' because when used in a type query, 'typeof' obtains the type of an expression. ## 4.15 Binary Operators The subsections that follow specify the compile-time processing rules of the binary operators. In general, if the operands of a binary operator do not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type any in further processing. Tables that summarize the compile-time processing rules for operands of the Any type, the Boolean, Number, and String primitive types, and all object types and type parameters (the Object column in the tables) are provided. -### 4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators +### 4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. The result is always of the Number primitive type. @@ -2743,7 +2743,7 @@ function getValue() { ... } var s = getValue() + ""; ``` -The example above converts the result of ‘getValue()’ to a string if it isn’t a string already. The type inferred for ‘s’ is the String primitive type regardless of the return type of ‘getValue’. +The example above converts the result of 'getValue()' to a string if it isn't a string already. The type inferred for 's' is the String primitive type regardless of the return type of 'getValue'. ### 4.15.3 The <, >, <=, >=, ==, !=, ===, and !== operators @@ -2759,9 +2759,9 @@ These operators require one operand type to be identical to or a subtype of the ### 4.15.4 The instanceof operator -The `instanceof` operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘Function’ interface type. The result is always of the Boolean primitive type. +The `instanceof` operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type. -Note that object types containing one or more call or construct signatures are automatically subtypes of the ‘Function’ interface type, as described in section [3.3](#3.3). +Note that object types containing one or more call or construct signatures are automatically subtypes of the 'Function' interface type, as described in section [3.3](#3.3). ### 4.15.5 The in operator @@ -2851,10 +2851,10 @@ the assignment f = function(s) { return s.toLowerCase(); } ``` -infers the type of the ‘s’ parameter to be the String primitive type even though there is no type annotation to that effect. The function expression is said to be ***contextually typed*** by the variable to which it is being assigned. Contextual typing occurs in the following situations: +infers the type of the 's' parameter to be the String primitive type even though there is no type annotation to that effect. The function expression is said to be ***contextually typed*** by the variable to which it is being assigned. Contextual typing occurs in the following situations: * In variable, parameter, and member declarations with a type annotation and an initializer, the initializer expression is contextually typed by the type of the variable, parameter, or property. -* In return statements, if the containing function includes a return type annotation, return expressions are contextually typed by that return type. Otherwise, if the containing function is contextually typed by a type *T*, return expressions are contextually typed by *T*’s return type. +* In return statements, if the containing function includes a return type annotation, return expressions are contextually typed by that return type. Otherwise, if the containing function is contextually typed by a type *T*, return expressions are contextually typed by *T*'s return type. * In typed function calls, argument expressions are contextually typed by their parameter types. * In type assertions, the expression is contextually typed by the indicated type. * In || operator expressions without a contextual type, the right hand expression is contextually typed by the type of the left hand expression. @@ -2868,24 +2868,24 @@ Contextual typing of an expression *e* by a type *T* proceeds as follows: * If *e* is an *ObjectLiteral* and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.5](#4.5). * If *e* is an *ArrayLiteral* and *T* is an object type with a numeric index signature, *e* is processed with the contextual type *T*, as described in section [4.6](#4.6). -* If *e* is a *FunctionExpression* or *ArrowFunctionExpression* with no type parameters and no parameter type annotations, *T* is a function type with exactly one call signature and *T*’s call signature is non-generic, then any inferences made for type parameters referenced by the parameters of *T*’s call signature are fixed (section [4.12.2](#4.12.2)) and *e* is processed with the contextual type *T*, as described in section [4.9.3](#4.9.3). +* If *e* is a *FunctionExpression* or *ArrowFunctionExpression* with no type parameters and no parameter type annotations, *T* is a function type with exactly one call signature and *T*'s call signature is non-generic, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are fixed (section [4.12.2](#4.12.2)) and *e* is processed with the contextual type *T*, as described in section [4.9.3](#4.9.3). * If *e* is a || operator expression and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.15.7](#4.15.7). * If *e* is a conditional operator expression and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.16](#4.16). * Otherwise, *e* is processed without a contextual type. -The rules above require expressions be of the exact syntactic forms specified in order to be processed as contextually typed constructs. For example, given the declaration of the variable ‘f’ above, the assignment +The rules above require expressions be of the exact syntactic forms specified in order to be processed as contextually typed constructs. For example, given the declaration of the variable 'f' above, the assignment ```TypeScript f = s => s.toLowerCase(); ``` -causes the function expression to be contextually typed, inferring the String primitive type for ‘s’. However, simply enclosing the construct in parentheses +causes the function expression to be contextually typed, inferring the String primitive type for 's'. However, simply enclosing the construct in parentheses ```TypeScript f = (s => s.toLowerCase()); ``` -causes the function expression to be processed without a contextual type, now inferring ‘s’ and the result of the function to be of type Any as no type annotations are present. +causes the function expression to be processed without a contextual type, now inferring 's' and the result of the function to be of type Any as no type annotations are present. In the following example @@ -2909,11 +2909,11 @@ setEventHandlers({ }); ``` -the object literal passed to ‘setEventHandlers’ is contextually typed to the ‘EventHandlers’ type. This causes the two property assignments to be contextually typed to the unnamed function type ‘(event: EventObject) => void’, which in turn causes the ‘e’ parameters in the arrow function expressions to automatically be typed as ‘EventObject’. +the object literal passed to 'setEventHandlers' is contextually typed to the 'EventHandlers' type. This causes the two property assignments to be contextually typed to the unnamed function type '(event: EventObject) => void', which in turn causes the 'e' parameters in the arrow function expressions to automatically be typed as 'EventObject'. ## 4.20 Type Guards -Type guards are particular expression patterns involving the ‘typeof’ and ‘instanceof’ operators that cause the types of variables or parameters to be ***narrowed*** to more specific types. For example, in the code below, knowledge of the static type of ‘x’ in combination with a ‘typeof’ check makes it safe to narrow the type of ‘x’ to string in the first branch of the ‘if’ statement and number in the second branch of the ‘if’ statement. +Type guards are particular expression patterns involving the 'typeof' and 'instanceof' operators that cause the types of variables or parameters to be ***narrowed*** to more specific types. For example, in the code below, knowledge of the static type of 'x' in combination with a 'typeof' check makes it safe to narrow the type of 'x' to string in the first branch of the 'if' statement and number in the second branch of the 'if' statement. ```TypeScript function foo(x: number | string) { @@ -2928,8 +2928,8 @@ function foo(x: number | string) { The type of a variable or parameter is narrowed in the following situations: -* In the true branch statement of an ‘if’ statement, the type of a variable or parameter is *narrowed* by any type guard in the ‘if’ condition *when true*, provided the true branch statement contains no assignments to the variable or parameter. -* In the false branch statement of an ‘if’ statement, the type of a variable or parameter is *narrowed* by any type guard in the ‘if’ condition *when false*, provided the false branch statement contains no assignments to the variable or parameter. +* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by any type guard in the 'if' condition *when true*, provided the true branch statement contains no assignments to the variable or parameter. +* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by any type guard in the 'if' condition *when false*, provided the false branch statement contains no assignments to the variable or parameter. * In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by any type guard in the condition *when true*, provided the true expression contains no assignments to the variable or parameter. * In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by any type guard in the condition *when false*, provided the false expression contains no assignments to the variable or parameter. * In the right operand of a && operation, the type of a variable or parameter is *narrowed* by any type guard in the left operand *when true*, provided the right operand contains no assignments to the variable or parameter. @@ -2937,13 +2937,13 @@ The type of a variable or parameter is narrowed in the following situations: A type guard is simply an expression that follows a particular pattern. The process of narrowing the type of a variable *x* by a type guard *when true* or *when false* depends on the type guard as follows: -* A type guard of the form `x instanceof C`, where *C* is of a subtype of the global type ‘Function’ and *C* has a property named ‘prototype’ - * *when true*, narrows the type of *x* to the type of the ‘prototype’ property in *C* provided it is a subtype of the type of *x*, or +* A type guard of the form `x instanceof C`, where *C* is of a subtype of the global type 'Function' and *C* has a property named 'prototype' + * *when true*, narrows the type of *x* to the type of the 'prototype' property in *C* provided it is a subtype of the type of *x*, or * *when false*, has no effect on the type of *x*. -* A type guard of the form `typeof x === s`, where *s* is a string literal with the value ‘string’, ‘number’, or ‘boolean’, +* A type guard of the form `typeof x === s`, where *s* is a string literal with the value 'string', 'number', or 'boolean', * *when true*, narrows the type of *x* to the given primitive type, or * *when false*, removes the primitive type from the type of *x*. -* A type guard of the form `typeof x === s`, where *s* is a string literal with any value but ‘string’, ‘number’, or ‘boolean’, +* A type guard of the form `typeof x === s`, where *s* is a string literal with any value but 'string', 'number', or 'boolean', * *when true*, removes the primitive types string, number, and boolean from the type of *x*, or * *when false*, has no effect on the type of *x*. * A type guard of the form `typeof x !== s`, where *s* is a string literal, @@ -2962,7 +2962,7 @@ A type guard is simply an expression that follows a particular pattern. The proc A primitive type *P* is removed from a type *T* as follows: -* If *T* is a union type *P* | *T1* | *T2* | … | *Tn*, the result is the type *T1* | *T2* | … | *Tn*. +* If *T* is a union type *P* | *T1* | *T2* | … | *Tn*, the result is the type *T1* | *T2* | … | *Tn*. * Otherwise, the result is *T*. Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable. @@ -2975,7 +2975,7 @@ function isLongString(obj: any) { } ``` -the ‘obj’ parameter has type string in the right operand of the && operator. +the 'obj' parameter has type string in the right operand of the && operator. In the example @@ -2990,7 +2990,7 @@ function f(x: string | number | boolean) { } ``` -the type of ‘x’ is string | number | boolean in left operand of the || operator, number | boolean in the right operand of the || operator, string | number in the first branch of the ‘if’ statement, and boolean in the second branch of the ‘if’ statement. +the type of 'x' is string | number | boolean in left operand of the || operator, number | boolean in the right operand of the || operator, string | number in the first branch of the 'if' statement, and boolean in the second branch of the 'if' statement. In the example @@ -3001,7 +3001,7 @@ function processData(data: string | { (): string }) { } ``` -the inferred type of ‘d’ is string. +the inferred type of 'd' is string. In the example @@ -3015,7 +3015,7 @@ function getName(obj: any) { } ``` -the inferred type of the ‘getName’ function is string. +the inferred type of the 'getName' function is string.
@@ -3039,7 +3039,7 @@ Variable statements are extended to include optional type annotations. A variable declaration introduces a variable with the given name in the containing declaration space. The type associated with a variable is determined as follows: * If the declaration includes a type annotation, the stated type becomes the type of the variable. If an initializer is present, the initializer expression is contextually typed (section [4.19](#4.19)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. -* If the declaration includes an initializer but no type annotation, and if the initializer doesn’t directly or indirectly reference the variable, the widened type (section [3.9](#3.9)) of the initializer expression becomes the type of the variable. If the initializer directly or indirectly references the variable, the type of the variable becomes the Any type. +* If the declaration includes an initializer but no type annotation, and if the initializer doesn't directly or indirectly reference the variable, the widened type (section [3.9](#3.9)) of the initializer expression becomes the type of the variable. If the initializer directly or indirectly references the variable, the type of the variable becomes the Any type. * If the declaration includes neither a type annotation nor an initializer, the type of the variable becomes the Any type. Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable. @@ -3054,7 +3054,7 @@ var d = { x: 1, y: "hello" }; // { x: number; y: string; } var e: any = "test"; // any ``` -The following is permitted because all declarations of the single variable ‘x’ associate the same type (Number) with ‘x’. +The following is permitted because all declarations of the single variable 'x' associate the same type (Number) with 'x'. ```TypeScript var x = 1; @@ -3064,7 +3064,7 @@ if (x == 1) { } ``` -In the following example, all five variables are of the same type, ‘{ x: number; y: number; }’. +In the following example, all five variables are of the same type, '{ x: number; y: number; }'. ```TypeScript interface Point { x: number; y: number; } @@ -3078,15 +3078,15 @@ var e = <{ x: number; y: number; }> { x: 0, y: undefined }; ##
5.2 If, Do, and While Statements -Expressions controlling ‘if’, ‘do’, and ‘while’ statements can be of any type (and not just type Boolean). +Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean). ## 5.3 For Statements -Variable declarations in ‘for’ statements are extended in the same manner as variable declarations in variable statements (section [5.1](#5.1)). +Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.1](#5.1)). ## 5.4 For-In Statements -In a ‘for-in’ statement of the form +In a 'for-in' statement of the form ```TypeScript for (v in expr) statement @@ -3094,7 +3094,7 @@ for (v in expr) statement *v* must be an expression classified as a reference of type Any or the String primitive type, and *expr* must be an expression of type Any, an object type, or a type parameter type. -In a ‘for-in’ statement of the form +In a 'for-in' statement of the form ```TypeScript for (var v in expr) statement @@ -3104,21 +3104,21 @@ for (var v in expr) statement ## 5.5 Continue Statements -A ‘continue’ statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration (‘do’, ‘while’, ‘for’, or ‘for-in’) statement. When a ‘continue’ statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement. +A 'continue' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') statement. When a 'continue' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement. ## 5.6 Break Statements -A ‘break’ statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration (‘do’, ‘while’, ‘for’, or ‘for-in’) or ‘switch’ statement. When a ‘break’ statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement. +A 'break' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') or 'switch' statement. When a 'break' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement. ## 5.7 Return Statements -It is an error for a ‘return’ statement to occur outside a function body. Specifically, ‘return’ statements are not permitted at the global level or in module bodies. +It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in module bodies. -A ‘return’ statement without an expression returns the value ‘undefined’ and is permitted in the body of any function, regardless of the return type of the function. +A 'return' statement without an expression returns the value 'undefined' and is permitted in the body of any function, regardless of the return type of the function. -When a ‘return’ statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.19](#4.19)) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*’s return type. +When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.19](#4.19)) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*'s return type. -In a function implementation without a return type annotation, the return type is inferred from the ‘return’ statements in the function body, as described in section [6.3](#6.3). +In a function implementation without a return type annotation, the return type is inferred from the 'return' statements in the function body, as described in section [6.3](#6.3). In the example @@ -3128,23 +3128,23 @@ function f(): (x: string) => number { } ``` -the arrow expression in the ‘return’ statement is contextually typed by the return type of ‘f’, thus giving type ‘string’ to ‘s’. +the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'. ## 5.8 With Statements -Use of the ‘with’ statement in TypeScript is an error, as is the case in ECMAScript 5’s strict mode. Furthermore, within the body of a ‘with’ statement, TypeScript considers every identifier occurring in an expression (section [4.3](#4.3)) to be of the Any type regardless of its declared type. Because the ‘with’ statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier. +Use of the 'with' statement in TypeScript is an error, as is the case in ECMAScript 5's strict mode. Furthermore, within the body of a 'with' statement, TypeScript considers every identifier occurring in an expression (section [4.3](#4.3)) to be of the Any type regardless of its declared type. Because the 'with' statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier. ## 5.9 Switch Statements -In a ‘switch’ statement, each ‘case’ expression must be of a type that is assignable to or from (section [3.8.4](#3.8.4)) the type of the ‘switch’ expression. +In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.8.4](#3.8.4)) the type of the 'switch' expression. ## 5.10 Throw Statements -The expression specified in a ‘throw’ statement can be of any type. +The expression specified in a 'throw' statement can be of any type. ## 5.11 Try Statements -The variable introduced by a ‘catch’ clause of a ‘try’ statement is always of type Any. It is not possible to include a type annotation in a ‘catch’ clause. +The variable introduced by a 'catch' clause of a 'try' statement is always of type Any. It is not possible to include a type annotation in a 'catch' clause.
@@ -3173,7 +3173,7 @@ A function declaration introduces a function with the given name in the containi ##
6.2 Function Overloads -Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function’s return type varies based on its arguments. Overload resolution in function calls is described further in section [4.12](#4.12). +Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function's return type varies based on its arguments. Overload resolution in function calls is described further in section [4.12](#4.12). Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost. @@ -3195,7 +3195,7 @@ function attr(nameOrMap: any, value?: string): any { } ``` -Note that each overload and the final implementation specify the same identifier. The type of the local variable ‘attr’ introduced by this declaration is +Note that each overload and the final implementation specify the same identifier. The type of the local variable 'attr' introduced by this declaration is ```TypeScript var attr: { @@ -3211,8 +3211,8 @@ Note that the signature of the actual function implementation is not included in A function implementation without a return type annotation is said to be an ***implicitly typed function***. The return type of an implicitly typed function *f* is inferred from its function body as follows: -* If there are no return statements with expressions in *f*’s function body, the inferred return type is Void. -* Otherwise, if *f*’s function body directly references *f* or references any implicitly typed functions that through this same analysis reference *f*, the inferred return type is Any. +* If there are no return statements with expressions in *f*'s function body, the inferred return type is Void. +* Otherwise, if *f*'s function body directly references *f* or references any implicitly typed functions that through this same analysis reference *f*, the inferred return type is Any. * Otherwise, if *f* is a contextually typed function expression (section [4.9.3](#4.9.3)), the inferred return type is the union type (section [3.3.4](#3.3.4)) of the types of the return statement expressions in the function body, ignoring return statements with no expressions. * Otherwise, the inferred return type is the first of the types of the return statement expressions in the function body that is a supertype (section [3.8.3](#3.8.3)) of each of the others, ignoring return statements with no expressions. A compile-time error occurs if no return statement expression has a type that is a supertype of each of the others. @@ -3229,11 +3229,11 @@ function g(x: number) { } ``` -the inferred return type for ‘f’ and ‘g’ is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type ‘number’ to either breaks the cycle and causes the return type ‘number’ to be inferred for the other. +the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other. -An explicitly typed function whose return type isn’t the Void or the Any type must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single ‘throw’ statement. +An explicitly typed function whose return type isn't the Void or the Any type must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement. -The type of ‘this’ in a function implementation is the Any type. +The type of 'this' in a function implementation is the Any type. In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [4.19](#4.19)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. When a parameter declaration has no type annotation but includes an initializer, the type of the parameter is the widened form (section [3.9](#3.9)) of the type of the initializer expression. @@ -3266,11 +3266,11 @@ function f(a = x) { } ``` -the local variable ‘x’ is in scope in the parameter initializer (thus hiding the outer ‘x’), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated. +the local variable 'x' is in scope in the parameter initializer (thus hiding the outer 'x'), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated. ## 6.4 Generic Functions -A function implementation may include type parameters in its signature (section [3.7.2.1](#3.7.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct. +A function implementation may include type parameters in its signature (section [3.7.2.1](#3.7.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct. Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation. @@ -3288,7 +3288,7 @@ function compare(x: T, y: T): number { } ``` -Note that the ‘x’ and ‘y’ parameters are known to be subtypes of the constraint ‘Comparable’ and therefore have a ‘compareTo’ member. This is described further in section [3.4.1](#3.4.1). +Note that the 'x' and 'y' parameters are known to be subtypes of the constraint 'Comparable' and therefore have a 'compareTo' member. This is described further in section [3.4.1](#3.4.1). The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section [4.12.2](#4.12.2)) from the types of the regular arguments in the call. In the example @@ -3301,7 +3301,7 @@ class Person { } ``` -the type argument to ‘compare’ is automatically inferred to be the String type because the two arguments are strings. +the type argument to 'compare' is automatically inferred to be the String type because the two arguments are strings. ## 6.5 Code Generation @@ -3316,7 +3316,7 @@ function () { *FunctionName* is the name of the function (or nothing in the case of a function expression). -*FunctionParameters* is a comma separated list of the function’s parameter names. +*FunctionParameters* is a comma separated list of the function's parameter names. *DefaultValueAssignments* is a sequence of default property value assignments, one for each parameter with a default value, in the order they are declared, of the form @@ -3334,7 +3334,7 @@ where *Parameter* is the parameter name and *Default* is the default value expre Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones. -Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions. +Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions. Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section [3.8.2](#3.8.2)). @@ -3363,7 +3363,7 @@ An interface may optionally have type parameters (section [3.4.1](#3.4.1)) that An interface can inherit from zero or more ***base types*** which are specified in the *InterfaceExtendsClause*. The base types must be type references to class or interface types. -An interface has the members specified in the *ObjectType* of its declaration and furthermore inherits all base type members that aren’t hidden by declarations in the interface: +An interface has the members specified in the *ObjectType* of its declaration and furthermore inherits all base type members that aren't hidden by declarations in the interface: * A property declaration hides a public base type property with the same name. * A string index signature declaration hides a base type string index signature. @@ -3393,7 +3393,7 @@ interface Shaker { } ``` -An interface that extends ‘Mover’ and ‘Shaker’ must declare a new ‘getStatus’ property as it would otherwise inherit two ‘getStatus’ properties with different types. The new ‘getStatus’ property must be declared such that the resulting ‘MoverShaker’ is a subtype of both ‘Mover’ and ‘Shaker’: +An interface that extends 'Mover' and 'Shaker' must declare a new 'getStatus' property as it would otherwise inherit two 'getStatus' properties with different types. The new 'getStatus' property must be declared such that the resulting 'MoverShaker' is a subtype of both 'Mover' and 'Shaker': ```TypeScript interface MoverShaker extends Mover, Shaker { @@ -3407,11 +3407,11 @@ Since function and constructor types are just object types containing call and c interface StringComparer { (a: string, b: string): number; } ``` -This declares type ‘StringComparer’ to be a function type taking two strings and returning a number. +This declares type 'StringComparer' to be a function type taking two strings and returning a number. ## 7.2 Declaration Merging -Interfaces are “open-ended” and interface declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single interface. +Interfaces are "open-ended" and interface declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single interface. When a generic interface has multiple declarations, all declarations must have identical type parameter lists, i.e. identical type parameter names with identical constraints in identical order. @@ -3478,13 +3478,13 @@ class Location { } ``` -In the above example, ‘SelectableControl’ contains all of the members of ‘Control’, including the private ‘state’ property. Since ‘state’ is a private member it is only possible for descendants of ‘Control’ to implement ‘SelectableControl’. This is because only descendants of ‘Control’ will have a ‘state’ private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.8](#3.8)). +In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.8](#3.8)). -Within the ‘Control’ class it is possible to access the ‘state’ private member through an instance of ‘SelectableControl’. Effectively, a ‘SelectableControl’ acts like a ‘Control’ that is known to have a ‘select’ method. The ‘Button’ and ‘TextBox’ classes are subtypes of ‘SelectableControl’ (because they both inherit from ‘Control’ and have a ‘select’ method), but the ‘Image’ and ‘Location’ classes are not. +Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not. ## 7.4 Dynamic Type Checks -TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section [7.1](#7.1), the following is a dynamic check for the ‘MoverShaker’ interface: +TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section [7.1](#7.1), the following is a dynamic check for the 'MoverShaker' interface: ```TypeScript var obj: any = getSomeObject(); @@ -3508,7 +3508,7 @@ function asMoverShaker(obj: any): MoverShaker { TypeScript supports classes that are closely aligned with those proposed for ECMAScript 6, and includes extensions for instance and static member declarations and properties declared and initialized from constructor parameters. -*NOTE: TypeScript currently doesn’t support class expressions or nested class declarations from the ECMAScript 6 proposal*. +*NOTE: TypeScript currently doesn't support class expressions or nested class declarations from the ECMAScript 6 proposal*. ## 8.1 Class Declarations @@ -3523,7 +3523,7 @@ The *Identifier* of a class declaration may not be one of the predefined type na A class may optionally have type parameters (section [3.4.1](#3.4.1)) that serve as placeholders for actual types to be provided when the class is referenced in type references. A class with type parameters is called a ***generic class***. The type parameters of a generic class declaration are in scope in the entire declaration and may be referenced in the *ClassHeritage* and *ClassBody*. -The following example introduces both a named type called ‘Point’ (the class type) and a member called ‘Point’ (the constructor function) in the containing module. +The following example introduces both a named type called 'Point' (the class type) and a member called 'Point' (the constructor function) in the containing module. ```TypeScript class Point { @@ -3533,7 +3533,7 @@ class Point { } ``` -The ‘Point’ type is exactly equivalent to +The 'Point' type is exactly equivalent to ```TypeScript interface Point { @@ -3543,7 +3543,7 @@ interface Point { } ``` -The ‘Point’ member is a constructor function whose type corresponds to the declaration +The 'Point' member is a constructor function whose type corresponds to the declaration ```TypeScript var Point: { @@ -3558,7 +3558,7 @@ The context in which a class is referenced distinguishes between the class insta var p: Point = new Point(10, 20); ``` -the identifier ‘Point’ in the type annotation refers to the class instance type, whereas the identifier ‘Point’ in the `new` expression refers to the constructor function object. +the identifier 'Point' in the type annotation refers to the class instance type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. ### 8.1.1 Class Heritage Specification @@ -3576,7 +3576,7 @@ The heritage specification of a class consists of optional `extends` and `implem   *ImplementsClause:*    `implements` *ClassOrInterfaceTypeList* -A class that includes an `extends` clause is called a ***derived class***, and the class specified in the `extends` clause is called the ***base class*** of the derived class. When a class heritage specification omits the `extends` clause, the class does not have a base class. However, as is the case with every object type, type references (section [3.3.1](#3.3.1)) to the class will appear to have the members of the global interface type named ‘Object’ unless those members are hidden by members with the same name in the class. +A class that includes an `extends` clause is called a ***derived class***, and the class specified in the `extends` clause is called the ***base class*** of the derived class. When a class heritage specification omits the `extends` clause, the class does not have a base class. However, as is the case with every object type, type references (section [3.3.1](#3.3.1)) to the class will appear to have the members of the global interface type named 'Object' unless those members are hidden by members with the same name in the class. The following constraints must be satisfied by the class heritage specification or otherwise a compile-time error occurs: @@ -3596,15 +3596,15 @@ module Foo { } ``` -When evaluated as an expression, the type reference ‘A’ in the `extends` clause doesn’t reference the class constructor function of ‘A’ (instead it references the local variable ‘A’). +When evaluated as an expression, the type reference 'A' in the `extends` clause doesn't reference the class constructor function of 'A' (instead it references the local variable 'A'). The only situation in which the last two constraints above are violated is when a class overrides one or more base class members with incompatible new members. -Note that because TypeScript has a structural type system, a class doesn’t need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The `implements` clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type. +Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The `implements` clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type. ### 8.1.2 Class Body -The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members. +The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members.   *ClassBody:*    *ClassElementsopt* @@ -3646,7 +3646,7 @@ Private property members can be accessed only within their declaring class. Spec Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments. -Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object’s static type to Any and accessing the member dynamically. +Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically. The following example demonstrates private and protected accessibility: @@ -3672,11 +3672,11 @@ class B extends A { } ``` -In class ‘A’, the accesses to ‘x’ are permitted because ‘x’ is declared in ‘A’, and the accesses to ‘y’ are permitted because both take place through an instance of ‘A’ or a type derived from ‘A’. In class ‘B’, access to ‘x’ is not permitted, and the first access to ‘y’ is an error because it takes place through an instance of ‘A’, which is not derived from the enclosing class ‘B’. +In class 'A', the accesses to 'x' are permitted because 'x' is declared in 'A', and the accesses to 'y' are permitted because both take place through an instance of 'A' or a type derived from 'A'. In class 'B', access to 'x' is not permitted, and the first access to 'y' is an error because it takes place through an instance of 'A', which is not derived from the enclosing class 'B'. ### 8.2.3 Inheritance and Overriding -A derived class ***inherits*** all members from its base class it doesn’t ***override***. Inheritance means that a derived class implicitly contains all non-overridden members of the base class. Only public and protected property members can be overridden. +A derived class ***inherits*** all members from its base class it doesn't ***override***. Inheritance means that a derived class implicitly contains all non-overridden members of the base class. Only public and protected property members can be overridden. A property member in a derived class is said to override a property member in a base class when the derived class property member has the same name and kind (instance or static) as the base class property member. The type of an overriding property member must be assignable (section [3.8.4](#3.8.4)) to the type of the overridden property member, or otherwise a compile-time error occurs. @@ -3717,7 +3717,7 @@ class B extends A { } ``` -the instance type of ‘A’ is +the instance type of 'A' is ```TypeScript interface A { @@ -3727,7 +3727,7 @@ interface A { } ``` -and the instance type of ‘B’ is +and the instance type of 'B' is ```TypeScript interface B { @@ -3738,7 +3738,7 @@ interface B { } ``` -Note that static declarations in a class do not contribute to the class type and its instance type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of ‘g’ in ‘B’ overrides the member inherited from ‘A’. +Note that static declarations in a class do not contribute to the class type and its instance type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'. ### 8.2.5 Constructor Function Types @@ -3751,10 +3751,10 @@ The type of the constructor function introduced by a class declaration is called * A property for each static member variable declaration in the class body. * A property of a function type for each static member function declaration in the class body. * A property for each uniquely named static member accessor declaration in the class body. -* A property named ‘prototype’, the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. +* A property named 'prototype', the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. * All base class constructor function type properties that are not overridden in the class. -Every class automatically contains a static property member named ‘prototype’, the type of which is the containing class with type Any substituted for each type parameter. +Every class automatically contains a static property member named 'prototype', the type of which is the containing class with type Any substituted for each type parameter. The example @@ -3792,7 +3792,7 @@ var TwoArrays: { } ``` -Note that the construct signatures in the constructor function types have the same type parameters as their class and return the instance type of their class. Also note that when a derived class doesn’t declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. +Note that the construct signatures in the constructor function types have the same type parameters as their class and return the instance type of their class. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. ## 8.3 Constructor Declarations @@ -3903,7 +3903,7 @@ Note that the declaration spaces of instance and static property members are sep Except for overrides, as described in section [8.2.3](#8.2.3), it is an error for a derived class to declare a property member with the same name and kind (instance or static) as a base class member. -Every class automatically contains a static property member named ‘prototype’, the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. It is an error to explicitly declare a static property member with the name ‘prototype’. +Every class automatically contains a static property member named 'prototype', the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. It is an error to explicitly declare a static property member with the name 'prototype'. Below is an example of a class containing both instance and static property member declarations: @@ -3920,7 +3920,7 @@ class Point { } ``` -The class instance type ‘Point’ has the members: +The class instance type 'Point' has the members: ```TypeScript interface Point { @@ -3930,7 +3930,7 @@ interface Point { } ``` -and the constructor function ‘Point’ has a type corresponding to the declaration: +and the constructor function 'Point' has a type corresponding to the declaration: ```TypeScript var Point: { @@ -4029,7 +4029,7 @@ class ColoredPoint extends Point { } ``` -In a static member function, `this` represents the constructor function object on which the static member function was invoked. Thus, a call to ‘new this()’ may actually invoke a derived class constructor: +In a static member function, `this` represents the constructor function object on which the static member function was invoked. Thus, a call to 'new this()' may actually invoke a derived class constructor: ```TypeScript class A { @@ -4047,7 +4047,7 @@ var x = A.create(); // new A() var y = B.create(); // new B() ``` -Note that TypeScript doesn’t require or verify that derived constructor functions are subtypes of base constructor functions. In other words, changing the declaration of ‘B’ to +Note that TypeScript doesn't require or verify that derived constructor functions are subtypes of base constructor functions. In other words, changing the declaration of 'B' to ```TypeScript class B extends A { @@ -4057,7 +4057,7 @@ class B extends A { } ``` -does not cause errors in the example, even though the call to the constructor from the ‘create’ function doesn’t specify an argument (thus giving the value ‘undefined’ to ‘b’). +does not cause errors in the example, even though the call to the constructor from the 'create' function doesn't specify an argument (thus giving the value 'undefined' to 'b'). ### 8.4.3 Member Accessor Declarations @@ -4075,7 +4075,7 @@ An instance member accessor declaration declares a property in the class instanc A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type. -Get and set accessors are emitted as calls to ‘Object.defineProperty’ in the generated JavaScript, as described in section [8.6.1](#8.6.1). +Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.6.1](#8.6.1). ## 8.5 Index Member Declarations @@ -4116,7 +4116,7 @@ var = (function () { *ClassName* is the name of the class. -*ConstructorParameters* is a comma separated list of the constructor’s parameter names. +*ConstructorParameters* is a comma separated list of the constructor's parameter names. *DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.5](#6.5). @@ -4190,7 +4190,7 @@ Object.defineProperty(, "", { }; ``` -where *MemberName* is the name of the member accessor, *GetAccessorStatements* is the code generated for the statements in the get acessor’s function body, *ParameterName* is the name of the set accessor parameter, and *SetAccessorStatements* is the code generated for the statements in the set accessor’s function body. The ‘get’ property is included only if a get accessor is declared and the ‘set’ property is included only if a set accessor is declared. +where *MemberName* is the name of the member accessor, *GetAccessorStatements* is the code generated for the statements in the get acessor's function body, *ParameterName* is the name of the set accessor parameter, and *SetAccessorStatements* is the code generated for the statements in the set accessor's function body. The 'get' property is included only if a get accessor is declared and the 'set' property is included only if a set accessor is declared. *StaticVariableAssignments* is a sequence of statements, one for each static member variable declaration with an initializer, in the order they are declared, of the form @@ -4220,7 +4220,7 @@ var = (function (_super) { })(); ``` -In addition, the ‘__extends’ function below is emitted at the beginning of the JavaScript source file. It copies all properties from the base constructor function object to the derived constructor function object (in order to inherit static members), and appropriately establishes the ‘prototype’ property of the derived constructor function object. +In addition, the '__extends' function below is emitted at the beginning of the JavaScript source file. It copies all properties from the base constructor function object to the derived constructor function object (in order to inherit static members), and appropriately establishes the 'prototype' property of the derived constructor function object. ```TypeScript var __extends = this.__extends || function(d, b) { @@ -4288,7 +4288,7 @@ An enum declaration declares an ***enum type*** and an ***enum object*** in the   *EnumDeclaration:*    `enum` *Identifier* `{` *EnumBodyopt* `}` -The enum type and enum object declared by an *EnumDeclaration* both have the name given by the *Identifier* of the declaration. The enum type is a distinct subtype of the Number primitive type. The enum object is a variable of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object’s type furthermore includes a numeric index signature with the signature ‘[x: number]: string’. +The enum type and enum object declared by an *EnumDeclaration* both have the name given by the *Identifier* of the declaration. The enum type is a distinct subtype of the Number primitive type. The enum object is a variable of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'. The *Identifier* of an enum declaration may not be one of the predefined type names (section [3.6.1](#3.6.1)). @@ -4298,7 +4298,7 @@ The example enum Color { Red, Green, Blue } ``` -declares a subtype of the Number primitive type called ‘Color’ and introduces a variable ‘Color’ with a type that corresponds to the declaration +declares a subtype of the Number primitive type called 'Color' and introduces a variable 'Color' with a type that corresponds to the declaration ```TypeScript var Color: { @@ -4309,7 +4309,7 @@ var Color: { }; ``` -The numeric index signature reflects a “reverse mapping” that is automatically generated in every enum object, as described in section [9.4](#9.4). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example +The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.4](#9.4). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example ```TypeScript var c = Color.Red; @@ -4370,7 +4370,7 @@ enum Test { } ``` -‘A’, ‘B’, ‘D’, and ‘E’ are constant members with values 0, 1, 10, and 11 respectively, and ‘C’ is a computed member. +'A', 'B', 'D', and 'E' are constant members with values 0, 1, 10, and 11 respectively, and 'C' is a computed member. In the example @@ -4389,9 +4389,9 @@ the first four members are constant members and the last two are computed member ## 9.3 Declaration Merging -Enums are “open-ended” and enum declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) define a single enum type and contribute to a single enum object. +Enums are "open-ended" and enum declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) define a single enum type and contribute to a single enum object. -It isn’t possible for one enum declaration to continue the automatic numbering sequence of another, and when an enum type has multiple declarations, only one declaration is permitted to omit a value for the first member. +It isn't possible for one enum declaration to continue the automatic numbering sequence of another, and when an enum type has multiple declarations, only one declaration is permitted to omit a value for the first member. ## 9.4 Code Generation @@ -4414,7 +4414,7 @@ var ; where *MemberName* is the name of the enum member and *Value* is the assigned constant value or the code generated for the computed value expression. -For example, the ‘Color’ enum example from section [9.1](#9.1) generates the following JavaScript: +For example, the 'Color' enum example from section [9.1](#9.1) generates the following JavaScript: ```TypeScript var Color; @@ -4429,7 +4429,7 @@ var Color; # 10 Internal Modules -An internal module is a named container of statements and declarations. An internal module represents both a namespace and a singleton module instance. The namespace contains named types and other namespaces, and the singleton module instance contains properties for the module’s exported members. The body of an internal module corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. +An internal module is a named container of statements and declarations. An internal module represents both a namespace and a singleton module instance. The namespace contains named types and other namespaces, and the singleton module instance contains properties for the module's exported members. The body of an internal module corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. ## 10.1 Module Declarations @@ -4442,7 +4442,7 @@ An internal module declaration declares a namespace name and, in the case of an    *Identifier*    *IdentifierPath* `.` *Identifier* -Internal modules are either ***instantiated*** or ***non-instantiated***. A non-instantiated module is an internal module containing only interface types and other non-instantiated modules. An instantiated module is an internal module that doesn’t meet this definition. In intuitive terms, an instantiated module is one for which a module object instance is created, whereas a non-instantiated module is one for which no code is generated. +Internal modules are either ***instantiated*** or ***non-instantiated***. A non-instantiated module is an internal module containing only interface types and other non-instantiated modules. An instantiated module is an internal module that doesn't meet this definition. In intuitive terms, an instantiated module is one for which a module object instance is created, whereas a non-instantiated module is one for which no code is generated. When a module identifier is referenced as a *ModuleName* (section [3.6.2](#3.6.2)) it denotes a container of module and type names, and when a module identifier is referenced as a *PrimaryExpression* (section [4.3](#4.3)) it denotes the singleton module instance. For example: @@ -4459,9 +4459,9 @@ var x2 = m.a; // Same as M.a var q: m.P; // Error ``` -Above, when ‘M’ is used as a *PrimaryExpression* it denotes an object instance with a single member ‘a’ and when ‘M’ is used as a *ModuleName* it denotes a container with a single type member ‘P’. The final line in the example is an error because ‘m’ is a variable which cannot be referenced in a type name. +Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *ModuleName* it denotes a container with a single type member 'P'. The final line in the example is an error because 'm' is a variable which cannot be referenced in a type name. -If the declaration of ‘M’ above had excluded the exported variable ‘a’, ‘M’ would be a non-instantiated module and it would be an error to reference ‘M’ as a *PrimaryExpression*. +If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated module and it would be an error to reference 'M' as a *PrimaryExpression*. An internal module declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier internal module declarations where all but the outermost are automatically exported. For example: @@ -4520,7 +4520,7 @@ Import declarations are used to create local aliases for entities in other modul An *EntityName* consisting of a single identifier is resolved as a *ModuleName* and is thus required to reference an internal module. The resulting local alias references the given internal module and is itself classified as an internal module. -An *EntityName* consisting of more than one identifier is resolved as a *ModuleName* followed by an identifier that names one or more exported entities in the given module. The resulting local alias has all the meanings and classifications of the referenced entity or entities. (As many as three distinct meanings are possible for an entity name—namespace, type, and member.) In effect, it is as if the imported entity or entities were declared locally with the local alias name. +An *EntityName* consisting of more than one identifier is resolved as a *ModuleName* followed by an identifier that names one or more exported entities in the given module. The resulting local alias has all the meanings and classifications of the referenced entity or entities. (As many as three distinct meanings are possible for an entity name—namespace, type, and member.) In effect, it is as if the imported entity or entities were declared locally with the local alias name. In the example @@ -4538,7 +4538,7 @@ module B { } ``` -within ‘B’, ‘Y’ is an alias only for module ‘A’ and not the local interface ‘A’, whereas ‘Z’ is an alias for all exported meanings of ‘A.X’, thus denoting both an interface type and a variable. +within 'B', 'Y' is an alias only for module 'A' and not the local interface 'A', whereas 'Z' is an alias for all exported meanings of 'A.X', thus denoting both an interface type and a variable. If the *ModuleName* portion of an *EntityName* references an instantiated module, the *ModuleName* is required to reference the module instance when evaluated as an expression. In the example @@ -4553,7 +4553,7 @@ module B { } ``` -‘Y’ is a local alias for the non-instantiated module ‘A’. If the declaration of ‘A’ is changed such that ‘A’ becomes an instantiated module, for example by including a variable declaration in ‘A’, the import statement in ‘B’ above would be an error because the expression ‘A’ doesn’t reference the module instance of module ‘A’. +'Y' is a local alias for the non-instantiated module 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated module, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the module instance of module 'A'. When an import statement includes an export modifier, all meanings of the local alias are exported. @@ -4563,7 +4563,7 @@ An export declaration declares an externally accessible module member. An export Exported class, interface, and enum types can be accessed as a *TypeName* (section [3.6.2](#3.6.2)) of the form *M.T*, where *M* is a reference to the containing module and *T* is the exported type name. Likewise, as part of a *TypeName*, exported modules can be accessed as a *ModuleName* of the form *M.N*, where *M* is a reference to the containing module and *N* is the exported module. -Exported variable, function, class, enum, module, and import alias declarations become properties on the module instance and together establish the module’s ***instance type***. This unnamed type has the following members: +Exported variable, function, class, enum, module, and import alias declarations become properties on the module instance and together establish the module's ***instance type***. This unnamed type has the following members: * A property for each exported variable declaration. * A property of a function type for each exported function declaration. @@ -4597,15 +4597,15 @@ interface A { x: string; } module M { export interface B { x: A; } export interface C { x: B; } - export function foo(c: C) { … } + export function foo(c: C) { … } } ``` -the ‘foo’ function depends upon the named types ‘A’, ‘B’, and ‘C’. In order to export ‘foo’ it is necessary to also export ‘B’ and ‘C’ as they otherwise would not be at least as accessible as ‘foo’. The ‘A’ interface is already at least as accessible as ‘foo’ because it is declared in a parent module of foo’s module. +the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because it is declared in a parent module of foo's module. ## 10.5 Declaration Merging -Internal modules are “open-ended” and internal module declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single module. For example, the following two declarations of a module outer might be located in separate source files. +Internal modules are "open-ended" and internal module declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single module. For example, the following two declarations of a module outer might be located in separate source files. File a.ts: @@ -4652,7 +4652,7 @@ Declaration merging also extends to internal module declarations with the same q * When merging a class and an internal module, the type of the constructor function object is merged with the instance type of the module. In effect, the overloads or implementation of the class constructor provide the construct signatures, and the static members of the class and exported members of the module provide the properties of the combined type. It is an error to have static class members and exported module members with the same name. * When merging an enum and an internal module, the type of the enum object is merged with the instance type of the module. In effect, the members of the enum and the exported members of the module provide the properties of the combined type. It is an error to have enum members and exported module members with the same name. -When merging a non-ambient function or class declaration and a non-ambient internal module declaration, the function or class declaration must be located prior to the internal module declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object “callable” after the fact.) +When merging a non-ambient function or class declaration and a non-ambient internal module declaration, the function or class declaration must be located prior to the internal module declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object "callable" after the fact.) The example @@ -4678,7 +4678,7 @@ var p2 = point.origin; var b = point.equals(p1, p2); ``` -declares ‘point’ as a function object with two properties, ‘origin’ and ‘equals’. Note that the module declaration for ‘point’ is located after the function declaration. +declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the module declaration for 'point' is located after the function declaration. ## 10.6 Code Generation @@ -4691,7 +4691,7 @@ var ; })(||(={})); ``` -where *ModuleName* is the name of the module and *ModuleStatements* is the code generated for the statements in the module body. The *ModuleName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire module is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn’t create and return a module instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that internal modules can extend each other. +where *ModuleName* is the name of the module and *ModuleStatements* is the code generated for the statements in the module body. The *ModuleName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire module is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn't create and return a module instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that internal modules can extend each other. An import statement generates code of the form @@ -4723,11 +4723,11 @@ This copies a reference to the entity into a property on the module instance. TypeScript implements external modules that are closely aligned with those proposed for ECMAScript 6 and supports code generation targeting CommonJS and AMD module systems. -*NOTE: TypeScript currently doesn’t support the full proposed capabilities of the ECMAScript 6 import and export syntax. We expect to align more closely on the syntax as the ECMAScript 6 specification evolves*. +*NOTE: TypeScript currently doesn't support the full proposed capabilities of the ECMAScript 6 import and export syntax. We expect to align more closely on the syntax as the ECMAScript 6 specification evolves*. ## 11.1 Source Files -A TypeScript ***program*** consists of one or more source files that are either ***implementation source files*** or ***declaration source files***. Source files with extension ‘.ts’ are *ImplementationSourceFiles* containing statements and declarations. Source files with extension ‘.d.ts’ are *DeclarationSourceFiles* containing declarations only. Declaration source files are a strict subset of implementation source files. +A TypeScript ***program*** consists of one or more source files that are either ***implementation source files*** or ***declaration source files***. Source files with extension '.ts' are *ImplementationSourceFiles* containing statements and declarations. Source files with extension '.d.ts' are *DeclarationSourceFiles* containing declarations only. Declaration source files are a strict subset of implementation source files.   *SourceFile:*    *ImplementationSourceFile* @@ -4761,9 +4761,9 @@ A TypeScript ***program*** consists of one or more source files that are either    `export`*opt* *AmbientDeclaration*    `export`*opt* *ExternalImportDeclaration* -When a TypeScript program is compiled, all of the program’s source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files. +When a TypeScript program is compiled, all of the program's source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files. -The source elements permitted in a TypeScript implementation source file are a superset of those supported by JavaScript. Specifically, TypeScript extends the JavaScript grammar’s existing *VariableDeclaration* (section [5.1](#5.1)) and *FunctionDeclaration* (section [6.1](#6.1)) productions, and adds *InterfaceDeclaration* (section [7.1](#7.1)), *ClassDeclaration* (section [8.1](#8.1)), *EnumDeclaration* (section [9.1](#9.1)), *ModuleDeclaration* (section [10.1](#10.1)), *ImportDeclaration* (section [10.3](#10.3)), *ExternalImportDeclaration* (section [11.2.2](#11.2.2)), *ExportAssignment* (section [11.2.4](#11.2.4)), *AmbientDeclaration* (section [12.1](#12.1)), and *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) productions. +The source elements permitted in a TypeScript implementation source file are a superset of those supported by JavaScript. Specifically, TypeScript extends the JavaScript grammar's existing *VariableDeclaration* (section [5.1](#5.1)) and *FunctionDeclaration* (section [6.1](#6.1)) productions, and adds *InterfaceDeclaration* (section [7.1](#7.1)), *ClassDeclaration* (section [8.1](#8.1)), *EnumDeclaration* (section [9.1](#9.1)), *ModuleDeclaration* (section [10.1](#10.1)), *ImportDeclaration* (section [10.3](#10.3)), *ExternalImportDeclaration* (section [11.2.2](#11.2.2)), *ExportAssignment* (section [11.2.4](#11.2.4)), *AmbientDeclaration* (section [12.1](#12.1)), and *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) productions. Declaration source files are restricted to contain declarations only. Declaration source files can be used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application. @@ -4775,11 +4775,11 @@ External modules can additionally be declared using *AmbientExternalModuleDeclar ### 11.1.1 Source Files Dependencies -The TypeScript compiler automatically determines a source file’s dependencies and includes those dependencies in the program being compiled. The determination is made from “reference comments” and external import declarations as follows: +The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and external import declarations as follows: -* A comment of the form /// <reference path="…"/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. -* An external import declaration that specifies a relative external module name (section [11.2.1](#11.2.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension ‘.ts’ exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension ‘.d.ts’ exists, that file is added as a dependency. -* An external import declaration that specifies a top-level external module name (section [11.2.1](#11.2.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension ‘.ts’ or ‘.d.ts’ corresponding to the reference is located, that file is added as a dependency. +* A comment of the form /// <reference path="…"/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. +* An external import declaration that specifies a relative external module name (section [11.2.1](#11.2.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency. +* An external import declaration that specifies a top-level external module name (section [11.2.1](#11.2.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency. Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined. @@ -4819,7 +4819,7 @@ export function message(s: string) { } ``` -The import declaration in the ‘main’ module references the ‘log’ module and compiling the ‘main.ts’ file causes the ‘log.ts’ file to also be compiled as part of the program. At run-time, the import declaration loads the ‘log’ module and produces a reference to its module instance through which it is possible to reference the exported function. +The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program. At run-time, the import declaration loads the 'log' module and produces a reference to its module instance through which it is possible to reference the exported function. TypeScript supports two patterns of JavaScript code generation for external modules: The CommonJS Modules pattern (section [11.2.5](#11.2.5)), typically used by server frameworks such as node.js, and the Asynchronous Module Definition (AMD) pattern (section [11.2.6](#11.2.6)), an extension to CommonJS Modules that permits asynchronous module loading, as is typical in browsers. The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author external modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code. @@ -4828,16 +4828,16 @@ TypeScript supports two patterns of JavaScript code generation for external modu External modules are identified and referenced using external module names. The following definition is aligned with that provided in the CommonJS Modules 1.0 specification. * An external module name is a string of terms delimited by forward slashes. -* External module names may not have file-name extensions like “.js”. -* External module names may be relative or top-level. An external module name is relative if the first term is “.” or “..”. +* External module names may not have file-name extensions like ".js". +* External module names may be relative or top-level. An external module name is relative if the first term is "." or "..". * Top-level names are resolved off the conceptual module name space root. * Relative names are resolved relative to the name of the module in which they occur. -For purposes of resolving external module references, TypeScript associates a file path with every external module. The file path is simply the path of the module’s source file without the file extension. For example, an external module contained in the source file ‘C:\src\lib\io.ts’ has the file path ‘C:/src/lib/io’ and an external module contained in the source file ‘C:\src\ui\editor.d.ts’ has the file path ‘C:/src/ui/editor’. +For purposes of resolving external module references, TypeScript associates a file path with every external module. The file path is simply the path of the module's source file without the file extension. For example, an external module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and an external module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'. An external module name in an import declaration is resolved as follows: -* If the import declaration specifies a relative external module name, the name is resolved relative to the directory of the referencing module’s file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path ‘C:/src/ui/main’, the external module names ‘./editor’ and ‘../lib/io’ reference modules with the file paths ‘C:/src/ui/editor’ and ‘C:/src/lib/io’. +* If the import declaration specifies a relative external module name, the name is resolved relative to the directory of the referencing module's file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path 'C:/src/ui/main', the external module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'. * If the import declaration specifies a top-level external module name and the program contains an *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, then the import declaration references that ambient external module. * If the import declaration specifies a top-level external module name and the program contains no *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs. @@ -4874,7 +4874,7 @@ When an external module containing an export assignment is imported, the local a It is an error for an external module to contain more than one export assignment. -Assume the following example resides in the file ‘point.ts’: +Assume the following example resides in the file 'point.ts': ```TypeScript export = Point; @@ -4885,7 +4885,7 @@ class Point { } ``` -When ‘point.ts’ is imported in another external module, the import alias references the exported class and can be used both as a type and as a constructor function: +When 'point.ts' is imported in another external module, the import alias references the exported class and can be used both as a type and as a constructor function: ```TypeScript import Pt = require("./point"); @@ -4898,9 +4898,9 @@ Note that there is no requirement that the import alias use the same name as the ### 11.2.5 CommonJS Modules -The CommonJS Modules definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a ‘require’ function that can be used to synchronously load other external modules to obtain their singleton module instance, as well as an ‘exports’ variable to which a module can add properties to define its external API. +The CommonJS Modules definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a 'require' function that can be used to synchronously load other external modules to obtain their singleton module instance, as well as an 'exports' variable to which a module can add properties to define its external API. -The ‘main’ and ‘log’ example from section [11.2](#11.2) above generates the following JavaScript code when compiled for the CommonJS Modules pattern: +The 'main' and 'log' example from section [11.2](#11.2) above generates the following JavaScript code when compiled for the CommonJS Modules pattern: File main.js: @@ -4917,7 +4917,7 @@ exports.message = function(s) { } ``` -An external import declaration is represented in the generated JavaScript as a variable initialized by a call to the ‘require’ function provided by the module system host. A variable declaration and ‘require’ call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName* or *TypeQueryExpression*, nothing is emitted. +An external import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName* or *TypeQueryExpression*, nothing is emitted. An example: @@ -4938,21 +4938,21 @@ import g = require("./geometry"); var p = g.point(10, 20); ``` -The ‘game’ module references the imported ‘geometry’ module in an expression (through its alias ‘g’) and a ‘require’ call is therefore included in the emitted JavaScript: +The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript: ```TypeScript var g = require("./geometry"); var p = g.point(10, 20); ``` -Had the ‘game’ module instead been written to only reference ‘geometry’ in a type position +Had the 'game' module instead been written to only reference 'geometry' in a type position ```TypeScript import g = require("./geometry"); var p: g.Point = { x: 10, y: 20 }; ``` -the emitted JavaScript would have no dependency on the ‘geometry’ module and would simply be +the emitted JavaScript would have no dependency on the 'geometry' module and would simply be ```TypeScript var p = { x: 10, y: 20 }; @@ -4960,9 +4960,9 @@ var p = { x: 10, y: 20 }; ### 11.2.6 AMD Modules -The Asynchronous Module Definition (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global ‘define’ function taking an array of dependencies, specified as external module names, and a callback function containing the module body. The global ‘define’ function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module’s dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array. +The Asynchronous Module Definition (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global 'define' function taking an array of dependencies, specified as external module names, and a callback function containing the module body. The global 'define' function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module's dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array. -The “main” and “log” example from above generates the following JavaScript code when compiled for the AMD pattern. +The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern. File main.js: @@ -4982,13 +4982,13 @@ define(["require", "exports"], function(require, exports) { } ``` -The special ‘require’ and ‘exports’ dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported external modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName*, no dependency is generated for that module. +The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported external modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName*, no dependency is generated for that module.
#
12 Ambients -Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or modules, ambient declarations provide type information for entities that exist “ambiently” and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag. +Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or modules, ambient declarations provide type information for entities that exist "ambiently" and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag. ## 12.1 Ambient Declarations @@ -5117,7 +5117,7 @@ An *ExternalImportDeclaration* in an *AmbientExternalModuleDeclaration* may refe If an ambient external module declaration includes an export assignment, it is an error for any of the declarations within the module to specify an `export` modifier. If an ambient external module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier. -Ambient external modules are “open-ended” and ambient external module declarations with the same string literal name contribute to a single external module. For example, the following two declarations of an external module ‘io’ might be located in separate source files. +Ambient external modules are "open-ended" and ambient external module declarations with the same string literal name contribute to a single external module. For example, the following two declarations of an external module 'io' might be located in separate source files. ```TypeScript declare module "io" { @@ -5326,7 +5326,7 @@ This appendix contains a summary of the grammar found in the main document. As d    `set` *PropertyName* `(` *Identifier* *TypeAnnotationopt* `)` `{` *FunctionBody* `}`   *CallExpression:* *( Modified )* -   … +   …    `super` `(` *ArgumentListopt* `)`    `super` `.` *IdentifierName* @@ -5334,7 +5334,7 @@ This appendix contains a summary of the grammar found in the main document. As d    `function` *Identifieropt* *CallSignature* `{` *FunctionBody* `}`   *AssignmentExpression:* *( Modified )* -   … +   …    *ArrowFunctionExpression*   *ArrowFunctionExpression:* @@ -5349,7 +5349,7 @@ This appendix contains a summary of the grammar found in the main document. As d    *TypeArgumentsopt* `(` *ArgumentListopt* `)`   *UnaryExpression:* *( Modified )* -   … +   …    `<` *Type* `>` *UnaryExpression* ## A.3 Statements diff --git a/scripts/word2md.js b/scripts/word2md.js index 8f9cd276f95ea..0645acbb1432b 100644 --- a/scripts/word2md.js +++ b/scripts/word2md.js @@ -1,4 +1,8 @@ var sys = (function () { + var fileStream = new ActiveXObject("ADODB.Stream"); + fileStream.Type = 2; + var binaryStream = new ActiveXObject("ADODB.Stream"); + binaryStream.Type = 1; var args = []; for (var i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); @@ -6,7 +10,24 @@ var sys = (function () { return { args: args, createObject: function (typeName) { return new ActiveXObject(typeName); }, - write: function (s) { return WScript.StdOut.Write(s); } + write: function (s) { + WScript.StdOut.Write(s); + }, + writeFile: function (fileName, data) { + fileStream.Open(); + binaryStream.Open(); + try { + fileStream.Charset = "utf-8"; + fileStream.WriteText(data); + fileStream.Position = 3; + fileStream.CopyTo(binaryStream); + binaryStream.SaveToFile(fileName, 2); + } + finally { + binaryStream.Close(); + fileStream.Close(); + } + } }; })(); function convertDocumentToMarkdown(doc) { @@ -149,6 +170,10 @@ function convertDocumentToMarkdown(doc) { lastInTable = inTable; } function writeDocument() { + var title = doc.builtInDocumentProperties.item(1) + ""; + if (title.length) { + write("# " + title + "\n\n"); + } for (var p = doc.paragraphs.first; p; p = p.next()) { writeParagraph(p); } @@ -168,16 +193,19 @@ function convertDocumentToMarkdown(doc) { findReplace("^19 REF", {}, "[^&](#^&)", {}); doc.fields.toggleShowCodes(); writeDocument(); + result = result.replace(/\x85/g, "\u2026"); + result = result.replace(/\x96/g, "\u2013"); + result = result.replace(/\x97/g, "\u2014"); return result; } function main(args) { - if (args.length !== 1) { - sys.write("Syntax: word2md \n"); + if (args.length !== 2) { + sys.write("Syntax: word2md \n"); return; } var app = sys.createObject("Word.Application"); var doc = app.documents.open(args[0]); - sys.write(convertDocumentToMarkdown(doc)); + sys.writeFile(args[1], convertDocumentToMarkdown(doc)); doc.close(false); app.quit(); } diff --git a/scripts/word2md.ts b/scripts/word2md.ts index b1bc50b0cb929..65b39d6e4f6bd 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -103,6 +103,7 @@ module Word { export interface Document { fields: Fields; paragraphs: Paragraphs; + builtInDocumentProperties: Collection; close(saveChanges: boolean): void; range(): Range; } @@ -118,6 +119,10 @@ module Word { } var sys = (function () { + var fileStream = new ActiveXObject("ADODB.Stream"); + fileStream.Type = 2 /*text*/; + var binaryStream = new ActiveXObject("ADODB.Stream"); + binaryStream.Type = 1 /*binary*/; var args: string[] = []; for (var i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); @@ -125,7 +130,26 @@ var sys = (function () { return { args: args, createObject: (typeName: string) => new ActiveXObject(typeName), - write: (s: string) => WScript.StdOut.Write(s) + write(s: string): void { + WScript.StdOut.Write(s); + }, + writeFile: (fileName: string, data: string): void => { + fileStream.Open(); + binaryStream.Open(); + try { + // Write characters in UTF-8 encoding + fileStream.Charset = "utf-8"; + fileStream.WriteText(data); + // We don't want the BOM, skip it by setting the starting location to 3 (size of BOM). + fileStream.Position = 3; + fileStream.CopyTo(binaryStream); + binaryStream.SaveToFile(fileName, 2 /*overwrite*/); + } + finally { + binaryStream.Close(); + fileStream.Close(); + } + } }; })(); @@ -298,6 +322,10 @@ function convertDocumentToMarkdown(doc: Word.Document): string { } function writeDocument() { + var title = doc.builtInDocumentProperties.item(1) + ""; + if (title.length) { + write("# " + title + "\n\n"); + } for (var p = doc.paragraphs.first; p; p = p.next()) { writeParagraph(p); } @@ -321,17 +349,21 @@ function convertDocumentToMarkdown(doc: Word.Document): string { writeDocument(); + result = result.replace(/\x85/g, "\u2026"); + result = result.replace(/\x96/g, "\u2013"); + result = result.replace(/\x97/g, "\u2014"); + return result; } function main(args: string[]) { - if (args.length !== 1) { - sys.write("Syntax: word2md \n"); + if (args.length !== 2) { + sys.write("Syntax: word2md \n"); return; } var app: Word.Application = sys.createObject("Word.Application"); var doc = app.documents.open(args[0]); - sys.write(convertDocumentToMarkdown(doc)); + sys.writeFile(args[1], convertDocumentToMarkdown(doc)); doc.close(false); app.quit(); }