1# TypeScript Language Specification 2 3Version 1.8 4 5January, 2016 6 7<br/> 8 9Microsoft 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](http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0). 10 11TypeScript is a trademark of Microsoft Corporation. 12 13<br/> 14 15## Table of Contents 16 17* [1 Introduction](#1) 18 * [1.1 Ambient Declarations](#1.1) 19 * [1.2 Function Types](#1.2) 20 * [1.3 Object Types](#1.3) 21 * [1.4 Structural Subtyping](#1.4) 22 * [1.5 Contextual Typing](#1.5) 23 * [1.6 Classes](#1.6) 24 * [1.7 Enum Types](#1.7) 25 * [1.8 Overloading on String Parameters](#1.8) 26 * [1.9 Generic Types and Functions](#1.9) 27 * [1.10 Namespaces](#1.10) 28 * [1.11 Modules](#1.11) 29* [2 Basic Concepts](#2) 30 * [2.1 Grammar Conventions](#2.1) 31 * [2.2 Names](#2.2) 32 * [2.2.1 Reserved Words](#2.2.1) 33 * [2.2.2 Property Names](#2.2.2) 34 * [2.2.3 Computed Property Names](#2.2.3) 35 * [2.3 Declarations](#2.3) 36 * [2.4 Scopes](#2.4) 37* [3 Types](#3) 38 * [3.1 The Any Type](#3.1) 39 * [3.2 Primitive Types](#3.2) 40 * [3.2.1 The Number Type](#3.2.1) 41 * [3.2.2 The Boolean Type](#3.2.2) 42 * [3.2.3 The String Type](#3.2.3) 43 * [3.2.4 The Symbol Type](#3.2.4) 44 * [3.2.5 The Void Type](#3.2.5) 45 * [3.2.6 The Null Type](#3.2.6) 46 * [3.2.7 The Undefined Type](#3.2.7) 47 * [3.2.8 Enum Types](#3.2.8) 48 * [3.2.9 String Literal Types](#3.2.9) 49 * [3.3 Object Types](#3.3) 50 * [3.3.1 Named Type References](#3.3.1) 51 * [3.3.2 Array Types](#3.3.2) 52 * [3.3.3 Tuple Types](#3.3.3) 53 * [3.3.4 Function Types](#3.3.4) 54 * [3.3.5 Constructor Types](#3.3.5) 55 * [3.3.6 Members](#3.3.6) 56 * [3.4 Union Types](#3.4) 57 * [3.5 Intersection Types](#3.5) 58 * [3.6 Type Parameters](#3.6) 59 * [3.6.1 Type Parameter Lists](#3.6.1) 60 * [3.6.2 Type Argument Lists](#3.6.2) 61 * [3.6.3 This-types](#3.6.3) 62 * [3.7 Named Types](#3.7) 63 * [3.8 Specifying Types](#3.8) 64 * [3.8.1 Predefined Types](#3.8.1) 65 * [3.8.2 Type References](#3.8.2) 66 * [3.8.3 Object Type Literals](#3.8.3) 67 * [3.8.4 Array Type Literals](#3.8.4) 68 * [3.8.5 Tuple Type Literals](#3.8.5) 69 * [3.8.6 Union Type Literals](#3.8.6) 70 * [3.8.7 Intersection Type Literals](#3.8.7) 71 * [3.8.8 Function Type Literals](#3.8.8) 72 * [3.8.9 Constructor Type Literals](#3.8.9) 73 * [3.8.10 Type Queries](#3.8.10) 74 * [3.8.11 This-Type References](#3.8.11) 75 * [3.9 Specifying Members](#3.9) 76 * [3.9.1 Property Signatures](#3.9.1) 77 * [3.9.2 Call Signatures](#3.9.2) 78 * [3.9.3 Construct Signatures](#3.9.3) 79 * [3.9.4 Index Signatures](#3.9.4) 80 * [3.9.5 Method Signatures](#3.9.5) 81 * [3.10 Type Aliases](#3.10) 82 * [3.11 Type Relationships](#3.11) 83 * [3.11.1 Apparent Members](#3.11.1) 84 * [3.11.2 Type and Member Identity](#3.11.2) 85 * [3.11.3 Subtypes and Supertypes](#3.11.3) 86 * [3.11.4 Assignment Compatibility](#3.11.4) 87 * [3.11.5 Excess Properties](#3.11.5) 88 * [3.11.6 Contextual Signature Instantiation](#3.11.6) 89 * [3.11.7 Type Inference](#3.11.7) 90 * [3.11.8 Recursive Types](#3.11.8) 91 * [3.12 Widened Types](#3.12) 92* [4 Expressions](#4) 93 * [4.1 Values and References](#4.1) 94 * [4.2 The this Keyword](#4.2) 95 * [4.3 Identifiers](#4.3) 96 * [4.4 Literals](#4.4) 97 * [4.5 Object Literals](#4.5) 98 * [4.6 Array Literals](#4.6) 99 * [4.7 Template Literals](#4.7) 100 * [4.8 Parentheses](#4.8) 101 * [4.9 The super Keyword](#4.9) 102 * [4.9.1 Super Calls](#4.9.1) 103 * [4.9.2 Super Property Access](#4.9.2) 104 * [4.10 Function Expressions](#4.10) 105 * [4.11 Arrow Functions](#4.11) 106 * [4.12 Class Expressions](#4.12) 107 * [4.13 Property Access](#4.13) 108 * [4.14 The new Operator](#4.14) 109 * [4.15 Function Calls](#4.15) 110 * [4.15.1 Overload Resolution](#4.15.1) 111 * [4.15.2 Type Argument Inference](#4.15.2) 112 * [4.15.3 Grammar Ambiguities](#4.15.3) 113 * [4.16 Type Assertions](#4.16) 114 * [4.17 JSX Expressions](#4.17) 115 * [4.18 Unary Operators](#4.18) 116 * [4.18.1 The ++ and -- operators](#4.18.1) 117 * [4.18.2 The +, –, and ~ operators](#4.18.2) 118 * [4.18.3 The ! operator](#4.18.3) 119 * [4.18.4 The delete Operator](#4.18.4) 120 * [4.18.5 The void Operator](#4.18.5) 121 * [4.18.6 The typeof Operator](#4.18.6) 122 * [4.19 Binary Operators](#4.19) 123 * [4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.19.1) 124 * [4.19.2 The + operator](#4.19.2) 125 * [4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.19.3) 126 * [4.19.4 The instanceof operator](#4.19.4) 127 * [4.19.5 The in operator](#4.19.5) 128 * [4.19.6 The && operator](#4.19.6) 129 * [4.19.7 The || operator](#4.19.7) 130 * [4.20 The Conditional Operator](#4.20) 131 * [4.21 Assignment Operators](#4.21) 132 * [4.21.1 Destructuring Assignment](#4.21.1) 133 * [4.22 The Comma Operator](#4.22) 134 * [4.23 Contextually Typed Expressions](#4.23) 135 * [4.24 Type Guards](#4.24) 136* [5 Statements](#5) 137 * [5.1 Blocks](#5.1) 138 * [5.2 Variable Statements](#5.2) 139 * [5.2.1 Simple Variable Declarations](#5.2.1) 140 * [5.2.2 Destructuring Variable Declarations](#5.2.2) 141 * [5.2.3 Implied Type](#5.2.3) 142 * [5.3 Let and Const Declarations](#5.3) 143 * [5.4 If, Do, and While Statements](#5.4) 144 * [5.5 For Statements](#5.5) 145 * [5.6 For-In Statements](#5.6) 146 * [5.7 For-Of Statements](#5.7) 147 * [5.8 Continue Statements](#5.8) 148 * [5.9 Break Statements](#5.9) 149 * [5.10 Return Statements](#5.10) 150 * [5.11 With Statements](#5.11) 151 * [5.12 Switch Statements](#5.12) 152 * [5.13 Throw Statements](#5.13) 153 * [5.14 Try Statements](#5.14) 154* [6 Functions](#6) 155 * [6.1 Function Declarations](#6.1) 156 * [6.2 Function Overloads](#6.2) 157 * [6.3 Function Implementations](#6.3) 158 * [6.4 Destructuring Parameter Declarations](#6.4) 159 * [6.5 Generic Functions](#6.5) 160 * [6.6 Code Generation](#6.6) 161 * [6.7 Generator Functions](#6.7) 162 * [6.8 Asynchronous Functions](#6.8) 163 * [6.9 Type Guard Functions](#6.9) 164* [7 Interfaces](#7) 165 * [7.1 Interface Declarations](#7.1) 166 * [7.2 Declaration Merging](#7.2) 167 * [7.3 Interfaces Extending Classes](#7.3) 168 * [7.4 Dynamic Type Checks](#7.4) 169* [8 Classes](#8) 170 * [8.1 Class Declarations](#8.1) 171 * [8.1.1 Class Heritage Specification](#8.1.1) 172 * [8.1.2 Class Body](#8.1.2) 173 * [8.2 Members](#8.2) 174 * [8.2.1 Instance and Static Members](#8.2.1) 175 * [8.2.2 Accessibility](#8.2.2) 176 * [8.2.3 Inheritance and Overriding](#8.2.3) 177 * [8.2.4 Class Types](#8.2.4) 178 * [8.2.5 Constructor Function Types](#8.2.5) 179 * [8.3 Constructor Declarations](#8.3) 180 * [8.3.1 Constructor Parameters](#8.3.1) 181 * [8.3.2 Super Calls](#8.3.2) 182 * [8.3.3 Automatic Constructors](#8.3.3) 183 * [8.4 Property Member Declarations](#8.4) 184 * [8.4.1 Member Variable Declarations](#8.4.1) 185 * [8.4.2 Member Function Declarations](#8.4.2) 186 * [8.4.3 Member Accessor Declarations](#8.4.3) 187 * [8.4.4 Dynamic Property Declarations](#8.4.4) 188 * [8.5 Index Member Declarations](#8.5) 189 * [8.6 Decorators](#8.6) 190 * [8.7 Code Generation](#8.7) 191 * [8.7.1 Classes Without Extends Clauses](#8.7.1) 192 * [8.7.2 Classes With Extends Clauses](#8.7.2) 193* [9 Enums](#9) 194 * [9.1 Enum Declarations](#9.1) 195 * [9.2 Enum Members](#9.2) 196 * [9.3 Declaration Merging](#9.3) 197 * [9.4 Constant Enum Declarations](#9.4) 198 * [9.5 Code Generation](#9.5) 199* [10 Namespaces](#10) 200 * [10.1 Namespace Declarations](#10.1) 201 * [10.2 Namespace Body](#10.2) 202 * [10.3 Import Alias Declarations](#10.3) 203 * [10.4 Export Declarations](#10.4) 204 * [10.5 Declaration Merging](#10.5) 205 * [10.6 Code Generation](#10.6) 206* [11 Scripts and Modules](#11) 207 * [11.1 Programs and Source Files](#11.1) 208 * [11.1.1 Source Files Dependencies](#11.1.1) 209 * [11.2 Scripts](#11.2) 210 * [11.3 Modules](#11.3) 211 * [11.3.1 Module Names](#11.3.1) 212 * [11.3.2 Import Declarations](#11.3.2) 213 * [11.3.3 Import Require Declarations](#11.3.3) 214 * [11.3.4 Export Declarations](#11.3.4) 215 * [11.3.5 Export Assignments](#11.3.5) 216 * [11.3.6 CommonJS Modules](#11.3.6) 217 * [11.3.7 AMD Modules](#11.3.7) 218* [12 Ambients](#12) 219 * [12.1 Ambient Declarations](#12.1) 220 * [12.1.1 Ambient Variable Declarations](#12.1.1) 221 * [12.1.2 Ambient Function Declarations](#12.1.2) 222 * [12.1.3 Ambient Class Declarations](#12.1.3) 223 * [12.1.4 Ambient Enum Declarations](#12.1.4) 224 * [12.1.5 Ambient Namespace Declarations](#12.1.5) 225 * [12.2 Ambient Module Declarations](#12.2) 226* [A Grammar](#A) 227 * [A.1 Types](#A.1) 228 * [A.2 Expressions](#A.2) 229 * [A.3 Statements](#A.3) 230 * [A.4 Functions](#A.4) 231 * [A.5 Interfaces](#A.5) 232 * [A.6 Classes](#A.6) 233 * [A.7 Enums](#A.7) 234 * [A.8 Namespaces](#A.8) 235 * [A.9 Scripts and Modules](#A.9) 236 * [A.10 Ambients](#A.10) 237 238<br/> 239 240# <a name="1"/>1 Introduction 241 242JavaScript 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 refactoring. 243 244TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) 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. 245 246TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. 247 248Classes enable programmers to express common object-oriented patterns in a standard way, making features like inheritance more readable and interoperable. Modules enable programmers to organize their code into components while avoiding naming conflicts. The TypeScript compiler provides module code generation options that support either static or dynamic loading of module contents. 249 250TypeScript 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. 251 252The 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. 253 254```TypeScript 255var i = 0; 256``` 257 258TypeScript will infer from the following function definition that the function f has return type string. 259 260```TypeScript 261function f() { 262 return "hello"; 263} 264``` 265 266To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screenshot. 267 268   269 270In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment. 271 272```TypeScript 273function f(s: string) { 274 return s; 275} 276 277f({}); // Error 278f("hello"); // Ok 279``` 280 281This 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: 282 283```TypeScript 284function f(s) { 285 return s; 286} 287``` 288 289In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emitting JavaScript. 290 291## <a name="1.1"/>1.1 Ambient Declarations 292 293An 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. 294 295```TypeScript 296declare var document; 297document.title = "Hello"; // Ok because document has been declared 298``` 299 300In 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. 301 302The TypeScript compiler does not include by default an interface for jQuery, so to use jQuery, a programmer could supply a declaration such as: 303 304```TypeScript 305declare var $; 306``` 307 308Section [1.3](#1.3) provides a more extensive example of how a programmer can add type information for jQuery and other libraries. 309 310## <a name="1.2"/>1.2 Function Types 311 312Function 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. 313 314TypeScript 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. 315 316```TypeScript 317function vote(candidate: string, callback: (result: string) => any) { 318 // ... 319} 320 321vote("BigPig", 322 function(result: string) { 323 if (result === "BigPig") { 324 // ... 325 } 326 } 327); 328``` 329 330In this example, the second parameter to 'vote' has the function type 331 332```TypeScript 333(result: string) => any 334``` 335 336which means the second parameter is a function returning type 'any' that has a single parameter of type 'string' named 'result'. 337 338Section [3.9.2](#3.9.2) provides additional information about function types. 339 340## <a name="1.3"/>1.3 Object Types 341 342TypeScript 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. 343 344```TypeScript 345var MakePoint: () => { 346 x: number; y: number; 347}; 348``` 349 350Programmers can give names to object types; we call named object types *interfaces*. For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor). 351 352```TypeScript 353interface Friend { 354 name: string; 355 favoriteColor?: string; 356} 357 358function add(friend: Friend) { 359 var name = friend.name; 360} 361 362add({ name: "Fred" }); // Ok 363add({ favoriteColor: "blue" }); // Error, name required 364add({ name: "Jill", favoriteColor: "green" }); // Ok 365``` 366 367TypeScript 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. 368 369The following code fragment captures a small subset of jQuery behavior, just enough to use jQuery in a simple way. 370 371```TypeScript 372interface JQuery { 373 text(content: string); 374} 375 376interface JQueryStatic { 377 get(url: string, callback: (data: string) => any); 378 (query: string): JQuery; 379} 380 381declare var $: JQueryStatic; 382 383$.get("http://mysite.org/divContent", 384 function (data: string) { 385 $("div").text(data); 386 } 387); 388``` 389 390The '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. 391 392Finally, the 'JQueryStatic' interface contains a bare function signature 393 394```TypeScript 395(query: string): JQuery; 396``` 397 398The bare signature indicates that instances of the interface are callable. This example illustrates that TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain one or more call signatures. For this reason we can write any function type as an object type literal. The following example uses both forms to describe the same type. 399 400```TypeScript 401var f: { (): string; }; 402var sameType: () => string = f; // Ok 403var nope: () => number = sameType; // Error: type mismatch 404``` 405 406We 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. 407 408```TypeScript 409(ready: () => any): any; 410``` 411 412This 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. 413 414A 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 screenshot. 415 416   417 418Section [3.3](#3.3) provides additional information about object types. 419 420## <a name="1.4"/>1.4 Structural Subtyping 421 422Object 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. 423 424```TypeScript 425interface Point { 426 x: number; 427 y: number; 428} 429 430function getX(p: Point) { 431 return p.x; 432} 433 434class CPoint { 435 x: number; 436 y: number; 437 constructor(x: number, y: number) { 438 this.x = x; 439 this.y = y; 440 } 441} 442 443getX(new CPoint(0, 0)); // Ok, fields match 444 445getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok 446 447getX({ x: 0 }); // Error: supplied parameter does not match 448``` 449 450See section [3.11](#3.11) for more information about type comparisons. 451 452## <a name="1.5"/>1.5 Contextual Typing 453 454Ordinarily, 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. 455 456```TypeScript 457function mul(a: number, b: number) { 458 return a * b; 459} 460``` 461 462For 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. 463 464However, 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. 465 466```TypeScript 467$.get("http://mysite.org/divContent", 468 function (data) { 469 $("div").text(data); // TypeScript infers data is a string 470 } 471); 472``` 473 474Contextual typing is also useful for writing out object literals. As the programmer types the object literal, the contextual type provides information that enables tools to provide completion for object member names. 475 476Section [4.23](#4.23) provides additional information about contextually typed expressions. 477 478## <a name="1.6"/>1.6 Classes 479 480JavaScript practice has two very 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. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.) 481 482This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace 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. 483 484```TypeScript 485class BankAccount { 486 balance = 0; 487 deposit(credit: number) { 488 this.balance += credit; 489 return this.balance; 490 } 491} 492``` 493 494This class generates the following JavaScript code. 495 496```TypeScript 497var BankAccount = (function () { 498 function BankAccount() { 499 this.balance = 0; 500 } 501 BankAccount.prototype.deposit = function(credit) { 502 this.balance += credit; 503 return this.balance; 504 }; 505 return BankAccount; 506})(); 507``` 508 509This 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. 510 511```TypeScript 512interface BankAccount { 513 balance: number; 514 deposit(credit: number): number; 515} 516``` 517 518If we were to write out the function type declaration for the 'BankAccount' constructor variable, it would have the following form. 519 520```TypeScript 521var BankAccount: new() => BankAccount; 522``` 523 524The 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. 525 526If we want to start our bank account with an initial balance, we can add to the 'BankAccount' class a constructor declaration. 527 528```TypeScript 529class BankAccount { 530 balance: number; 531 constructor(initially: number) { 532 this.balance = initially; 533 } 534 deposit(credit: number) { 535 this.balance += credit; 536 return this.balance; 537 } 538} 539``` 540 541This 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. 542 543```TypeScript 544class BankAccount { 545 constructor(public balance: number) { 546 } 547 deposit(credit: number) { 548 this.balance += credit; 549 return this.balance; 550 } 551} 552``` 553 554The '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. 555 556TypeScript classes also support inheritance, as in the following example.* * 557 558```TypeScript 559class CheckingAccount extends BankAccount { 560 constructor(balance: number) { 561 super(balance); 562 } 563 writeCheck(debit: number) { 564 this.balance -= debit; 565 } 566} 567``` 568 569In 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 'BankAccount'. 570 571TypeScript classes may also specify static members. Static class members become properties of the class constructor. 572 573Section [8](#8) provides additional information about classes. 574 575## <a name="1.7"/>1.7 Enum Types 576 577TypeScript enables programmers to summarize a set of numeric constants as an *enum type*. The example below creates an enum type to represent operators in a calculator application. 578 579```TypeScript 580const enum Operator { 581 ADD, 582 DIV, 583 MUL, 584 SUB 585} 586 587function compute(op: Operator, a: number, b: number) { 588 console.log("the operator is" + Operator[op]); 589 // ... 590} 591``` 592 593In 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. 594 595When enums are declared with the `const` modifier, 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. 596 597For example, the 'compute' function could contain a switch statement like the following. 598 599```TypeScript 600switch (op) { 601 case Operator.ADD: 602 // execute add 603 break; 604 case Operator.DIV: 605 // execute div 606 break; 607 // ... 608} 609``` 610 611For this switch statement, the compiler will generate the following code. 612 613```TypeScript 614switch (op) { 615 case 0 /* Operator.ADD */: 616 // execute add 617 break; 618 case 1 /* Operator.DIV */: 619 // execute div 620 break; 621 // ... 622} 623``` 624 625JavaScript implementations can use these explicit constants to generate efficient code for this switch statement, for example by building a jump table indexed by case value. 626 627## <a name="1.8"/>1.8 Overloading on String Parameters 628 629An 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. 630 631JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screenshot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method. 632 633   634 635The 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'. 636 637```TypeScript 638var span = document.createElement("span"); 639span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property 640``` 641 642In the following screenshot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property. 643 644   645 646Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures. 647 648## <a name="1.9"/>1.9 Generic Types and Functions 649 650Like 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. 651 652To 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. 653 654```TypeScript 655interface Array<T> { 656 reverse(): T[]; 657 sort(compareFn?: (a: T, b: T) => number): T[]; 658 // ... 659} 660``` 661 662Interface 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'. 663 664Functions can also have generic parameters. For example, the array interface contains a 'map' method, defined as follows: 665 666```TypeScript 667map<U>(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; 668``` 669 670The 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'. 671 672The 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. 673 674```TypeScript 675function numberToString(a: number[]) { 676 var stringArray = a.map(v => v.toString()); 677 return stringArray; 678} 679``` 680 681The compiler infers in this example that the 'numberToString' function returns an array of strings. 682 683In 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. 684 685```TypeScript 686interface NamedItem { 687 name: string; 688} 689 690class List<T extends NamedItem> { 691 next: List<T> = null; 692 693 constructor(public item: T) { 694 } 695 696 insertAfter(item: T) { 697 var temp = this.next; 698 this.next = new List(item); 699 this.next.next = temp; 700 } 701 702 log() { 703 console.log(this.item.name); 704 } 705 706 // ... 707} 708``` 709 710Section [3.7](#3.7) provides further information about generic types. 711 712## <a name="1.10"/>1.10 Namespaces 713 714Classes 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. 715 716In JavaScript, a very common 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. The module pattern can also provide the ability to introduce namespaces, avoiding use of the global namespace for most software components. 717 718The following example illustrates the JavaScript module pattern. 719 720```TypeScript 721(function(exports) { 722 var key = generateSecretKey(); 723 function sendMessage(message) { 724 sendSecureMessage(message, key); 725 } 726 exports.sendMessage = sendMessage; 727})(MessageModule); 728``` 729 730This 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. 731 732The 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'. 733 734TypeScript namespaces provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting namespaces and classes within an outer namespace. 735 736The following example shows the definition and use of a simple namespace. 737 738```TypeScript 739namespace M { 740 var s = "hello"; 741 export function f() { 742 return s; 743 } 744} 745 746M.f(); 747M.s; // Error, s is not exported 748``` 749 750In this example, variable 's' is a private feature of the namespace, but function 'f' is exported from the namespace and accessible to code outside of the namespace. If we were to describe the effect of namespace 'M' in terms of interfaces and variables, we would write 751 752```TypeScript 753interface M { 754 f(): string; 755} 756 757var M: M; 758``` 759 760The interface 'M' summarizes the externally visible behavior of namespace '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). 761 762The TypeScript compiler emits the following JavaScript code for the namespace: 763 764```TypeScript 765var M; 766(function(M) { 767 var s = "hello"; 768 function f() { 769 return s; 770 } 771 M.f = f; 772})(M || (M = {})); 773``` 774 775In this case, the compiler assumes that the namespace object resides in global variable 'M', which may or may not have been initialized to the desired namespace object. 776 777## <a name="1.11"/>1.11 Modules 778 779TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD). 780 781<br/> 782 783# <a name="2"/>2 Basic Concepts 784 785The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification. 786 787## <a name="2.1"/>2.1 Grammar Conventions 788 789The 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: 790 791  *Declaration:* *( Modified )* 792   … 793   *InterfaceDeclaration* 794   *TypeAliasDeclaration* 795   *EnumDeclaration* 796 797The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production. 798 799Similar 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. 800 801## <a name="2.2"/>2.2 Names 802 803A core purpose of the TypeScript compiler is to track the named entities in a program and validate that they are used according to their designated meaning. Names in TypeScript can be written in several ways, depending on context. Specifically, a name can be written as 804 805* an *IdentifierName*, 806* a *StringLiteral* in a property name, 807* a *NumericLiteral* in a property name, or 808* a *ComputedPropertyName* that denotes a well-known symbol ([2.2.3](#2.2.3)). 809 810Most commonly, names are written to conform with the *Identifier* production, which is any *IdentifierName* that isn't a reserved word. 811 812### <a name="2.2.1"/>2.2.1 Reserved Words 813 814The following keywords are reserved and cannot be used as an *Identifier*: 815 816```TypeScript 817break case catch class 818const continue debugger default 819delete do else enum 820export extends false finally 821for function if import 822in instanceof new null 823return super switch this 824throw true try typeof 825var void while with 826``` 827 828The following keywords cannot be used as identifiers in strict mode code, but are otherwise not restricted: 829 830```TypeScript 831implements interface let package 832private protected public static 833yield 834``` 835 836The following keywords cannot be used as user defined type names, but are otherwise not restricted: 837 838```TypeScript 839any boolean number string 840symbol 841``` 842 843The following keywords have special meaning in certain contexts, but are valid identifiers: 844 845```TypeScript 846abstract as async await 847constructor declare from get 848is module namespace of 849require set type 850``` 851 852### <a name="2.2.2"/>2.2.2 Property Names 853 854The *PropertyName* production from the ECMAScript grammar is reproduced below: 855 856  *PropertyName:* 857   *LiteralPropertyName* 858   *ComputedPropertyName* 859 860  *LiteralPropertyName:* 861   *IdentifierName* 862   *StringLiteral* 863   *NumericLiteral* 864 865  *ComputedPropertyName:* 866   `[` *AssignmentExpression* `]` 867 868A property name can be any identifier (including a reserved word), a string literal, a numeric literal, or a computed property name. String literals may be used to give properties names that are not valid identifiers, such as names containing blanks. Numeric literal property names are equivalent to string literal property names with the string representation of the numeric literal, as defined in the ECMAScript specification. 869 870### <a name="2.2.3"/>2.2.3 Computed Property Names 871 872ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form 873 874```TypeScript 875[ Symbol . xxx ] 876``` 877 878In a well-known symbol, the identifier to the right of the dot must denote a property of the primitive type `symbol` in the type of the global variable 'Symbol', or otherwise an error occurs. 879 880In a *PropertyName* that specifies a *ComputedPropertyName*, the computed property name is required to denote a well-known symbol unless the property name occurs in a property assignment of an object literal ([4.5](#4.5)) or a property member declaration in a non-ambient class ([8.4](#8.4)). 881 882Below is an example of an interface that declares a property with a well-known symbol name: 883 884```TypeScript 885interface Iterable<T> { 886 [Symbol.iterator](): Iterator<T>; 887} 888``` 889 890*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*. 891 892## <a name="2.3"/>2.3 Declarations 893 894Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example: 895 896```TypeScript 897var X: string; // Value named X 898 899type X = number; // Type named X 900 901namespace X { // Namespace named X 902 type Y = string; 903} 904``` 905 906A name that denotes a value has an associated type (section [3](#3)) and can be referenced in expressions (section [4.3](#4.3)). A name that denotes a type can be used by itself in a type reference or on the right hand side of a dot in a type reference ([3.8.2](#3.8.2)). A name that denotes a namespace can be used on the left hand side of a dot in a type reference. 907 908When a name with multiple meanings is referenced, the context in which the reference occurs determines the meaning. For example: 909 910```TypeScript 911var n: X; // X references type 912var s: X.Y = X; // First X references namespace, second X references value 913``` 914 915In the first line, X references the type X because it occurs in a type position. In the second line, the first X references the namespace X because it occurs before a dot in a type name, and the second X references the variable X because it occurs in an expression. 916 917Declarations introduce the following meanings for the name they declare: 918 919* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning. 920* An interface, type alias, or type parameter declaration introduces a type meaning. 921* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type). 922* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type). 923* A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [10.1](#10.1)), a value meaning (the namespace instance). 924* An import or export declaration introduces the meaning(s) of the imported or exported entity. 925 926Below are some examples of declarations that introduce multiple meanings for a name: 927 928```TypeScript 929class C { // Value and type named C 930 x: string; 931} 932 933namespace N { // Value and namespace named N 934 export var x: string; 935} 936``` 937 938Declaration spaces exist as follows: 939 940* The global namespace, each module, and each declared namespace has a declaration space for its contained entities (whether local or exported). 941* Each module has a declaration space for its exported entities. All export declarations in the module contribute to this declaration space. 942* Each declared namespace has a declaration space for its exported entities. All export declarations in the namespace contribute to this declaration space. A declared namespace’s declaration space is shared with other declared namespaces that have the same root container and the same qualified name starting from that root container. 943* Each class declaration has a declaration space for instance members and type parameters, and a declaration space for static members. 944* Each interface declaration has a declaration space for members and type parameters. An interface's declaration space is shared with other interfaces that have the same root container and the same qualified name starting from that root container. 945* 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 container and the same qualified name starting from that root container. 946* Each type alias declaration has a declaration space for its type parameters. 947* Each function-like declaration (including function declarations, constructor declarations, member function declarations, member accessor declarations, function expressions, and arrow functions) has a declaration space for locals and type parameters. This declaration space includes parameter declarations, all local var and function declarations, and local let, const, class, interface, type alias, and enum declarations that occur immediately within the function body and are not further nested in blocks. 948* Each statement block has a declaration space for local let, const, class, interface, type alias, and enum declarations that occur immediately within that block. 949* Each object literal has a declaration space for its properties. 950* Each object type literal has a declaration space for its members. 951 952Top-level declarations in a source file with no top-level import or export declarations belong to the ***global namespace***. Top-level declarations in a source file with one or more top-level import or export declarations belong to the ***module*** represented by that source file. 953 954The ***container*** of an entity is defined as follows: 955 956* The container of an entity declared in a namespace declaration is that namespace declaration. 957* The container of an entity declared in a module is that module. 958* The container of an entity declared in the global namespace is the global namespace. 959* The container of a module is the global namespace. 960 961The ***root container*** of an entity is defined as follows: 962 963* The root container of a non-exported entity is the entity’s container. 964* The root container of an exported entity is the root container of the entity's container. 965 966Intuitively, the root container of an entity is the outermost module or namespace body from within which the entity is reachable. 967 968Interfaces, enums, and namespaces are "open ended," meaning that interface, enum, and namespace 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). 969 970Instance and static members in a class are in separate declaration spaces. Thus the following is permitted: 971 972```TypeScript 973class C { 974 x: number; // Instance member 975 static x: string; // Static member 976} 977``` 978 979## <a name="2.4"/>2.4 Scopes 980 981The ***scope*** of a name is the region of program text within which it is possible to refer to the entity declared by that name without qualification of the name. The scope of a name depends on the context in which the name is declared. The contexts are listed below in order from outermost to innermost: 982 983* The scope of a name declared in the global namespace is the entire program text. 984* The scope of a name declared in a module is the source file of that module. 985* The scope of an exported name declared within a namespace declaration is the body of that namespace declaration and every namespace declaration with the same root and the same qualified name relative to that root. 986* The scope of a non-exported name declared within a namespace declaration is the body of that namespace declaration. 987* The scope of a type parameter name declared in a class or interface declaration is that entire declaration, including constraints, extends clause, implements clause, and declaration body, but not including static member declarations. 988* The scope of a type parameter name declared in a type alias declaration is that entire type alias declaration. 989* The scope of a member name declared in an enum declaration is the body of that declaration and every enum declaration with the same root and the same qualified name relative to that root. 990* The scope of a type parameter name declared in a call or construct signature is that entire signature declaration, including constraints, parameter list, and return type. If the signature is part of a function implementation, the scope includes the function body. 991* The scope of a parameter name declared in a call or construct signature is the remainder of the signature declaration. If the signature is part of a function-like declaration with a body (including a function declaration, constructor declaration, member function declaration, member accessor declaration, function expression, or arrow function), the scope includes the body of that function-like declaration. 992* The scope of a local var or function name declared anywhere in the body of a function-like declaration is the body of that function-like declaration. 993* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within the body of a function-like declaration is the body of that function-like declaration. 994* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within a statement block is the body of that statement block. 995 996Scopes may overlap, for example through nesting of namespaces and functions. When the scopes of two names overlap, the name with the innermost declaration takes precedence and access to the outer name is either not possible or only possible by qualification. 997 998When an identifier is resolved as a *PrimaryExpression* (section [4.3](#4.3)), only names in scope with a value meaning are considered and other names are ignored. 999 1000When an identifier is resolved as a *TypeName* (section [3.8.2](#3.8.2)), only names in scope with a type meaning are considered and other names are ignored. 1001 1002When an identifier is resolved as a *NamespaceName* (section [3.8.2](#3.8.2)), only names in scope with a namespace meaning are considered and other names are ignored. 1003 1004*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. 1005 1006Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. 1007 1008As the rules above imply, locally declared entities in a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example: 1009 1010```TypeScript 1011var x = 1; 1012namespace M { 1013 export var x = 2; 1014 console.log(x); // 2 1015} 1016namespace M { 1017 console.log(x); // 2 1018} 1019namespace M { 1020 var x = 3; 1021 console.log(x); // 3 1022} 1023``` 1024 1025<br/> 1026 1027# <a name="3"/>3 Types 1028 1029TypeScript 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. 1030 1031All 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***, ***union types***, ***intersection types***, or ***type parameters***. These types introduce various static constraints on their values. 1032 1033The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, `symbol`, and `void` keywords reference the Number, Boolean, String, Symbol, 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. 1034 1035The object types are all class, interface, array, tuple, function, and constructor 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. 1036 1037Union types represent values that have one of multiple types, and intersection types represent values that simultaneously have more than one type. 1038 1039Declarations of classes, properties, functions, variables and other language entities associate types with those entities. The mechanism by which a type is formed and associated with a language entity depends on the particular kind of entity. For example, a namespace declaration associates the namespace with an anonymous type containing a set of properties corresponding to the exported variables and functions in the namespace, and a function declaration associates the function with an anonymous type containing a call signature corresponding to the parameters and return type of the function. Types can be associated with variables through explicit ***type annotations***, such as 1040 1041```TypeScript 1042var x: number; 1043``` 1044 1045or through implicit ***type inference***, as in 1046 1047```TypeScript 1048var x = 1; 1049``` 1050 1051which infers the type of 'x' to be the Number primitive type because that is the type of the value used to initialize 'x'. 1052 1053## <a name="3.1"/>3.1 The Any Type 1054 1055The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list. 1056 1057The `any` keyword references the Any type. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed. 1058 1059The Any type is a supertype of all types, and is assignable to and from all types. 1060 1061Some examples: 1062 1063```TypeScript 1064var x: any; // Explicitly typed 1065var y; // Same as y: any 1066var z: { a; b; }; // Same as z: { a: any; b: any; } 1067 1068function f(x) { // Same as f(x: any): void 1069 console.log(x); 1070} 1071``` 1072 1073## <a name="3.2"/>3.2 Primitive Types 1074 1075The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types and all user defined enum types. 1076 1077### <a name="3.2.1"/>3.2.1 The Number Type 1078 1079The Number primitive type corresponds to the similarly named JavaScript primitive type and represents double-precision 64-bit format IEEE 754 floating point values. 1080 1081The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type. 1082 1083For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. 1084 1085Some examples: 1086 1087```TypeScript 1088var x: number; // Explicitly typed 1089var y = 0; // Same as y: number = 0 1090var z = 123.456; // Same as z: number = 123.456 1091var s = z.toFixed(2); // Property of Number interface 1092``` 1093 1094### <a name="3.2.2"/>3.2.2 The Boolean Type 1095 1096The Boolean primitive type corresponds to the similarly named JavaScript primitive type and represents logical values that are either true or false. 1097 1098The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values. 1099 1100For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. 1101 1102Some examples: 1103 1104```TypeScript 1105var b: boolean; // Explicitly typed 1106var yes = true; // Same as yes: boolean = true 1107var no = false; // Same as no: boolean = false 1108``` 1109 1110### <a name="3.2.3"/>3.2.3 The String Type 1111 1112The String primitive type corresponds to the similarly named JavaScript primitive type and represents sequences of characters stored as Unicode UTF-16 code units. 1113 1114The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type. 1115 1116For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. 1117 1118Some examples: 1119 1120```TypeScript 1121var s: string; // Explicitly typed 1122var empty = ""; // Same as empty: string = "" 1123var abc = 'abc'; // Same as abc: string = "abc" 1124var c = abc.charAt(2); // Property of String interface 1125``` 1126 1127### <a name="3.2.4"/>3.2.4 The Symbol Type 1128 1129The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties. 1130 1131The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 2015 environments. 1132 1133For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Symbol primitive type behaves as an object type with the same properties as the global interface type 'Symbol'. 1134 1135Some examples: 1136 1137```TypeScript 1138var secretKey = Symbol(); 1139var obj = {}; 1140obj[secretKey] = "secret message"; // Use symbol as property key 1141obj[Symbol.toStringTag] = "test"; // Use of well-known symbol 1142``` 1143 1144### <a name="3.2.5"/>3.2.5 The Void Type 1145 1146The Void type, referenced by the `void` keyword, represents the absence of a value and is used as the return type of functions with no return value. 1147 1148The only possible values for the Void type are `null` and `undefined`. The Void type is a subtype of the Any type and a supertype of the Null and Undefined types, but otherwise Void is unrelated to all other types. 1149 1150*NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters*. 1151 1152### <a name="3.2.6"/>3.2.6 The Null Type 1153 1154The Null type corresponds to the similarly named JavaScript primitive type and is the type of the `null` literal. 1155 1156The `null` literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself. 1157 1158The Null type is a subtype of all types, except the Undefined type. This means that `null` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters, including even the Number and Boolean primitive types. 1159 1160Some examples: 1161 1162```TypeScript 1163var n: number = null; // Primitives can be null 1164var x = null; // Same as x: any = null 1165var e: Null; // Error, can't reference Null type 1166``` 1167 1168### <a name="3.2.7"/>3.2.7 The Undefined Type 1169 1170The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the `undefined` literal. 1171 1172The `undefined` literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself. 1173 1174The undefined type is a subtype of all types. This means that `undefined` is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters. 1175 1176Some examples: 1177 1178```TypeScript 1179var n: number; // Same as n: number = undefined 1180var x = undefined; // Same as x: any = undefined 1181var e: Undefined; // Error, can't reference Undefined type 1182``` 1183 1184### <a name="3.2.8"/>3.2.8 Enum Types 1185 1186Enum types are distinct user defined subtypes of the Number primitive type. Enum types are declared using enum declarations (section [9.1](#9.1)) and referenced using type references (section [3.8.2](#3.8.2)). 1187 1188Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other. 1189 1190### <a name="3.2.9"/>3.2.9 String Literal Types 1191 1192Specialized signatures (section [3.9.2.4](#3.9.2.4)) permit string literals to be used as types in parameter type annotations. String literal types are permitted only in that context and nowhere else. 1193 1194All string literal types are subtypes of the String primitive type. 1195 1196*TODO: Update to reflect [expanded support for string literal types](https://github.com/Microsoft/TypeScript/pull/5185)*. 1197 1198## <a name="3.3"/>3.3 Object Types 1199 1200Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members. 1201 1202Class and interface type references, array types, tuple types, function types, and constructor types are all classified as object types. Multiple constructs in the TypeScript language create object types, including: 1203 1204* Object type literals (section [3.8.3](#3.8.3)). 1205* Array type literals (section [3.8.4](#3.8.4)). 1206* Tuple type literals (section [3.8.5](#3.8.5)). 1207* Function type literals (section [3.8.8](#3.8.8)). 1208* Constructor type literals (section [3.8.9](#3.8.9)). 1209* Object literals (section [4.5](#4.5)). 1210* Array literals (section [4.6](#4.6)). 1211* Function expressions (section [4.10](#4.10)) and function declarations ([6.1](#6.1)). 1212* Constructor function types created by class declarations (section [8.2.5](#8.2.5)). 1213* Namespace instance types created by namespace declarations (section [10.3](#10.3)). 1214 1215### <a name="3.3.1"/>3.3.1 Named Type References 1216 1217Type references (section [3.8.2](#3.8.2)) to class and interface types are classified as object types. Type references to generic class and interface types include type arguments that are substituted for the type parameters of the class or interface to produce an actual object type. 1218 1219### <a name="3.3.2"/>3.3.2 Array Types 1220 1221***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 namespace with the array element type as a type argument. Array type literals (section [3.8.4](#3.8.4)) provide a shorthand notation for creating such references. 1222 1223The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members: 1224 1225```TypeScript 1226interface Array<T> { 1227 length: number; 1228 [x: number]: T; 1229 // Other members 1230} 1231``` 1232 1233Array literals (section [4.6](#4.6)) may be used to create values of array types. For example 1234 1235```TypeScript 1236var a: string[] = ["hello", "world"]; 1237``` 1238 1239A type is said to be an ***array-like type*** if it is assignable (section [3.11.4](#3.11.4)) to the type `any[]`. 1240 1241### <a name="3.3.3"/>3.3.3 Tuple Types 1242 1243***Tuple types*** represent JavaScript arrays with individually tracked element types. Tuple types are written using tuple type literals (section [3.8.5](#3.8.5)). A tuple type combines a set of numerically named properties with the members of an array type. Specifically, a tuple type 1244 1245```TypeScript 1246[ T0, T1, ..., Tn ] 1247``` 1248 1249combines the set of properties 1250 1251```TypeScript 1252{ 1253 0: T0; 1254 1: T1; 1255 ... 1256 n: Tn; 1257} 1258``` 1259 1260with the members of an array type whose element type is the union type (section [3.4](#3.4)) of the tuple element types. 1261 1262Array literals (section [4.6](#4.6)) may be used to create values of tuple types. For example: 1263 1264```TypeScript 1265var t: [number, string] = [3, "three"]; 1266var n = t[0]; // Type of n is number 1267var s = t[1]; // Type of s is string 1268var i: number; 1269var x = t[i]; // Type of x is number | string 1270``` 1271 1272Named tuple types can be created by declaring interfaces that derive from Array<T> and introduce numerically named properties. For example: 1273 1274```TypeScript 1275interface KeyValuePair<K, V> extends Array<K | V> { 0: K; 1: V; } 1276 1277var x: KeyValuePair<number, string> = [10, "ten"]; 1278``` 1279 1280A type is said to be a ***tuple-like type*** if it has a property with the numeric name '0'. 1281 1282### <a name="3.3.4"/>3.3.4 Function Types 1283 1284An object type containing one or more call signatures is said to be a ***function type***. Function types may be written using function type literals (section [3.8.8](#3.8.8)) or by including call signatures in object type literals. 1285 1286### <a name="3.3.5"/>3.3.5 Constructor Types 1287 1288An object type containing one or more construct signatures is said to be a ***constructor type***. Constructor types may be written using constructor type literals (section [3.8.9](#3.8.9)) or by including construct signatures in object type literals. 1289 1290### <a name="3.3.6"/>3.3.6 Members 1291 1292Every object type is composed from zero or more of the following kinds of members: 1293 1294* ***Properties***, which define the names and types of the properties of objects of the given type. Property names are unique within their type. 1295* ***Call signatures***, which define the possible parameter lists and return types associated with applying call operations to objects of the given type. 1296* ***Construct signatures***, which define the possible parameter lists and return types associated with applying the `new` operator to objects of the given type. 1297* ***Index signatures***, which define type constraints for properties in the given type. An object type can have at most one string index signature and one numeric index signature. 1298 1299Properties are either ***public***, ***private***, or ***protected*** and are either ***required*** or ***optional***: 1300 1301* Properties in a class declaration may be designated public, private, or protected, while properties declared in other contexts are always considered public. Private members are only accessible within their declaring class, as described in section [8.2.2](#8.2.2), and private properties match only themselves in subtype and assignment compatibility checks, as described in section [3.11](#3.11). Protected members are only accessible within their declaring class and classes derived from it, as described in section [8.2.2](#8.2.2), and protected properties match only themselves and overrides in subtype and assignment compatibility checks, as described in section [3.11](#3.11). 1302* Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section [3.11.4](#3.11.4). 1303 1304Call and construct signatures may be ***specialized*** (section [3.9.2.4](#3.9.2.4)) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. 1305 1306## <a name="3.4"/>3.4 Union Types 1307 1308***Union types*** represent values that may have one of several distinct 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.8.6](#3.8.6)). 1309 1310A union type encompasses an ordered set of constituent types. While it is generally true that *A* | *B* is equivalent to *B* | *A*, the order of the constituent types may matter when determining the call and construct signatures of the union type. 1311 1312Union types have the following subtype relationships: 1313 1314* A union type *U* is a subtype of a type *T* if each type in *U* is a subtype of *T*. 1315* A type *T* is a subtype of a union type *U* if *T* is a subtype of any type in *U*. 1316 1317Similarly, union types have the following assignability relationships: 1318 1319* A union type *U* is assignable to a type *T* if each type in *U* is assignable to *T*. 1320* A type *T* is assignable to a union type *U* if *T* is assignable to any type in *U*. 1321 1322The || and conditional operators (section [4.19.7](#4.19.7) and [4.20](#4.20)) may produce values of union types, and array literals (section [4.6](#4.6)) may produce array values that have union types as their element types. 1323 1324Type guards (section [4.24](#4.24)) may be used to narrow a union type to a more specific type. In particular, type guards are useful for narrowing union type values to a non-union type values. 1325 1326In the example 1327 1328```TypeScript 1329var x: string | number; 1330var test: boolean; 1331x = "hello"; // Ok 1332x = 42; // Ok 1333x = test; // Error, boolean not assignable 1334x = test ? 5 : "five"; // Ok 1335x = test ? 0 : false; // Error, number | boolean not assignable 1336``` 1337 1338it 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`: 1339 1340```TypeScript 1341var n = typeof x === "string" ? x.length : x; // Type of n is number 1342``` 1343 1344For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of a union type are those that are present in every one of its constituent types, with types that are unions of the respective apparent members in the constituent types. The following example illustrates the merging of member types that occurs when union types are created from object types. 1345 1346```TypeScript 1347interface A { 1348 a: string; 1349 b: number; 1350} 1351 1352interface B { 1353 a: number; 1354 b: number; 1355 c: number; 1356} 1357 1358var x: A | B; 1359var a = x.a; // a has type string | number 1360var b = x.b; // b has type number 1361var c = x.c; // Error, no property c in union type 1362``` 1363 1364Note 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 'B' has a property 'c'. 1365 1366When used as a contextual type (section [4.23](#4.23)), a union type has those members that are present in any of its constituent types, with types that are unions of the respective members in the constituent types. Specifically, a union type used as a contextual type has the apparent members defined in section [3.11.1](#3.11.1), except that a particular member need only be present in one or more constituent types instead of all constituent types. 1367 1368## <a name="3.5"/>3.5 Intersection Types 1369 1370***Intersection types*** represent values that simultaneously have multiple types. A value of an intersection type *A* & *B* is a value that is *both* of type *A* and type *B*. Intersection types are written using intersection type literals (section [3.8.7](#3.8.7)). 1371 1372An intersection type encompasses an ordered set of constituent types. While it is generally true that *A* & *B* is equivalent to *B* & *A*, the order of the constituent types may matter when determining the call and construct signatures of the intersection type. 1373 1374Intersection types have the following subtype relationships: 1375 1376* An intersection type *I* is a subtype of a type *T* if any type in *I* is a subtype of *T*. 1377* A type *T* is a subtype of an intersection type *I* if *T* is a subtype of each type in *I*. 1378 1379Similarly, intersection types have the following assignability relationships: 1380 1381* An intersection type *I* is assignable to a type *T* if any type in *I* is assignable to *T*. 1382* A type *T* is assignable to an intersection type *I* if *T* is assignable to each type in *I*. 1383 1384For purposes of property access and function calls, the apparent members (section [3.11.1](#3.11.1)) of an intersection type are those that are present in one or more of its constituent types, with types that are intersections of the respective apparent members in the constituent types. The following examples illustrate the merging of member types that occurs when intersection types are created from object types. 1385 1386```TypeScript 1387interface A { a: number } 1388interface B { b: number } 1389 1390var ab: A & B = { a: 1, b: 1 }; 1391var a: A = ab; // A & B assignable to A 1392var b: B = ab; // A & B assignable to B 1393 1394interface X { p: A } 1395interface Y { p: B } 1396 1397var xy: X & Y = { p: ab }; // X & Y has property p of type A & B 1398 1399type F1 = (a: string, b: string) => void; 1400type F2 = (a: number, b: number) => void; 1401 1402var f: F1 & F2 = (a: string | number, b: string | number) => { }; 1403f("hello", "world"); // Ok 1404f(1, 2); // Ok 1405f(1, "test"); // Error 1406``` 1407 1408The union and intersection type operators can be applied to type parameters. This capability can for example be used to model functions that merge objects: 1409 1410```TypeScript 1411function extend<T, U>(first: T, second: U): T & U { 1412 // Extend first with properties of second 1413} 1414 1415var x = extend({ a: "hello" }, { b: 42 }); 1416var s = x.a; 1417var n = x.b; 1418``` 1419 1420It is possible to create intersection types for which no values other than null or undefined are possible. For example, intersections of primitive types such as `string & number` fall into this category. 1421 1422## <a name="3.6"/>3.6 Type Parameters 1423 1424A type parameter represents an actual type that the parameter is bound to in a generic type reference or a generic function call. Type parameters have constraints that establish upper bounds for their actual type arguments. 1425 1426Since a type parameter represents a multitude of different type arguments, type parameters have certain restrictions compared to other types. In particular, a type parameter cannot be used as a base class or interface. 1427 1428### <a name="3.6.1"/>3.6.1 Type Parameter Lists 1429 1430Class, interface, type alias, and function declarations may optionally include lists of type parameters enclosed in < and > brackets. Type parameters are also permitted in call signatures of object, function, and constructor type literals. 1431 1432  *TypeParameters:* 1433   `<` *TypeParameterList* `>` 1434 1435  *TypeParameterList:* 1436   *TypeParameter* 1437   *TypeParameterList* `,` *TypeParameter* 1438 1439  *TypeParameter:* 1440   *BindingIdentifier* *Constraint<sub>opt</sub>* 1441 1442  *Constraint:* 1443   `extends` *Type* 1444 1445Type parameter names must be unique. A compile-time error occurs if two or more type parameters in the same *TypeParameterList* have the same name. 1446 1447The scope of a type parameter extends over the entire declaration with which the type parameter list is associated, with the exception of static member declarations in classes. 1448 1449A type parameter may have an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter. 1450 1451The ***base constraint*** of a type parameter *T* is defined as follows: 1452 1453* If *T* has no declared constraint, *T*'s base constraint is the empty object type `{}`. 1454* If *T*'s declared constraint is a type parameter, *T*'s base constraint is that of the type parameter. 1455* Otherwise, *T*'s base constraint is *T*'s declared constraint. 1456 1457In the example 1458 1459```TypeScript 1460interface G<T, U extends V, V extends Function> { } 1461``` 1462 1463the base constraint of 'T' is the empty object type and the base constraint of 'U' and 'V' is 'Function'. 1464 1465For purposes of determining type relationships (section [3.11](#3.11)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)), type parameters appear to have the members of their base constraint, but no other members. 1466 1467It is an error for a type parameter to directly or indirectly be a constraint for itself. For example, both of the following declarations are invalid: 1468 1469```TypeScript 1470interface A<T extends T> { } 1471 1472interface B<T extends U, U extends T> { } 1473``` 1474 1475### <a name="3.6.2"/>3.6.2 Type Argument Lists 1476 1477A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section [4.15](#4.15)) to a generic function may explicitly include a type argument list instead of relying on type inference. 1478 1479  *TypeArguments:* 1480   `<` *TypeArgumentList* `>` 1481 1482  *TypeArgumentList:* 1483   *TypeArgument* 1484   *TypeArgumentList* `,` *TypeArgument* 1485 1486  *TypeArgument:* 1487   *Type* 1488 1489Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument for a constrained type parameter is required to ***satisfy*** the constraint of that type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters. 1490 1491Given the declaration 1492 1493```TypeScript 1494interface G<T, U extends Function> { } 1495``` 1496 1497a type reference of the form 'G<A, B>' places no requirements on 'A' but requires 'B' to be assignable to 'Function'. 1498 1499The 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. 1500 1501### <a name="3.6.3"/>3.6.3 This-types 1502 1503Every class and interface has a ***this-type*** that represents the actual type of instances of the class or interface within the declaration of the class or interface. The this-type is referenced using the keyword `this` in a type position. Within instance methods and constructors of a class, the type of the expression `this` (section [4.2](#4.2)) is the this-type of the class. 1504 1505Classes and interfaces support inheritance and therefore the instance represented by `this` in a method isn't necessarily an instance of the containing class—it may in fact be an instance of a derived class or interface. To model this relationship, the this-type of a class or interface is classified as a type parameter. Unlike other type parameters, it is not possible to explicitly pass a type argument for a this-type. Instead, in a type reference to a class or interface type, the type reference *itself* is implicitly passed as a type argument for the this-type. For example: 1506 1507```TypeScript 1508class A { 1509 foo() { 1510 return this; 1511 } 1512} 1513 1514class B extends A { 1515 bar() { 1516 return this; 1517 } 1518} 1519 1520let b: B; 1521let x = b.foo().bar(); // Fluent pattern works, type of x is B 1522``` 1523 1524In the declaration of `b` above, the type reference `B` is itself passed as a type argument for B's this-type. Thus, the referenced type is an instantiation of class `B` where all occurrences of the type `this` are replaced with `B`, and for that reason the `foo` method of `B` actually returns `B` (as opposed to `A`). 1525 1526The this-type of a given class or interface type *C* implicitly has a constraint consisting of a type reference to *C* with *C*'s own type parameters passed as type arguments and with that type reference passed as the type argument for the this-type. 1527 1528## <a name="3.7"/>3.7 Named Types 1529 1530Classes, interfaces, enums, and type aliases are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), enum declarations ([9.1](#9.1)), and type alias declarations (section [3.10](#3.10)). Classes, interfaces, and type aliases may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***. 1531 1532Interface 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. 1533 1534Named types are referenced through ***type references*** (section [3.8.2](#3.8.2)) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type. 1535 1536Named 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. 1537 1538TypeScript 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 1539 1540```TypeScript 1541interface Pair<T1, T2> { first: T1; second: T2; } 1542``` 1543 1544the type reference 1545 1546```TypeScript 1547Pair<string, Entity> 1548``` 1549 1550is indistinguishable from the type 1551 1552```TypeScript 1553{ first: string; second: Entity; } 1554``` 1555 1556## <a name="3.8"/>3.8 Specifying Types 1557 1558Types are specified either by referencing their keyword or name, or by writing object type literals, array type literals, tuple type literals, function type literals, constructor type literals, or type queries. 1559 1560  *Type:* 1561   *UnionOrIntersectionOrPrimaryType* 1562   *FunctionType* 1563   *ConstructorType* 1564 1565  *UnionOrIntersectionOrPrimaryType:* 1566   *UnionType* 1567   *IntersectionOrPrimaryType* 1568 1569  *IntersectionOrPrimaryType:* 1570   *IntersectionType* 1571   *PrimaryType* 1572 1573  *PrimaryType:* 1574   *ParenthesizedType* 1575   *PredefinedType* 1576   *TypeReference* 1577   *ObjectType* 1578   *ArrayType* 1579   *TupleType* 1580   *TypeQuery* 1581   *ThisType* 1582 1583  *ParenthesizedType:* 1584   `(` *Type* `)` 1585 1586Parentheses are required around union, intersection, function, or constructor types when they are used as array element types; around union, function, or constructor types in intersection types; and around function or constructor types in union types. For example: 1587 1588```TypeScript 1589(string | number)[] 1590((x: string) => string) | ((x: number) => number) 1591(A | B) & (C | D) 1592``` 1593 1594The different forms of type notations are described in the following sections. 1595 1596### <a name="3.8.1"/>3.8.1 Predefined Types 1597 1598The `any`, `number`, `boolean`, `string`, `symbol` and `void` keywords reference the Any type and the Number, Boolean, String, Symbol, and Void primitive types respectively. 1599 1600  *PredefinedType:* 1601   `any` 1602   `number` 1603   `boolean` 1604   `string` 1605   `symbol` 1606   `void` 1607 1608The predefined type keywords are reserved and cannot be used as names of user defined types. 1609 1610### <a name="3.8.2"/>3.8.2 Type References 1611 1612A type reference references a named type or type parameter through its name and, in the case of a generic type, supplies a type argument list. 1613 1614  *TypeReference:* 1615   *TypeName* *[no LineTerminator here]* *TypeArguments<sub>opt</sub>* 1616 1617  *TypeName:* 1618   *IdentifierReference* 1619   *NamespaceName* `.` *IdentifierReference* 1620 1621  *NamespaceName:* 1622   *IdentifierReference* 1623   *NamespaceName* `.` *IdentifierReference* 1624 1625A *TypeReference* consists of a *TypeName* that a references a named type or type parameter. A reference to a generic type must be followed by a list of *TypeArguments* (section [3.6.2](#3.6.2)). 1626 1627A *TypeName* is either a single identifier or a sequence of identifiers separated by dots. In a type name, all identifiers but the last one refer to namespaces and the last identifier refers to a named type. 1628 1629Resolution of a *TypeName* consisting of a single identifier is described in section [2.4](#2.4). 1630 1631Resolution of a *TypeName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains a named type *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. 1632 1633Resolution of a *NamespaceName* consisting of a single identifier is described in section [2.4](#2.4). Identifiers declared in namespace declarations (section [10.1](#10.1)) or import declarations (sections [10.3](#10.3), [11.3.2](#11.3.2), and [11.3.3](#11.3.3)) may be classified as namespaces. 1634 1635Resolution of a *NamespaceName* of the form *N.X*, where *N* is a *NamespaceName* and *X* is an *IdentifierReference*, proceeds by first resolving the namespace name *N*. If the resolution of *N* is successful and the export member set (sections [10.4](#10.4) and [11.3.4.4](#11.3.4.4)) of the resulting namespace contains an exported namespace member *X*, then *N.X* refers to that member. Otherwise, *N.X* is undefined. 1636 1637A type reference to a generic type is required to specify exactly one type argument for each type parameter of the referenced generic type, and each type argument must be assignable to (section [3.11.4](#3.11.4)) the constraint of the corresponding type parameter or otherwise an error occurs. An example: 1638 1639```TypeScript 1640interface A { a: string; } 1641 1642interface B extends A { b: string; } 1643 1644interface C extends B { c: string; } 1645 1646interface G<T, U extends B> { 1647 x: T; 1648 y: U; 1649} 1650 1651var v1: G<A, C>; // Ok 1652var v2: G<{ a: string }, C>; // Ok, equivalent to G<A, C> 1653var v3: G<A, A>; // Error, A not valid argument for U 1654var v4: G<G<A, B>, C>; // Ok 1655var v5: G<any, any>; // Ok 1656var v6: G<any>; // Error, wrong number of arguments 1657var v7: G; // Error, no arguments 1658``` 1659 1660A 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. 1661 1662As described in section [3.7](#3.7), 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: 1663 1664```TypeScript 1665var v1: { 1666 x: { a: string; } 1667 y: { a: string; b: string; c: string }; 1668}; 1669``` 1670 1671### <a name="3.8.3"/>3.8.3 Object Type Literals 1672 1673An object type literal defines an object type by specifying the set of members that are statically considered to be present in instances of the type. Object type literals can be given names using interface declarations but are otherwise anonymous. 1674 1675  *ObjectType:* 1676   `{` *TypeBody<sub>opt</sub>* `}` 1677 1678  *TypeBody:* 1679   *TypeMemberList* `;`*<sub>opt</sub>* 1680   *TypeMemberList* `,`*<sub>opt</sub>* 1681 1682  *TypeMemberList:* 1683   *TypeMember* 1684   *TypeMemberList* `;` *TypeMember* 1685   *TypeMemberList* `,` *TypeMember* 1686 1687  *TypeMember:* 1688   *PropertySignature* 1689   *CallSignature* 1690   *ConstructSignature* 1691   *IndexSignature* 1692   *MethodSignature* 1693 1694The members of an object type literal are specified as a combination of property, call, construct, index, and method signatures. Object type members are described in section [3.9](#3.9). 1695 1696### <a name="3.8.4"/>3.8.4 Array Type Literals 1697 1698An array type literal is written as an element type followed by an open and close square bracket. 1699 1700  *ArrayType:* 1701   *PrimaryType* *[no LineTerminator here]* `[` `]` 1702 1703An 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 namespace with the element type as a type argument. 1704 1705When union, intersection, function, or constructor types are used as array element types they must be enclosed in parentheses. For example: 1706 1707```TypeScript 1708(string | number)[] 1709(() => string)[] 1710``` 1711 1712Alternatively, array types can be written using the 'Array<T>' notation. For example, the types above are equivalent to 1713 1714```TypeScript 1715Array<string | number> 1716Array<() => string> 1717``` 1718 1719### <a name="3.8.5"/>3.8.5 Tuple Type Literals 1720 1721A tuple type literal is written as a sequence of element types, separated by commas and enclosed in square brackets. 1722 1723  *TupleType:* 1724   `[` *TupleElementTypes* `]` 1725 1726  *TupleElementTypes:* 1727   *TupleElementType* 1728   *TupleElementTypes* `,` *TupleElementType* 1729 1730  *TupleElementType:* 1731   *Type* 1732 1733A tuple type literal references a tuple type (section [3.3.3](#3.3.3)). 1734 1735### <a name="3.8.6"/>3.8.6 Union Type Literals 1736 1737A union type literal is written as a sequence of types separated by vertical bars. 1738 1739  *UnionType:* 1740   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* 1741 1742A union type literal references a union type (section [3.4](#3.4)). 1743 1744### <a name="3.8.7"/>3.8.7 Intersection Type Literals 1745 1746An intersection type literal is written as a sequence of types separated by ampersands. 1747 1748  *IntersectionType:* 1749   *IntersectionOrPrimaryType* `&` *PrimaryType* 1750 1751An intersection type literal references an intersection type (section [3.5](#3.5)). 1752 1753### <a name="3.8.8"/>3.8.8 Function Type Literals 1754 1755A function type literal specifies the type parameters, regular parameters, and return type of a call signature. 1756 1757  *FunctionType:* 1758   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type* 1759 1760A function type literal is shorthand for an object type containing a single call signature. Specifically, a function type literal of the form 1761 1762```TypeScript 1763< T1, T2, ... > ( p1, p2, ... ) => R 1764``` 1765 1766is exactly equivalent to the object type literal 1767 1768```TypeScript 1769{ < T1, T2, ... > ( p1, p2, ... ) : R } 1770``` 1771 1772Note that function types with multiple call or construct signatures cannot be written as function type literals but must instead be written as object type literals. 1773 1774### <a name="3.8.9"/>3.8.9 Constructor Type Literals 1775 1776A constructor type literal specifies the type parameters, regular parameters, and return type of a construct signature. 1777 1778  *ConstructorType:* 1779   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type* 1780 1781A constructor type literal is shorthand for an object type containing a single construct signature. Specifically, a constructor type literal of the form 1782 1783```TypeScript 1784new < T1, T2, ... > ( p1, p2, ... ) => R 1785``` 1786 1787is exactly equivalent to the object type literal 1788 1789```TypeScript 1790{ new < T1, T2, ... > ( p1, p2, ... ) : R } 1791``` 1792 1793Note that constructor types with multiple construct signatures cannot be written as constructor type literals but must instead be written as object type literals. 1794 1795### <a name="3.8.10"/>3.8.10 Type Queries 1796 1797A type query obtains the type of an expression. 1798 1799  *TypeQuery:* 1800   `typeof` *TypeQueryExpression* 1801 1802  *TypeQueryExpression:* 1803   *IdentifierReference* 1804   *TypeQueryExpression* `.` *IdentifierName* 1805 1806A type query consists of the keyword `typeof` followed by an expression. The expression is restricted to a single identifier or a sequence of identifiers separated by periods. The expression is processed as an identifier expression (section [4.3](#4.3)) or property access expression (section [4.13](#4.13)), the widened type (section [3.12](#3.12)) of which becomes the result. Similar to other static typing constructs, type queries are erased from the generated JavaScript code and add no run-time overhead. 1807 1808Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and namespace declarations. For example: 1809 1810```TypeScript 1811var a = { x: 10, y: 20 }; 1812var b: typeof a; 1813``` 1814 1815Above, 'b' is given the same type as 'a', namely `{ x: number; y: number; }`. 1816 1817If 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: 1818 1819```TypeScript 1820var c: typeof c; 1821var d: typeof e; 1822var e: typeof d; 1823var f: Array<typeof f>; 1824``` 1825 1826However, if a circular path of type queries includes at least one *ObjectType*, *FunctionType* or *ConstructorType*, the construct denotes a recursive type: 1827 1828```TypeScript 1829var g: { x: typeof g; }; 1830var h: () => typeof h; 1831``` 1832 1833Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type. 1834 1835### <a name="3.8.11"/>3.8.11 This-Type References 1836 1837The `this` keyword is used to reference the this-type (section [3.6.3](#3.6.3)) of a class or interface. 1838 1839  *ThisType:* 1840   `this` 1841 1842The meaning of a *ThisType* depends on the closest enclosing *FunctionDeclaration*, *FunctionExpression*, *PropertyDefinition*, *ClassElement*, or *TypeMember*, known as the root declaration of the *ThisType*, as follows: 1843 1844* When the root declaration is an instance member or constructor of a class, the *ThisType* references the this-type of that class. 1845* When the root declaration is a member of an interface type, the *ThisType* references the this-type of that interface. 1846* Otherwise, the *ThisType* is an error. 1847 1848Note that in order to avoid ambiguities it is not possible to reference the this-type of a class or interface in a nested object type literal. In the example 1849 1850```TypeScript 1851interface ListItem { 1852 getHead(): this; 1853 getTail(): this; 1854 getHeadAndTail(): { head: this, tail: this }; // Error 1855} 1856``` 1857 1858the `this` references on the last line are in error because their root declarations are not members of a class or interface. The recommended way to reference the this-type of an outer class or interface in an object type literal is to declare an intermediate generic type and pass `this` as a type argument. For example: 1859 1860```TypeScript 1861type HeadAndTail<T> = { head: T, tail: T }; 1862 1863interface ListItem { 1864 getHead(): this; 1865 getTail(): this; 1866 getHeadAndTail(): HeadAndTail<this>; 1867} 1868``` 1869 1870## <a name="3.9"/>3.9 Specifying Members 1871 1872The members of an object type literal (section [3.8.3](#3.8.3)) are specified as a combination of property, call, construct, index, and method signatures. 1873 1874### <a name="3.9.1"/>3.9.1 Property Signatures 1875 1876A property signature declares the name and type of a property member. 1877 1878  *PropertySignature:* 1879   *PropertyName* `?`*<sub>opt</sub>* *TypeAnnotation<sub>opt</sub>* 1880 1881  *TypeAnnotation:* 1882   `:` *Type* 1883 1884The *PropertyName* ([2.2.2](#2.2.2)) of a property signature must be unique within its containing type, and must denote a well-known symbol if it is a computed property name ([2.2.3](#2.2.3)). If the property name is followed by a question mark, the property is optional. Otherwise, the property is required. 1885 1886If a property signature omits a *TypeAnnotation*, the Any type is assumed. 1887 1888### <a name="3.9.2"/>3.9.2 Call Signatures 1889 1890A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section [4.15](#4.15)) to an instance of the containing type. A type may ***overload*** call operations by defining multiple different call signatures. 1891 1892  *CallSignature:* 1893   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>* 1894 1895A call signature that includes *TypeParameters* (section [3.6.1](#3.6.1)) is called a ***generic call signature***. Conversely, a call signature with no *TypeParameters* is called a non-generic call signature. 1896 1897As well as being members of object type literals, call signatures occur in method signatures (section [3.9.5](#3.9.5)), function expressions (section [4.10](#4.10)), and function declarations (section [6.1](#6.1)). 1898 1899An object type containing call signatures is said to be a ***function type***. 1900 1901#### <a name="3.9.2.1"/>3.9.2.1 Type Parameters 1902 1903Type parameters (section [3.6.1](#3.6.1)) in call signatures provide a mechanism for expressing the relationships of parameter and return types in call operations. For example, a signature might introduce a type parameter and use it as both a parameter type and a return type, in effect describing a function that returns a value of the same type as its argument. 1904 1905Type parameters may be referenced in parameter types and return type annotations, but not in type parameter constraints, of the call signature in which they are introduced. 1906 1907Type arguments (section [3.6.2](#3.6.2)) for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. An ***instantiation*** of a generic call signature for a particular set of type arguments is the call signature formed by replacing each type parameter with its corresponding type argument. 1908 1909Some examples of call signatures with type parameters follow below. 1910 1911A function taking an argument of any type, returning a value of that same type: 1912 1913```TypeScript 1914<T>(x: T): T 1915``` 1916 1917A function taking two values of the same type, returning an array of that type: 1918 1919```TypeScript 1920<T>(x: T, y: T): T[] 1921``` 1922 1923A function taking two arguments of different types, returning an object with properties 'x' and 'y' of those types: 1924 1925```TypeScript 1926<T, U>(x: T, y: U): { x: T; y: U; } 1927``` 1928 1929A function taking an array of one type and a function argument, returning an array of another type, where the function argument takes a value of the first array element type and returns a value of the second array element type: 1930 1931```TypeScript 1932<T, U>(a: T[], f: (x: T) => U): U[] 1933``` 1934 1935#### <a name="3.9.2.2"/>3.9.2.2 Parameter List 1936 1937A 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. 1938 1939  *ParameterList:* 1940   *RequiredParameterList* 1941   *OptionalParameterList* 1942   *RestParameter* 1943   *RequiredParameterList* `,` *OptionalParameterList* 1944   *RequiredParameterList* `,` *RestParameter* 1945   *OptionalParameterList* `,` *RestParameter* 1946   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* 1947 1948  *RequiredParameterList:* 1949   *RequiredParameter* 1950   *RequiredParameterList* `,` *RequiredParameter* 1951 1952  *RequiredParameter:* 1953   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* 1954   *BindingIdentifier* `:` *StringLiteral* 1955 1956  *AccessibilityModifier:* 1957   `public` 1958   `private` 1959   `protected` 1960 1961  *BindingIdentifierOrPattern:* 1962   *BindingIdentifier* 1963   *BindingPattern* 1964 1965  *OptionalParameterList:* 1966   *OptionalParameter* 1967   *OptionalParameterList* `,` *OptionalParameter* 1968 1969  *OptionalParameter:* 1970   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* `?` *TypeAnnotation<sub>opt</sub>* 1971   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* *Initializer* 1972   *BindingIdentifier* `?` `:` *StringLiteral* 1973 1974  *RestParameter:* 1975   `...` *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* 1976 1977A parameter declaration may specify either an identifier or a binding pattern ([5.2.2](#5.2.2)). The identifiers specified in parameter declarations and binding patterns in a parameter list must be unique within that parameter list. 1978 1979The type of a parameter in a signature is determined as follows: 1980 1981* If the declaration includes a type annotation, the parameter is of that type. 1982* Otherwise, if the declaration includes an initializer expression (which is permitted only when the parameter list occurs in conjunction with a function body), the parameter type is the widened form (section [3.12](#3.12)) of the type of the initializer expression. 1983* Otherwise, if the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section [5.2.3](#5.2.3)). 1984* Otherwise, if the parameter is a rest parameter, the parameter type is `any[]`. 1985* Otherwise, the parameter type is `any`. 1986 1987A parameter is permitted to include a `public`, `private`, or `protected` modifier only if it occurs in the parameter list of a *ConstructorImplementation* (section [8.3.1](#8.3.1)) and only if it doesn't specify a *BindingPattern*. 1988 1989A type annotation for a rest parameter must denote an array type. 1990 1991When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.9.2.4](#3.9.2.4)). Specialized signatures are not permitted in conjunction with a function body, i.e. the *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, and *ConstructorImplementation* grammar productions do not permit parameters with string literal types. 1992 1993A parameter can be marked optional by following its name or binding pattern with a question mark (`?`) or by including an initializer. Initializers (including binding property or element initializers) are permitted only when the parameter list occurs in conjunction with a function body, i.e. only in a *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, or *ConstructorImplementation* grammar production. 1994 1995*TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*. 1996 1997*TODO: Update to reflect [required parameters support initializers](https://github.com/Microsoft/TypeScript/pull/4022)*. 1998 1999#### <a name="3.9.2.3"/>3.9.2.3 Return Type 2000 2001If 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. 2002 2003When 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. 2004 2005When a call signature with no return type annotation occurs in a context that has a function body (specifically, a function implementation, a member function implementation, or a member accessor declaration), the return type is inferred from the function body as described in section [6.3](#6.3). 2006 2007#### <a name="3.9.2.4"/>3.9.2.4 Specialized Signatures 2008 2009When a parameter type annotation specifies a string literal type (section [3.2.9](#3.2.9)), the containing signature is considered a specialized signature. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. For example, the declaration 2010 2011```TypeScript 2012interface Document { 2013 createElement(tagName: "div"): HTMLDivElement; 2014 createElement(tagName: "span"): HTMLSpanElement; 2015 createElement(tagName: "canvas"): HTMLCanvasElement; 2016 createElement(tagName: string): HTMLElement; 2017} 2018``` 2019 2020states 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'. 2021 2022When 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.15.1](#4.15.1)) processes the candidates in declaration order and picks the first one that matches. 2023 2024Every 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. 2025 2026### <a name="3.9.3"/>3.9.3 Construct Signatures 2027 2028A construct signature defines the parameter list and return type associated with applying the `new` operator (section [4.14](#4.14)) to an instance of the containing type. A type may overload `new` operations by defining multiple construct signatures with different parameter lists. 2029 2030  *ConstructSignature:* 2031   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>* 2032 2033The type parameters, parameter list, and return type of a construct signature are subject to the same rules as a call signature. 2034 2035A type containing construct signatures is said to be a ***constructor type***. 2036 2037### <a name="3.9.4"/>3.9.4 Index Signatures 2038 2039An index signature defines a type constraint for properties in the containing type. 2040 2041  *IndexSignature:* 2042   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* 2043   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* 2044 2045There are two kinds of index signatures: 2046 2047* ***String index signatures***, specified using index type `string`, define type constraints for all properties and numeric index signatures in the containing type. Specifically, in a type with a string index signature of type *T*, all properties and numeric index signatures must have types that are assignable to *T*. 2048* ***Numeric index signatures***, specified using index type `number`, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type *T*, all numerically named properties must have types that are assignable to *T*. 2049 2050A ***numerically named property*** is a property whose name is a valid numeric literal. Specifically, a property with a name *N* for which ToString(ToNumber(*N*)) is identical to *N*, where ToString and ToNumber are the abstract operations defined in ECMAScript specification. 2051 2052An object type can contain at most one string index signature and one numeric index signature. 2053 2054Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section [4.13](#4.13). 2055 2056### <a name="3.9.5"/>3.9.5 Method Signatures 2057 2058A method signature is shorthand for declaring a property of a function type. 2059 2060  *MethodSignature:* 2061   *PropertyName* `?`*<sub>opt</sub>* *CallSignature* 2062 2063If the *PropertyName* is a computed property name ([2.2.3](#2.2.3)), it must specify a well-known symbol. If the *PropertyName* is followed by a question mark, the property is optional. Otherwise, the property is required. Only object type literals and interfaces can declare optional properties. 2064 2065A method signature of the form 2066 2067```TypeScript 2068f < T1, T2, ... > ( p1, p2, ... ) : R 2069``` 2070 2071is equivalent to the property declaration 2072 2073```TypeScript 2074f : { < T1, T2, ... > ( p1, p2, ... ) : R } 2075``` 2076 2077A literal type may ***overload*** a method by declaring multiple method signatures with the same name but differing parameter lists. Overloads must either all be required (question mark omitted) or all be optional (question mark included). A set of overloaded method signatures correspond to a declaration of a single property with a type composed from an equivalent set of call signatures. Specifically 2078 2079```TypeScript 2080f < T1, T2, ... > ( p1, p2, ... ) : R ; 2081f < U1, U2, ... > ( q1, q2, ... ) : S ; 2082... 2083``` 2084 2085is equivalent to 2086 2087```TypeScript 2088f : { 2089 < T1, T2, ... > ( p1, p2, ... ) : R ; 2090 < U1, U2, ... > ( q1, q2, ... ) : S ; 2091 ... 2092} ; 2093``` 2094 2095In the following example of an object type 2096 2097```TypeScript 2098{ 2099 func1(x: number): number; // Method signature 2100 func2: (x: number) => number; // Function type literal 2101 func3: { (x: number): number }; // Object type literal 2102} 2103``` 2104 2105the 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 2106 2107```TypeScript 2108{ 2109 func4(x: number): number; 2110 func4(s: string): string; 2111 func5: { 2112 (x: number): number; 2113 (s: string): string; 2114 }; 2115} 2116``` 2117 2118the properties 'func4' and 'func5' are of the same type, namely an object type with two call signatures taking and returning number and string respectively. 2119 2120## <a name="3.10"/>3.10 Type Aliases 2121 2122A type alias declaration introduces a ***type alias*** in the containing declaration space. 2123 2124  *TypeAliasDeclaration:* 2125   `type` *BindingIdentifier* *TypeParameters<sub>opt</sub>* `=` *Type* `;` 2126 2127A type alias serves as an alias for the type specified in the type alias declaration. Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types. 2128 2129A type alias may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the type alias is referenced in type references. A type alias with type parameters is called a ***generic type alias***. The type parameters of a generic type alias declaration are in scope and may be referenced in the aliased *Type*. 2130 2131Type aliases are referenced using type references ([3.8.2](#3.8.2)). Type references to generic type aliases produce instantiations of the aliased type with the given type arguments. Writing a reference to a non-generic type alias has exactly the same effect as writing the aliased type itself, and writing a reference to a generic type alias has exactly the same effect as writing the resulting instantiation of the aliased type. 2132 2133The *BindingIdentifier* of a type alias declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). 2134 2135It is an error for the type specified in a type alias to depend on that type alias. Types have the following dependencies: 2136 2137* A type alias *directly depends on* the type it aliases. 2138* A type reference *directly depends on* the referenced type and each of the type arguments, if any. 2139* A union or intersection type *directly depends on* each of the constituent types. 2140* An array type *directly depends on* its element type. 2141* A tuple type *directly depends on* each of its element types. 2142* A type query *directly depends on* the type of the referenced entity. 2143 2144Given this definition, the complete set of types upon which a type depends is the transitive closure of the *directly depends on* relationship. Note that object type literals, function type literals, and constructor type literals do not depend on types referenced within them and are therefore permitted to circularly reference themselves through type aliases. 2145 2146Some examples of type alias declarations: 2147 2148```TypeScript 2149type StringOrNumber = string | number; 2150type Text = string | { text: string }; 2151type NameLookup = Dictionary<string, Person>; 2152type ObjectStatics = typeof Object; 2153type Callback<T> = (data: T) => void; 2154type Pair<T> = [T, T]; 2155type Coordinates = Pair<number>; 2156type Tree<T> = T | { left: Tree<T>, right: Tree<T> }; 2157``` 2158 2159Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type 2160 2161```TypeScript 2162interface Point { 2163 x: number; 2164 y: number; 2165} 2166``` 2167 2168could be written as the type alias 2169 2170```TypeScript 2171type Point = { 2172 x: number; 2173 y: number; 2174}; 2175``` 2176 2177However, doing so means the following capabilities are lost: 2178 2179* An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot. 2180* An interface can have multiple merged declarations, but a type alias for an object type literal cannot. 2181 2182## <a name="3.11"/>3.11 Type Relationships 2183 2184Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections. 2185 2186### <a name="3.11.1"/>3.11.1 Apparent Members 2187 2188The ***apparent members*** of a type are the members observed in subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)). The apparent members of a type are determined as follows: 2189 2190* The apparent members of the primitive type Number and all enum types are the apparent members of the global interface type 'Number'. 2191* The apparent members of the primitive type Boolean are the apparent members of the global interface type 'Boolean'. 2192* The apparent members of the primitive type String and all string literal types are the apparent members of the global interface type 'String'. 2193* The apparent members of a type parameter are the apparent members of the constraint (section [3.6.1](#3.6.1)) of that type parameter. 2194* The apparent members of an object type *T* are the combination of the following: 2195 * The declared and/or inherited members of *T*. 2196 * The properties of the global interface type 'Object' that aren't hidden by properties with the same name in *T*. 2197 * If *T* has one or more call or construct signatures, the properties of the global interface type 'Function' that aren't hidden by properties with the same name in *T*. 2198* The apparent members of a union type *U* are determined as follows: 2199 * When all constituent types of *U* have an apparent property named *N*, *U* has an apparent property named *N* of a union type of the respective property types. 2200 * When all constituent types of *U* have an apparent call signature with a parameter list *P*, *U* has an apparent call signature with the parameter list *P* and a return type that is a union of the respective return types. The call signatures appear in the same order as in the first constituent type. 2201 * When all constituent types of *U* have an apparent construct signature with a parameter list *P*, *U* has an apparent construct signature with the parameter list *P* and a return type that is a union of the respective return types. The construct signatures appear in the same order as in the first constituent type. 2202 * When all constituent types of *U* have an apparent string index signature, *U* has an apparent string index signature of a union type of the respective string index signature types. 2203 * When all constituent types of *U* have an apparent numeric index signature, *U* has an apparent numeric index signature of a union type of the respective numeric index signature types. 2204* The apparent members of an intersection type *I* are determined as follows: 2205 * When one of more constituent types of *I* have an apparent property named *N*, *I* has an apparent property named *N* of an intersection type of the respective property types. 2206 * When one or more constituent types of *I* have a call signature *S*, *I* has the apparent call signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. 2207 * When one or more constituent types of *I* have a construct signature *S*, *I* has the apparent construct signature *S*. The signatures are ordered as a concatenation of the signatures of each constituent type in the order of the constituent types within *I*. 2208 * When one or more constituent types of *I* have an apparent string index signature, *I* has an apparent string index signature of an intersection type of the respective string index signature types. 2209 * When one or more constituent types of *I* have an apparent numeric index signature, *I* has an apparent numeric index signature of an intersection type of the respective numeric index signature types. 2210 2211If a type is not one of the above, it is considered to have no apparent members. 2212 2213In effect, a type's apparent members make it 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. 2214 2215Some examples: 2216 2217```TypeScript 2218var o: Object = { x: 10, y: 20 }; // Ok 2219var f: Function = (x: number) => x * x; // Ok 2220var err: Object = { toString: 0 }; // Error 2221``` 2222 2223The last assignment is an error because the object literal has a 'toString' method that isn't compatible with that of 'Object'. 2224 2225### <a name="3.11.2"/>3.11.2 Type and Member Identity 2226 2227Two types are considered ***identical*** when 2228 2229* they are both the Any type, 2230* they are the same primitive type, 2231* they are the same type parameter, 2232* they are union types with identical sets of constituent types, or 2233* they are intersection types with identical sets of constituent types, or 2234* they are object types with identical sets of members. 2235 2236Two members are considered identical when 2237 2238* they are public properties with identical names, optionality, and types, 2239* they are private or protected properties originating in the same declaration and having identical types, 2240* they are identical call signatures, 2241* they are identical construct signatures, or 2242* they are index signatures of identical kind with identical types. 2243 2244Two call or construct signatures are considered identical when they have the same number of type parameters with identical type parameter constraints and, after substituting type Any for the type parameters introduced by the signatures, identical number of parameters with identical kind (required, optional or rest) and types, and identical return types. 2245 2246Note that, except for primitive types and classes with private or protected members, it is structure, not naming, of types that determines identity. Also, note that parameter names are not significant when determining identity of signatures. 2247 2248Private and protected properties match only if they originate in the same declaration and have identical types. Two distinct types might contain properties that originate in the same declaration if the types are separate parameterized references to the same generic class. In the example 2249 2250```TypeScript 2251class C<T> { private x: T; } 2252 2253interface X { f(): string; } 2254 2255interface Y { f(): string; } 2256 2257var a: C<X>; 2258var b: C<Y>; 2259``` 2260 2261the 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. 2262 2263### <a name="3.11.3"/>3.11.3 Subtypes and Supertypes 2264 2265*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: 2266 2267* *S* and *T* are identical types. 2268* *T* is the Any type. 2269* *S* is the Undefined type. 2270* *S* is the Null type and *T* is not the Undefined type. 2271* *S* is an enum type and *T* is the primitive type Number. 2272* *S* is a string literal type and *T* is the primitive type String. 2273* *S* is a union type and each constituent type of *S* is a subtype of *T*. 2274* *S* is an intersection type and at least one constituent type of *S* is a subtype of *T*. 2275* *T* is a union type and *S* is a subtype of at least one constituent type of *T*. 2276* *T* is an intersection type and *S* is a subtype of each constituent type of *T*. 2277* *S* is a type parameter and the constraint of *S* is a subtype of *T*. 2278* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: 2279 * *M* is a property and *S* has an apparent property *N* where 2280 * *M* and *N* have the same name, 2281 * the type of *N* is a subtype of that of *M*, 2282 * if *M* is a required property, *N* is also a required property, and 2283 * *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. 2284 * *M* is a non-specialized call or construct signature and *S* has an apparent 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), 2285 * the signatures are of the same kind (call or construct), 2286 * *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*, 2287 * 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 2288 * the result type of *M* is Void, or the result type of *N* is a subtype of that of *M*. 2289 * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is a subtype of *U*. 2290 * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is a subtype of *U*. 2291 2292When 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. 2293 2294Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining subtype and supertype relationships. 2295 2296Also note that type parameters are not considered object types. Thus, the only subtypes of a type parameter *T* are *T* itself and other type parameters that are directly or indirectly constrained to *T*. 2297 2298### <a name="3.11.4"/>3.11.4 Assignment Compatibility 2299 2300Types 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. 2301 2302*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if *S* has no excess properties with respect to *T* ([3.11.5](#3.11.5)) and one of the following is true: 2303 2304* *S* and *T* are identical types. 2305* *S* or *T* is the Any type. 2306* *S* is the Undefined type. 2307* *S* is the Null type and *T* is not the Undefined type. 2308* *S* or *T* is an enum type and the other is the primitive type Number. 2309* *S* is a string literal type and *T* is the primitive type String. 2310* *S* is a union type and each constituent type of *S* is assignable to *T*. 2311* *S* is an intersection type and at least one constituent type of *S* is assignable to *T*. 2312* *T* is a union type and *S* is assignable to at least one constituent type of *T*. 2313* *T* is an intersection type and *S* is assignable to each constituent type of *T*. 2314* *S* is a type parameter and the constraint of *S* is assignable to *T*. 2315* *S* is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, *T* is an object type, and for each member *M* in *T*, one of the following is true: 2316 * *M* is a property and *S* has an apparent property *N* where 2317 * *M* and *N* have the same name, 2318 * the type of *N* is assignable to that of *M*, 2319 * if *M* is a required property, *N* is also a required property, and 2320 * *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. 2321 * *M* is an optional property and *S* has no apparent property of the same name as *M*. 2322 * *M* is a non-specialized call or construct signature and *S* has an apparent 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), 2323 * the signatures are of the same kind (call or construct), 2324 * *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*, 2325 * 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 2326 * the result type of *M* is Void, or the result type of *N* is assignable to that of *M*. 2327 * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is assignable to *U*. 2328 * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is assignable to *U*. 2329 2330When 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. 2331 2332Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining assignment compatibility. 2333 2334The assignment compatibility and subtyping rules differ only in that 2335 2336* the Any type is assignable to, but not a subtype of, all types, 2337* the primitive type Number is assignable to, but not a subtype of, all enum types, and 2338* an object type without a particular property is assignable to an object type in which that property is optional. 2339 2340The assignment compatibility rules imply that, when assigning values or passing parameters, optional properties must either be present and of a compatible type, or not be present at all. For example: 2341 2342```TypeScript 2343function foo(x: { id: number; name?: string; }) { } 2344 2345foo({ id: 1234 }); // Ok 2346foo({ id: 1234, name: "hello" }); // Ok 2347foo({ id: 1234, name: false }); // Error, name of wrong type 2348foo({ name: "hello" }); // Error, id required but missing 2349``` 2350 2351### <a name="3.11.5"/>3.11.5 Excess Properties 2352 2353The subtype and assignment compatibility relationships require that source types have no excess properties with respect to their target types. The purpose of this check is to detect excess or misspelled properties in object literals. 2354 2355A source type *S* is considered to have excess properties with respect to a target type *T* if 2356 2357* *S* is a fresh object literal type, as defined below, and 2358* *S* has one or more properties that aren't expected in *T*. 2359 2360A property *P* is said to be expected in a type *T* if one of the following is true: 2361 2362* *T* is not an object, union, or intersection type. 2363* *T* is an object type and 2364 * *T* has a property with the same name as *P*, 2365 * *T* has a string or numeric index signature, 2366 * *T* has no properties, or 2367 * *T* is the global type 'Object'. 2368* *T* is a union or intersection type and *P* is expected in at least one of the constituent types of *T*. 2369 2370The type inferred for an object literal (as described in section [4.5](#4.5)) is considered a ***fresh object literal type***. The freshness disappears when an object literal type is widened ([3.12](#3.12)) or is the type of the expression in a type assertion ([4.16](#4.16)). 2371 2372Consider the following example: 2373 2374```TypeScript 2375interface CompilerOptions { 2376 strict?: boolean; 2377 sourcePath?: string; 2378 targetPath?: string; 2379} 2380 2381var options: CompilerOptions = { 2382 strict: true, 2383 sourcepath: "./src", // Error, excess or misspelled property 2384 targetpath: "./bin" // Error, excess or misspelled property 2385}; 2386``` 2387 2388The 'CompilerOptions' type contains only optional properties, so without the excess property check, *any* object literal would be assignable to the 'options' variable (because a misspelled property would just be considered an excess property of a different name). 2389 2390In cases where excess properties are expected, an index signature can be added to the target type as an indicator of intent: 2391 2392```TypeScript 2393interface InputElement { 2394 name: string; 2395 visible?: boolean; 2396 [x: string]: any; // Allow additional properties of any type 2397} 2398 2399var address: InputElement = { 2400 name: "Address", 2401 visible: true, 2402 help: "Enter address here", // Allowed because of index signature 2403 shortcut: "Alt-A" // Allowed because of index signature 2404}; 2405``` 2406 2407### <a name="3.11.6"/>3.11.6 Contextual Signature Instantiation 2408 2409During type argument inference in a function call (section [4.15.2](#4.15.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: 2410 2411* Using the process described in [3.11.7](#3.11.7), 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. 2412* 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. 2413 2414### <a name="3.11.7"/>3.11.7 Type Inference 2415 2416In certain contexts, inferences for a given set of type parameters are made *from* a type *S*, in which those type parameters do not occur, *to* another type *T*, in which those type parameters do occur. Inferences consist of a set of candidate type arguments collected for each of the type parameters. The inference process recursively relates *S* and *T* to gather as many inferences as possible: 2417 2418* 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. 2419* 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*. 2420* Otherwise, if *S* and *T* are tuple types with the same number of elements, inferences are made from each element type in *S* to each corresponding element type in *T*. 2421* Otherwise, if *T* is a union or intersection type: 2422 * 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. 2423 * If the first step produced no inferences then if T is a union type 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. 2424* Otherwise, if *S* is a union or intersection type, inferences are made from each constituent type in *S* to *T*. 2425* Otherwise, if *S* and *T* are object types, then for each member *M* in *T*: 2426 * If *M* is a property and *S* contains a property *N* with the same name as *M*, inferences are made from the type of *N* to the type of *M*. 2427 * If *M* is a call signature and a corresponding call signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. 2428 * If *M* is a construct signature and a corresponding construct signature *N* exists in *S*, *N* is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in *N* to the corresponding parameter types in *M* for positions that are present in both signatures, and from the return type of *N* to the return type of *M*. 2429 * If *M* is a string index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. 2430 * If *M* is a numeric index signature and *S* contains a numeric index signature *N*, inferences are made from the type of *N* to the type of *M*. 2431 * If *M* is a numeric index signature and *S* contains a string index signature *N*, inferences are made from the type of *N* to the type of *M*. 2432 2433When comparing call or construct signatures, signatures in *S* correspond to signatures of the same kind in *T* pairwise in declaration order. If *S* and *T* have different numbers of a given kind of signature, the excess *first* signatures in declaration order of the longer list are ignored. 2434 2435*TODO: Update to reflect [improved union and intersection type inference](https://github.com/Microsoft/TypeScript/pull/5738)*. 2436 2437### <a name="3.11.8"/>3.11.8 Recursive Types 2438 2439Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type 2440 2441```TypeScript 2442interface A { next: A; } 2443``` 2444 2445contains 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: 2446 2447```TypeScript 2448interface B { next: C; } 2449 2450interface C { next: D; } 2451 2452interface D { next: B; } 2453``` 2454 2455To 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. 2456 2457When 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. 2458 2459In certain circumstances, generic types that directly or indirectly reference themselves in a recursive fashion can lead to infinite series of distinct instantiations. For example, in the type 2460 2461```TypeScript 2462interface List<T> { 2463 data: T; 2464 next: List<T>; 2465 owner: List<List<T>>; 2466} 2467``` 2468 2469'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. 2470 2471## <a name="3.12"/>3.12 Widened Types 2472 2473In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example 2474 2475```TypeScript 2476var name = "Steve"; 2477``` 2478 2479infers 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`. 2480 2481The following example shows the results of widening types to produce inferred variable types. 2482 2483```TypeScript 2484var a = null; // var a: any 2485var b = undefined; // var b: any 2486var c = { x: 0, y: null }; // var c: { x: number, y: any } 2487var d = [ null, undefined ]; // var d: any[] 2488``` 2489 2490<br/> 2491 2492# <a name="4"/>4 Expressions 2493 2494This 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. 2495 2496TypeScript'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. 2497 2498In addition to type inference and type checking, TypeScript augments JavaScript expressions with the following constructs: 2499 2500* Optional parameter and return type annotations in function expressions and arrow functions. 2501* Type arguments in function calls. 2502* Type assertions. 2503 2504Unless otherwise noted in the sections that follow, TypeScript expressions and the JavaScript expressions generated from them are identical. 2505 2506## <a name="4.1"/>4.1 Values and References 2507 2508Expressions are classified as ***values*** or ***references***. References are the subset of expressions that are permitted as the target of an assignment. Specifically, references are combinations of identifiers (section [4.3](#4.3)), parentheses (section [4.8](#4.8)), and property accesses (section [4.13](#4.13)). All other expression constructs described in this chapter are classified as values. 2509 2510## <a name="4.2"/>4.2 The this Keyword 2511 2512The type of `this` in an expression depends on the location in which the reference takes place: 2513 2514* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the this-type (section [3.6.3](#3.6.3)) of the containing class. 2515* In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class. 2516* In a function declaration or a function expression, `this` is of type Any. 2517* In the global namespace, `this` is of type Any. 2518 2519In all other contexts it is a compile-time error to reference `this`. 2520 2521Note that an arrow function (section [4.11](#4.11)) has no `this` parameter but rather preserves the `this` of its enclosing context. 2522 2523## <a name="4.3"/>4.3 Identifiers 2524 2525When an expression is an *IdentifierReference*, the expression refers to the most nested namespace, class, enum, function, variable, or parameter with that name whose scope (section [2.4](#2.4)) includes the location of the reference. The type of such an expression is the type associated with the referenced entity: 2526 2527* For a namespace, the object type associated with the namespace instance. 2528* For a class, the constructor type associated with the constructor function object. 2529* For an enum, the object type associated with the enum object. 2530* For a function, the function type associated with the function object. 2531* For a variable, the type of the variable. 2532* For a parameter, the type of the parameter. 2533 2534An identifier expression that references a variable or parameter is classified as a reference. An identifier expression that references any other kind of entity is classified as a value (and therefore cannot be the target of an assignment). 2535 2536## <a name="4.4"/>4.4 Literals 2537 2538Literals are typed as follows: 2539 2540* The type of the `null` literal is the Null primitive type. 2541* The type of the literals `true` and `false` is the Boolean primitive type. 2542* The type of numeric literals is the Number primitive type. 2543* The type of string literals is the String primitive type. 2544* The type of regular expression literals is the global interface type 'RegExp'. 2545 2546## <a name="4.5"/>4.5 Object Literals 2547 2548Object literals are extended to support type annotations in methods and get and set accessors. 2549 2550  *PropertyDefinition:* *( Modified )* 2551   *IdentifierReference* 2552   *CoverInitializedName* 2553   *PropertyName* `:` *AssignmentExpression* 2554   *PropertyName* *CallSignature* `{` *FunctionBody* `}` 2555   *GetAccessor* 2556   *SetAccessor* 2557 2558  *GetAccessor:* 2559   `get` *PropertyName* `(` `)` *TypeAnnotation<sub>opt</sub>* `{` *FunctionBody* `}` 2560 2561  *SetAccessor:* 2562   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* `)` `{` *FunctionBody* `}` 2563 2564The type of an object literal is an object type with the set of properties specified by the property assignments in the object literal. A get and set accessor may specify the same property name, but otherwise it is an error to specify multiple property assignments for the same property. 2565 2566A shorthand property assignment of the form 2567 2568```TypeScript 2569prop 2570``` 2571 2572is equivalent to 2573 2574```TypeScript 2575prop : prop 2576``` 2577 2578Likewise, a property assignment of the form 2579 2580```TypeScript 2581f ( ... ) { ... } 2582``` 2583 2584is equivalent to 2585 2586```TypeScript 2587f : function ( ... ) { ... } 2588``` 2589 2590Each property assignment in an object literal is processed as follows: 2591 2592* If the object literal is contextually typed and the contextual type contains a property with a matching name, the property assignment is contextually typed by the type of that property. 2593* Otherwise, if the object literal is contextually typed, if the contextual type contains a numeric index signature, and if the property assignment specifies a numeric property name, the property assignment is contextually typed by the type of the numeric index signature. 2594* Otherwise, if the object literal is contextually typed and the contextual type contains a string index signature, the property assignment is contextually typed by the type of the string index signature. 2595* Otherwise, the property assignment is processed without a contextual type. 2596 2597The type of a property introduced by a property assignment of the form *Name* `:` *Expr* is the type of *Expr*. 2598 2599A get accessor declaration is processed in the same manner as an ordinary function declaration (section [6.1](#6.1)) with no parameters. A set accessor declaration is processed in the same manner as an ordinary function declaration with a single parameter and a Void return type. When both a get and set accessor is declared for a property: 2600 2601* If both accessors include type annotations, the specified types must be identical. 2602* If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. 2603* If neither accessor includes a type annotation, the inferred return type of the get accessor becomes the parameter type of the set accessor. 2604 2605If a get accessor is declared for a property, the return type of the get accessor becomes the type of the property. If only a set accessor is declared for a property, the parameter type (which may be type Any if no type annotation is present) of the set accessor becomes the type of the property. 2606 2607When an object literal is contextually typed by a type that includes a string index signature, the resulting type of the object literal includes a string index signature with the union type of the types of the properties declared in the object literal, or the Undefined type if the object literal is empty. Likewise, when an object literal is contextually typed by a type that includes a numeric index signature, the resulting type of the object literal includes a numeric index signature with the union type of the types of the numerically named properties (section [3.9.4](#3.9.4)) declared in the object literal, or the Undefined type if the object literal declares no numerically named properties. 2608 2609If the *PropertyName* of a property assignment is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property assignment***. The following rules apply to dynamic property assignments: 2610 2611* A dynamic property assignment does not introduce a property in the type of the object literal. 2612* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. 2613* The name associated with a dynamic property assignment is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. 2614 2615## <a name="4.6"/>4.6 Array Literals 2616 2617An array literal 2618 2619```TypeScript 2620[ expr1, expr2, ..., exprN ] 2621``` 2622 2623denotes a value of an array type (section [3.3.2](#3.3.2)) or a tuple type (section [3.3.3](#3.3.3)) depending on context. 2624 2625Each element expression in a non-empty array literal is processed as follows: 2626 2627* If the array literal contains no spread elements, and if the array literal is contextually typed (section [4.23](#4.23)) by a type *T* and *T* has a property with the numeric name *N*, where *N* is the index of the element expression in the array literal, the element expression is contextually typed by the type of that property. 2628* Otherwise, if the array literal is contextually typed by a type *T* with a numeric index signature, the element expression is contextually typed by the type of the numeric index signature. 2629* Otherwise, the element expression is not contextually typed. 2630 2631The resulting type an array literal expression is determined as follows: 2632 2633* If the array literal is empty, the resulting type is an array type with the element type Undefined. 2634* Otherwise, if the array literal contains no spread elements and is contextually typed by a tuple-like type (section [3.3.3](#3.3.3)), the resulting type is a tuple type constructed from the types of the element expressions. 2635* Otherwise, if the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section [4.21.1](#4.21.1)), the resulting type is a tuple type constructed from the types of the element expressions. 2636* Otherwise, the resulting type is an array type with an element type that is the union of the types of the non-spread element expressions and the numeric index signature types of the spread element expressions. 2637 2638A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs. 2639 2640*TODO: The compiler currently doesn't support applying the spread operator to a string (to spread the individual characters of a string into a string array). This will eventually be allowed, but only when the code generation target is ECMAScript 2015 or later*. 2641 2642*TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*. 2643 2644The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example 2645 2646```TypeScript 2647var a = [1, 2]; // number[] 2648var b = ["hello", true]; // (string | boolean)[] 2649var c: [number, string] = [3, "three"]; // [number, string] 2650``` 2651 2652When the output target is ECMAScript 3 or 5, array literals containing spread elements are rewritten to invocations of the `concat` method. For example, the assignments 2653 2654```TypeScript 2655var a = [2, 3, 4]; 2656var b = [0, 1, ...a, 5, 6]; 2657``` 2658 2659are rewritten to 2660 2661```TypeScript 2662var a = [2, 3, 4]; 2663var b = [0, 1].concat(a, [5, 6]); 2664``` 2665 2666## <a name="4.7"/>4.7 Template Literals 2667 2668*TODO: [Template literals](https://github.com/Microsoft/TypeScript/pull/960)*. 2669 2670## <a name="4.8"/>4.8 Parentheses 2671 2672A parenthesized expression 2673 2674```TypeScript 2675( expr ) 2676``` 2677 2678has the same type and classification as the contained expression itself. Specifically, if the contained expression is classified as a reference, so is the parenthesized expression. 2679 2680## <a name="4.9"/>4.9 The super Keyword 2681 2682The `super` keyword can be used in expressions to reference base class properties and the base class constructor. 2683 2684### <a name="4.9.1"/>4.9.1 Super Calls 2685 2686Super calls consist of the keyword `super` followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes, as described in section [8.3.2](#8.3.2). 2687 2688A super call invokes the constructor of the base class on the instance referenced by `this`. A super call is processed as a function call (section [4.15](#4.15)) using the construct signatures of the base class constructor function type as the initial set of candidate signatures for overload resolution. Type arguments cannot be explicitly specified in a super call. If the base class is a generic class, the type arguments used to process a super call are always those specified in the `extends` clause that references the base class. 2689 2690The type of a super call expression is Void. 2691 2692The JavaScript code generated for a super call is specified in section [8.7.2](#8.7.2). 2693 2694### <a name="4.9.2"/>4.9.2 Super Property Access 2695 2696A super property access consists of the keyword `super` followed by a dot and an identifier. Super property accesses are used to access base class member functions from derived classes and are permitted in contexts where `this` (section [4.2](#4.2)) references a derived class instance or a derived class constructor function. Specifically: 2697 2698* In a constructor, instance member function, instance member accessor, or instance member variable initializer where `this` references a derived class instance, a super property access is permitted and must specify a public instance member function of the base class. 2699* In a static member function or static member accessor where `this` references the constructor function object of a derived class, a super property access is permitted and must specify a public static member function of the base class. 2700 2701Super property accesses are not permitted in other contexts, and it is not possible to access other kinds of base class members in a super property access. Note that super property accesses are not permitted inside function expressions nested in the above constructs because `this` is of type Any in such function expressions. 2702 2703Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section [8.4.2](#8.4.2). 2704 2705The JavaScript code generated for a super property access is specified in section [8.7.2](#8.7.2). 2706 2707*TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*. 2708 2709## <a name="4.10"/>4.10 Function Expressions 2710 2711Function expressions are extended from JavaScript to optionally include parameter and return type annotations. 2712 2713  *FunctionExpression:* *( Modified )* 2714   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}` 2715 2716The descriptions of function declarations provided in chapter [6](#6) apply to function expressions as well, except that function expressions do not support overloading. 2717 2718The 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. 2719 2720When a function expression with no type parameters and no parameter type annotations is contextually typed (section [4.23](#4.23)) by a type *T* and a contextual signature *S* can be extracted from *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *S*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *S*, the additional parameters in *S* are ignored. If the function expression has more parameters than *S*, the additional parameters are all considered to have type Any. 2721 2722Likewise, when a function expression with no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, expressions in contained return statements (section [5.10](#5.10)) are contextually typed by the return type of *S*. 2723 2724A contextual signature *S* is extracted from a function type *T* as follows: 2725 2726* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature. 2727* If *T* is a union type, let *U* be the set of element types in *T* that have call signatures. If each type in *U* has exactly one call signature and that call signature is non-generic, and if all of the signatures are identical ignoring return types, then *S* is a signature with the same parameters and a union of the return types. 2728* Otherwise, no contextual signature can be extracted from *T*. 2729 2730In the example 2731 2732```TypeScript 2733var f: (s: string) => string = function (s) { 2734 return s.toLowerCase(); 2735}; 2736``` 2737 2738the function expression is contextually typed by the type of 'f', and since the function expression has no type parameters or type annotations its parameter type information is extracted from the contextual type, thus inferring the type of 's' to be the String primitive type. 2739 2740## <a name="4.11"/>4.11 Arrow Functions 2741 2742Arrow functions are extended from JavaScript to optionally include parameter and return type annotations. 2743 2744  *ArrowFormalParameters:* *( Modified )* 2745   *CallSignature* 2746 2747The descriptions of function declarations provided in chapter [6](#6) apply to arrow functions as well, except that arrow functions do not support overloading. 2748 2749The type of an arrow function is determined in the same manner as a function expression (section [4.10](#4.10)). Likewise, parameters of an arrow function and return statements in the body of an arrow function are contextually typed in the same manner as for function expressions. 2750 2751When an arrow function with an expression body and no return type annotation is contextually typed (section [4.23](#4.23)) by a function type *T* and a contextual signature *S* can be extracted from *T*, the expression body is contextually typed by the return type of *S*. 2752 2753An arrow function expression of the form 2754 2755```TypeScript 2756( ... ) => expr 2757``` 2758 2759is exactly equivalent to 2760 2761```TypeScript 2762( ... ) => { return expr ; } 2763``` 2764 2765Furthermore, arrow function expressions of the forms 2766 2767```TypeScript 2768id => { ... } 2769id => expr 2770``` 2771 2772are exactly equivalent to 2773 2774```TypeScript 2775( id ) => { ... } 2776( id ) => expr 2777``` 2778 2779Thus, the following examples are all equivalent: 2780 2781```TypeScript 2782(x) => { return Math.sin(x); } 2783(x) => Math.sin(x) 2784x => { return Math.sin(x); } 2785x => Math.sin(x) 2786``` 2787 2788A function expression introduces a new dynamically bound `this`, whereas an arrow function expression preserves the `this` of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise often have an undefined or unexpected `this`. 2789 2790In the example 2791 2792```TypeScript 2793class Messenger { 2794 message = "Hello World"; 2795 start() { 2796 setTimeout(() => alert(this.message), 3000); 2797 } 2798}; 2799 2800var messenger = new Messenger(); 2801messenger.start(); 2802``` 2803 2804the 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: 2805 2806```TypeScript 2807class Messenger { 2808 message = "Hello World"; 2809 start() { 2810 var _this = this; 2811 setTimeout(function() { alert(_this.message); }, 3000); 2812 } 2813}; 2814 2815var messenger = new Messenger(); 2816messenger.start(); 2817``` 2818 2819The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions. 2820 2821A construct of the form 2822 2823```TypeScript 2824< T > ( ... ) => { ... } 2825``` 2826 2827could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former, but parentheses can be used to select the latter meaning: 2828 2829```TypeScript 2830< T > ( ( ... ) => { ... } ) 2831``` 2832 2833## <a name="4.12"/>4.12 Class Expressions 2834 2835*TODO: Document [class expressions](https://github.com/Microsoft/TypeScript/issues/497)*. 2836 2837## <a name="4.13"/>4.13 Property Access 2838 2839A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference. 2840 2841A dot notation property access of the form 2842 2843```TypeScript 2844object . name 2845``` 2846 2847where *object* is an expression and *name* is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time: 2848 2849* If *object* is of type Any, any *name* is permitted and the property access is of type Any. 2850* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the widened type (section [3.12](#3.12)) of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2). 2851* Otherwise, the property access is invalid and a compile-time error occurs. 2852 2853A bracket notation property access of the form 2854 2855```TypeScript 2856object [ index ] 2857``` 2858 2859where *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: 2860 2861* If *index* is a string literal or a numeric literal and *object* has an apparent property (section [3.11.1](#3.11.1)) 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. 2862* Otherwise, if *object* has an apparent 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. 2863* Otherwise, if *object* has an apparent 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. 2864* Otherwise, if *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. 2865* Otherwise, the property access is invalid and a compile-time error occurs. 2866 2867*TODO: Indexing with [symbols](https://github.com/Microsoft/TypeScript/pull/1978)*. 2868 2869The rules above mean that properties are strongly typed when accessed using bracket notation with the literal representation of their name. For example: 2870 2871```TypeScript 2872var type = { 2873 name: "boolean", 2874 primitive: true 2875}; 2876 2877var s = type["name"]; // string 2878var b = type["primitive"]; // boolean 2879``` 2880 2881Tuple types assign numeric names to each of their elements and elements are therefore strongly typed when accessed using bracket notation with a numeric literal: 2882 2883```TypeScript 2884var data: [string, number] = ["five", 5]; 2885var s = data[0]; // string 2886var n = data[1]; // number 2887``` 2888 2889## <a name="4.14"/>4.14 The new Operator 2890 2891A `new` operation has one of the following forms: 2892 2893```TypeScript 2894new C 2895new C ( ... ) 2896new C < ... > ( ... ) 2897``` 2898 2899where *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: 2900 2901* If *C* is of type Any, any argument list is permitted and the result of the operation is of type Any. 2902* If *C* has one or more apparent construct signatures (section [3.11.1](#3.11.1)), 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. 2903* If *C* has no apparent construct signatures but one or more apparent 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. 2904 2905## <a name="4.15"/>4.15 Function Calls 2906 2907Function calls are extended from JavaScript to support optional type arguments. 2908 2909  *Arguments:* *( Modified )* 2910   *TypeArguments<sub>opt</sub>* `(` *ArgumentList<sub>opt</sub>* `)` 2911 2912A function call takes one of the forms 2913 2914```TypeScript 2915func ( ... ) 2916func < ... > ( ... ) 2917``` 2918 2919where *func* is an expression of a function type or of type Any. The function expression is followed by an optional type argument list (section [3.6.2](#3.6.2)) and an argument list. 2920 2921If *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. 2922 2923If *func* has apparent call signatures (section [3.11.1](#3.11.1)) 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. 2924 2925### <a name="4.15.1"/>4.15.1 Overload Resolution 2926 2927The 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. 2928 2929*TODO: Describe use of [wildcard function types](https://github.com/Microsoft/TypeScript/issues/3970) in overload resolution*. 2930 2931The compile-time processing of a typed function call consists of the following steps: 2932 2933* First, a list of candidate signatures is constructed from the call signatures in the function type in declaration order. For classes and interfaces, inherited signatures are considered to follow explicitly declared signatures in `extends` clause order. 2934 * A non-generic signature is a candidate when 2935 * the function call has no type arguments, and 2936 * the signature is applicable with respect to the argument list of the function call. 2937 * A generic signature is a candidate in a function call without type arguments when 2938 * type inference (section [4.15.2](#4.15.2)) succeeds for each type parameter, 2939 * once the inferred type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. 2940 * A generic signature is a candidate in a function call with type arguments when 2941 * The signature has the same number of type parameters as were supplied in the type argument list, 2942 * the type arguments satisfy their constraints, and 2943 * once the type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call. 2944* If the list of candidate signatures is empty, the function call is an error. 2945* Otherwise, if the candidate list contains one or more signatures for which the type of each argument expression is a subtype of each corresponding parameter type, the return type of the first of those signatures becomes the return type of the function call. 2946* Otherwise, the return type of the first signature in the candidate list becomes the return type of the function call. 2947 2948A signature is said to be an ***applicable signature*** with respect to an argument list when 2949 2950* the number of arguments is not less than the number of required parameters, 2951* the number of arguments is not greater than the number of parameters, and 2952* for each argument expression *e* and its corresponding parameter *P,* when *e* is contextually typed (section [4.23](#4.23)) by the type of *P*, no errors ensue and the type of *e* is assignable to (section [3.11.4](#3.11.4)) the type of *P*. 2953 2954*TODO: [Spread operator in function calls](https://github.com/Microsoft/TypeScript/pull/1931) and spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into a function call*. 2955 2956### <a name="4.15.2"/>4.15.2 Type Argument Inference 2957 2958Given a signature < *T<sub>1</sub>* , *T<sub>2</sub>* , … , *T<sub>n</sub>* > ( *p<sub>1</sub>* : *P<sub>1</sub>* , *p<sub>2</sub>* : *P<sub>2</sub>* , … , *p<sub>m</sub>* : *P<sub>m</sub>* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e<sub>1</sub>* , *e<sub>2</sub>* , … , *e<sub>m</sub>* ), the task of type argument inference is to find a set of type arguments *A<sub>1</sub>*…*A<sub>n</sub>* to substitute for *T<sub>1</sub>*…*T<sub>n</sub>* such that the argument list becomes an applicable signature. 2959 2960*TODO: Update [type argument inference and overload resolution rules](https://github.com/Microsoft/TypeScript/issues/1186)*. 2961 2962Type 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: 2963 2964* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint. 2965* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the widened form (section [3.12](#3.12)) of 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. 2966* 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*. 2967 2968In order to compute candidate types, the argument list is processed as follows: 2969 2970* Initially all inferred type arguments are considered ***unfixed*** with an empty set of candidate types. 2971* Proceeding from left to right, each argument expression *e* is ***inferentially typed*** by its corresponding parameter type *P*, possibly causing some inferred type arguments to become ***fixed***, and candidate type inferences (section [3.11.7](#3.11.7)) are made for unfixed inferred type arguments from the type computed for *e* to *P*. 2972 2973The process of inferentially typing an expression *e* by a type *T* is the same as that of contextually typing *e* by *T*, with the following exceptions: 2974 2975* Where expressions contained within *e* would be contextually typed, they are instead inferentially typed. 2976* When a function expression is inferentially typed (section [4.10](#4.10)) 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. 2977* 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.11.6](#3.11.6)). 2978 2979An example: 2980 2981```TypeScript 2982function choose<T>(x: T, y: T): T { 2983 return Math.random() < 0.5 ? x : y; 2984} 2985 2986var x = choose(10, 20); // Ok, x of type number 2987var y = choose("Five", 5); // Error 2988``` 2989 2990In 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 2991 2992```TypeScript 2993var x = choose<number>(10, 20); 2994``` 2995 2996In 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. 2997 2998In the example 2999 3000```TypeScript 3001function map<T, U>(a: T[], f: (x: T) => U): U[] { 3002 var result: U[] = []; 3003 for (var i = 0; i < a.length; i++) result.push(f(a[i])); 3004 return result; 3005} 3006 3007var names = ["Peter", "Paul", "Mary"]; 3008var lengths = map(names, s => s.length); 3009``` 3010 3011inferences 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 3012 3013```TypeScript 3014var lengths = map<string, number>(names, s => s.length); 3015``` 3016 3017and the resulting type of 'lengths' is therefore 'number[]'. 3018 3019In the example 3020 3021```TypeScript 3022function zip<S, T, U>(x: S[], y: T[], combine: (x: S) => (y: T) => U): U[] { 3023 var len = Math.max(x.length, y.length); 3024 var result: U[] = []; 3025 for (var i = 0; i < len; i++) result.push(combine(x[i])(y[i])); 3026 return result; 3027} 3028 3029var names = ["Peter", "Paul", "Mary"]; 3030var ages = [7, 9, 12]; 3031var pairs = zip(names, ages, s => n => ({ name: s, age: n })); 3032``` 3033 3034inferences 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 3035 3036```TypeScript 3037var pairs = zip<string, number, { name: string; age: number }>( 3038 names, ages, s => n => ({ name: s, age: n })); 3039``` 3040 3041and the resulting type of 'pairs' is therefore '{ name: string; age: number }[]'. 3042 3043### <a name="4.15.3"/>4.15.3 Grammar Ambiguities 3044 3045The inclusion of type arguments in the *Arguments* production (section [4.15](#4.15)) gives rise to certain ambiguities in the grammar for expressions. For example, the statement 3046 3047```TypeScript 3048f(g<A, B>(7)); 3049``` 3050 3051could 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. 3052 3053The 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. 3054 3055This 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 3056 3057```TypeScript 3058f(g < A, B > 7); 3059f(g < A, B > +(7)); 3060``` 3061 3062are both interpreted as calls to 'f' with two arguments. 3063 3064## <a name="4.16"/>4.16 Type Assertions 3065 3066TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression: 3067 3068  *UnaryExpression:* *( Modified )* 3069   … 3070   `<` *Type* `>` *UnaryExpression* 3071 3072A 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. 3073 3074In a type assertion expression of the form < *T* > *e*, *e* is contextually typed (section [4.23](#4.23)) 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*. 3075 3076Type 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 3077 3078```TypeScript 3079class Shape { ... } 3080 3081class Circle extends Shape { ... } 3082 3083function createShape(kind: string): Shape { 3084 if (kind === "circle") return new Circle(); 3085 ... 3086} 3087 3088var circle = <Circle> createShape("circle"); 3089``` 3090 3091the 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'. 3092 3093As 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: 3094 3095```TypeScript 3096var shape = createShape(shapeKind); 3097if (shape instanceof Circle) { 3098 var circle = <Circle> shape; 3099 ... 3100} 3101``` 3102 3103*TODO: Document [as operator](https://github.com/Microsoft/TypeScript/pull/3564)*. 3104 3105## <a name="4.17"/>4.17 JSX Expressions 3106 3107*TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*. 3108 3109## <a name="4.18"/>4.18 Unary Operators 3110 3111The subsections that follow specify the compile-time processing rules of the unary operators. In general, if the operand of a unary operator does not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type Any in further processing. 3112 3113### <a name="4.18.1"/>4.18.1 The ++ and -- operators 3114 3115These 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. 3116 3117### <a name="4.18.2"/>4.18.2 The +, –, and ~ operators 3118 3119These operators permit their operand to be of any type and produce a result of the Number primitive type. 3120 3121The unary + operator can conveniently be used to convert a value of any type to the Number primitive type: 3122 3123```TypeScript 3124function getValue() { ... } 3125 3126var n = +getValue(); 3127``` 3128 3129The 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'. 3130 3131### <a name="4.18.3"/>4.18.3 The ! operator 3132 3133The ! operator permits its operand to be of any type and produces a result of the Boolean primitive type. 3134 3135Two unary ! operators in sequence can conveniently be used to convert a value of any type to the Boolean primitive type: 3136 3137```TypeScript 3138function getValue() { ... } 3139 3140var b = !!getValue(); 3141``` 3142 3143The 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'. 3144 3145### <a name="4.18.4"/>4.18.4 The delete Operator 3146 3147The 'delete' operator takes an operand of any type and produces a result of the Boolean primitive type. 3148 3149### <a name="4.18.5"/>4.18.5 The void Operator 3150 3151The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.7](#3.2.7)). 3152 3153### <a name="4.18.6"/>4.18.6 The typeof Operator 3154 3155The '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.8.10](#3.8.10)) to produce the type of an expression. 3156 3157```TypeScript 3158var x = 5; 3159var y = typeof x; // Use in an expression 3160var z: typeof x; // Use in a type query 3161``` 3162 3163In 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. 3164 3165## <a name="4.19"/>4.19 Binary Operators 3166 3167The 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 other types (the Other column in the tables) are provided. 3168 3169### <a name="4.19.1"/>4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators 3170 3171These 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. 3172 3173||Any|Boolean|Number|String|Other| 3174|:---:|:---:|:---:|:---:|:---:|:---:| 3175|Any|Number||Number||| 3176|Boolean|||||| 3177|Number|Number||Number||| 3178|String|||||| 3179|Other|||||| 3180 3181*TODO: Document the [exponentation operator](https://github.com/Microsoft/TypeScript/issues/4812)*. 3182 3183### <a name="4.19.2"/>4.19.2 The + operator 3184 3185The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive 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. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any. 3186 3187||Any|Boolean|Number|String|Other| 3188|:---:|:---:|:---:|:---:|:---:|:---:| 3189|Any|Any|Any|Any|String|Any| 3190|Boolean|Any|||String|| 3191|Number|Any||Number|String|| 3192|String|String|String|String|String|String| 3193|Other|Any|||String|| 3194 3195A value of any type can converted to the String primitive type by adding an empty string: 3196 3197```TypeScript 3198function getValue() { ... } 3199 3200var s = getValue() + ""; 3201``` 3202 3203The 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'. 3204 3205### <a name="4.19.3"/>4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators 3206 3207These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type. 3208 3209||Any|Boolean|Number|String|Other| 3210|:---:|:---:|:---:|:---:|:---:|:---:| 3211|Any|Boolean|Boolean|Boolean|Boolean|Boolean| 3212|Boolean|Boolean|Boolean|||| 3213|Number|Boolean||Boolean||| 3214|String|Boolean|||Boolean|| 3215|Other|Boolean||||Boolean| 3216 3217### <a name="4.19.4"/>4.19.4 The instanceof operator 3218 3219The `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. 3220 3221Note 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). 3222 3223### <a name="4.19.5"/>4.19.5 The in operator 3224 3225The `in` operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, and the right operand to be of type Any, an object type, or a type parameter type. The result is always of the Boolean primitive type. 3226 3227### <a name="4.19.6"/>4.19.6 The && operator 3228 3229The && operator permits the operands to be of any type and produces a result of the same type as the second operand. 3230 3231||Any|Boolean|Number|String|Other| 3232|:---:|:---:|:---:|:---:|:---:|:---:| 3233|Any|Any|Boolean|Number|String|Other| 3234|Boolean|Any|Boolean|Number|String|Other| 3235|Number|Any|Boolean|Number|String|Other| 3236|String|Any|Boolean|Number|String|Other| 3237|Other|Any|Boolean|Number|String|Other| 3238 3239### <a name="4.19.7"/>4.19.7 The || operator 3240 3241The || operator permits the operands to be of any type. 3242 3243If the || expression is contextually typed (section [4.23](#4.23)), the operands are contextually typed by the same type. Otherwise, the left operand is not contextually typed and the right operand is contextually typed by the type of the left operand. 3244 3245The type of the result is the union type of the two operand types. 3246 3247||Any|Boolean|Number|String|Other| 3248|:---:|:---:|:---:|:---:|:---:|:---:| 3249|Any|Any|Any|Any|Any|Any| 3250|Boolean|Any|Boolean|N | B|S | B|B | O| 3251|Number|Any|N | B|Number|S | N|N | O| 3252|String|Any|S | B|S | N|String|S | O| 3253|Other|Any|B | O|N | O|S | O|Other| 3254 3255## <a name="4.20"/>4.20 The Conditional Operator 3256 3257In a conditional expression of the form 3258 3259```TypeScript 3260test ? expr1 : expr2 3261``` 3262 3263the *test* expression may be of any type. 3264 3265If the conditional expression is contextually typed (section [4.23](#4.23)), *expr1* and *expr2* are contextually typed by the same type. Otherwise, *expr1* and *expr2* are not contextually typed. 3266 3267The type of the result is the union type of the types of *expr1* and *expr2*. 3268 3269## <a name="4.21"/>4.21 Assignment Operators 3270 3271An assignment of the form 3272 3273```TypeScript 3274v = expr 3275``` 3276 3277requires *v* to be classified as a reference (section [4.1](#4.1)) or as an assignment pattern (section [4.21.1](#4.21.1)). The *expr* expression is contextually typed (section [4.23](#4.23)) by the type of *v*, and the type of *expr* must be assignable to (section [3.11.4](#3.11.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*. 3278 3279A compound assignment of the form 3280 3281```TypeScript 3282v ??= expr 3283``` 3284 3285where ??= is one of the compound assignment operators 3286 3287```TypeScript 3288*= /= %= += -= <<= >>= >>>= &= ^= |= 3289``` 3290 3291is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires *v* to be classified as a reference (section [4.1](#4.1)) and the type of the non-compound operation to be assignable to the type of *v*. Note that *v* is not permitted to be an assignment pattern in a compound assignment. 3292 3293### <a name="4.21.1"/>4.21.1 Destructuring Assignment 3294 3295A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 2015 specification. 3296 3297In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true: 3298 3299* *V* is variable and *S* is assignable to the type of *V*. 3300* *V* is an object assignment pattern and, for each assignment property *P* in *V*, 3301 * *S* is the type Any, or 3302 * *S* has an apparent property with the property name specified in *P* of a type that is assignable to the target given in *P*, or 3303 * *P* specifies a numeric property name and *S* has a numeric index signature of a type that is assignable to the target given in *P*, or 3304 * *S* has a string index signature of a type that is assignable to the target given in *P*. 3305* *V* is an array assignment pattern, *S* is the type Any or an array-like type (section [3.3.2](#3.3.2)), and, for each assignment element *E* in *V*, 3306 * *S* is the type Any, or 3307 * *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or 3308 * *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*. 3309 3310*TODO: [Update to specify behavior when assignment element E is a rest element](https://github.com/Microsoft/TypeScript/issues/2713)*. 3311 3312In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element. 3313 3314When the output target is ECMAScript 2015 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment 3315 3316```TypeScript 3317var x = 1; 3318var y = 2; 3319[x, y] = [y, x]; 3320``` 3321 3322is rewritten to the simple variable assignments 3323 3324```TypeScript 3325var x = 1; 3326var y = 2; 3327_a = [y, x], x = _a[0], y = _a[1]; 3328var _a; 3329``` 3330 3331## <a name="4.22"/>4.22 The Comma Operator 3332 3333The comma operator permits the operands to be of any type and produces a result that is of the same type as the second operand. 3334 3335## <a name="4.23"/>4.23 Contextually Typed Expressions 3336 3337Type checking of an expression is improved in several contexts by factoring in the type of the destination of the value computed by the expression. In such situations, the expression is said to be ***contextually typed*** by the type of the destination. An expression is contextually typed in the following circumstances: 3338 3339* In a variable, parameter, binding property, binding element, or member declaration, an initializer expression is contextually typed by 3340 * the type given in the declaration's type annotation, if any, or otherwise 3341 * for a parameter, the type provided by a contextual signature (section [4.10](#4.10)), if any, or otherwise 3342 * the type implied by the binding pattern in the declaration (section [5.2.3](#5.2.3)), if any. 3343* In the body of a function declaration, function expression, arrow function, method declaration, or get accessor declaration that has a return type annotation, return expressions are contextually typed by the type given in the return type annotation. 3344* In the body of a function expression or arrow function that has no return type annotation, if the function expression or arrow function is contextually typed by a function type with exactly one call signature, and if that call signature is non-generic, return expressions are contextually typed by the return type of that call signature. 3345* In the body of a constructor declaration, return expressions are contextually typed by the containing class type. 3346* In the body of a get accessor with no return type annotation, if a matching set accessor exists and that set accessor has a parameter type annotation, return expressions are contextually typed by the type given in the set accessor's parameter type annotation. 3347* In a typed function call, argument expressions are contextually typed by their corresponding parameter types. 3348* In a contextually typed object literal, each property value expression is contextually typed by 3349 * the type of the property with a matching name in the contextual type, if any, or otherwise 3350 * for a numerically named property, the numeric index type of the contextual type, if any, or otherwise 3351 * the string index type of the contextual type, if any. 3352* In a contextually typed array literal expression containing no spread elements, an element expression at index *N* is contextually typed by 3353 * the type of the property with the numeric name *N* in the contextual type, if any, or otherwise 3354 * the numeric index type of the contextual type, if any. 3355* In a contextually typed array literal expression containing one or more spread elements, an element expression at index *N* is contextually typed by the numeric index type of the contextual type, if any. 3356* In a contextually typed parenthesized expression, the contained expression is contextually typed by the same type. 3357* In a type assertion, the expression is contextually typed by the indicated type. 3358* In a || operator expression, if the expression is contextually typed, the operands are contextually typed by the same type. Otherwise, the right expression is contextually typed by the type of the left expression. 3359* In a contextually typed conditional operator expression, the operands are contextually typed by the same type. 3360* In an assignment expression, the right hand expression is contextually typed by the type of the left hand expression. 3361 3362In the following example 3363 3364```TypeScript 3365interface EventObject { 3366 x: number; 3367 y: number; 3368} 3369 3370interface EventHandlers { 3371 mousedown?: (event: EventObject) => void; 3372 mouseup?: (event: EventObject) => void; 3373 mousemove?: (event: EventObject) => void; 3374} 3375 3376function setEventHandlers(handlers: EventHandlers) { ... } 3377 3378setEventHandlers({ 3379 mousedown: e => { startTracking(e.x, e.y); }, 3380 mouseup: e => { endTracking(); } 3381}); 3382``` 3383 3384the 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'. 3385 3386## <a name="4.24"/>4.24 Type Guards 3387 3388Type 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. 3389 3390```TypeScript 3391function foo(x: number | string) { 3392 if (typeof x === "string") { 3393 return x.length; // x has type string here 3394 } 3395 else { 3396 return x + 1; // x has type number here 3397 } 3398} 3399``` 3400 3401The type of a variable or parameter is narrowed in the following situations: 3402 3403* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided no part of the 'if' statement contains assignments to the variable or parameter. 3404* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided no part of the 'if' statement contains assignments to the variable or parameter. 3405* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when true*, provided no part of the conditional expression contains assignments to the variable or parameter. 3406* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when false*, provided no part of the conditional expression contains assignments to the variable or parameter. 3407* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when true*, provided neither operand contains assignments to the variable or parameter. 3408* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when false*, provided neither operand contains assignments to the variable or parameter. 3409 3410A 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: 3411 3412* A type guard of the form `x instanceof C`, where *x* is not of type Any, *C* is of a subtype of the global type 'Function', and *C* has a property named 'prototype' 3413 * *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, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the type of the 'prototype' property in *C*, or 3414 * *when false*, has no effect on the type of *x*. 3415* A type guard of the form `typeof x === s`, where *s* is a string literal with the value 'string', 'number', or 'boolean', 3416 * *when true*, narrows the type of *x* to the given primitive type provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the given primitive type, or 3417 * *when false*, removes the primitive type from the type of *x*. 3418* A type guard of the form `typeof x === s`, where *s* is a string literal with any value but 'string', 'number', or 'boolean', 3419 * *when true*, if *x* is a union type, removes from the type of *x* all constituent types that are subtypes of the string, number, or boolean primitive type, or 3420 * *when false*, has no effect on the type of *x*. 3421* A type guard of the form `typeof x !== s`, where *s* is a string literal, 3422 * *when true*, narrows the type of x by `typeof x === s` *when false*, or 3423 * *when false*, narrows the type of x by `typeof x === s` *when true*. 3424* A type guard of the form `!expr` 3425 * *when true*, narrows the type of *x* by *expr* *when false*, or 3426 * *when false*, narrows the type of *x* by *expr* *when true*. 3427* A type guard of the form `expr1 && expr2` 3428 * *when true*, narrows the type of *x* by *expr<sub>1</sub>* *when true* and then by *expr<sub>2</sub>* *when true*, or 3429 * *when false*, narrows the type of *x* to *T<sub>1</sub>* | *T<sub>2</sub>*, where *T<sub>1</sub>* is the type of *x* narrowed by *expr<sub>1</sub>* *when false*, and *T<sub>2</sub>* is the type of *x* narrowed by *expr<sub>1</sub>* *when true* and then by *expr<sub>2</sub>* *when false*. 3430* A type guard of the form `expr1 || expr2` 3431 * *when true*, narrows the type of *x* to *T<sub>1</sub>* | *T<sub>2</sub>*, where *T<sub>1</sub>* is the type of *x* narrowed by *expr<sub>1</sub>* *when true*, and *T<sub>2</sub>* is the type of *x* narrowed by *expr<sub>1</sub>* *when false* and then by *expr<sub>2</sub>* *when true*, or 3432 * *when false*, narrows the type of *x* by *expr<sub>1</sub>* *when false* and then by *expr<sub>2</sub>* *when false*. 3433* A type guard of any other form has no effect on the type of *x*. 3434 3435In the rules above, when a narrowing operation would remove all constituent types from a union type, the operation has no effect on the union type. 3436 3437Note 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. 3438 3439*TODO: Document [user defined type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*. 3440 3441In the example 3442 3443```TypeScript 3444function isLongString(obj: any) { 3445 return typeof obj === "string" && obj.length > 100; 3446} 3447``` 3448 3449the `obj` parameter has type `string` in the right operand of the && operator. 3450 3451In the example 3452 3453```TypeScript 3454function processValue(value: number | (() => number)) { 3455 var x = typeof value !== "number" ? value() : value; 3456 // Process number in x 3457} 3458``` 3459 3460the value parameter has type `() => number` in the first conditional expression and type `number` in the second conditional expression, and the inferred type of x is `number`. 3461 3462In the example 3463 3464```TypeScript 3465function f(x: string | number | boolean) { 3466 if (typeof x === "string" || typeof x === "number") { 3467 var y = x; // Type of y is string | number 3468 } 3469 else { 3470 var z = x; // Type of z is boolean 3471 } 3472} 3473``` 3474 3475the type of x is `string | number | boolean` in the 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. 3476 3477In the example 3478 3479```TypeScript 3480class C { 3481 data: string | string[]; 3482 getData() { 3483 var data = this.data; 3484 return typeof data === "string" ? data : data.join(" "); 3485 } 3486} 3487``` 3488 3489the type of the `data` variable is `string` in the first conditional expression and `string[]` in the second conditional expression, and the inferred type of `getData` is `string`. Note that the `data` property must be copied to a local variable for the type guard to have an effect. 3490 3491In the example 3492 3493```TypeScript 3494class NamedItem { 3495 name: string; 3496} 3497 3498function getName(obj: Object) { 3499 return obj instanceof NamedItem ? obj.name : "unknown"; 3500} 3501``` 3502 3503the type of `obj` is narrowed to `NamedItem` in the first conditional expression, and the inferred type of the `getName` function is `string`. 3504 3505<br/> 3506 3507# <a name="5"/>5 Statements 3508 3509This chapter describes the static type checking TypeScript provides for JavaScript statements. TypeScript itself does not introduce any new statement constructs, but it does extend the grammar for local declarations to include interface, type alias, and enum declarations. 3510 3511## <a name="5.1"/>5.1 Blocks 3512 3513Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar). 3514 3515  *Declaration:* *( Modified )* 3516   … 3517   *InterfaceDeclaration* 3518   *TypeAliasDeclaration* 3519   *EnumDeclaration* 3520 3521Local class, interface, type alias, and enum declarations are block scoped, similar to let and const declarations. 3522 3523## <a name="5.2"/>5.2 Variable Statements 3524 3525Variable statements are extended to include optional type annotations. 3526 3527  *VariableDeclaration:* *( Modified )* 3528   *SimpleVariableDeclaration* 3529   *DestructuringVariableDeclaration* 3530 3531A variable declaration is either a simple variable declaration or a destructuring variable declaration. 3532 3533### <a name="5.2.1"/>5.2.1 Simple Variable Declarations 3534 3535A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value. 3536 3537  *SimpleVariableDeclaration:* 3538   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 3539 3540The type *T* of a variable introduced by a simple variable declaration is determined as follows: 3541 3542* If the declaration includes a type annotation, *T* is that type. 3543* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. 3544* Otherwise, *T* is the Any type. 3545 3546When a variable declaration specifies both a type annotation and an initializer expression, the type of the initializer expression is required to be assignable to (section [3.11.4](#3.11.4)) the type given in the type annotation. 3547 3548Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable. 3549 3550When a variable declaration has a type annotation, it is an error for that type annotation to use the `typeof` operator to reference the variable being declared. 3551 3552Below are some examples of simple variable declarations and their associated types. 3553 3554```TypeScript 3555var a; // any 3556var b: number; // number 3557var c = 1; // number 3558var d = { x: 1, y: "hello" }; // { x: number; y: string; } 3559var e: any = "test"; // any 3560``` 3561 3562The following is permitted because all declarations of the single variable 'x' associate the same type (Number) with 'x'. 3563 3564```TypeScript 3565var x = 1; 3566var x: number; 3567if (x == 1) { 3568 var x = 2; 3569} 3570``` 3571 3572In the following example, all five variables are of the same type, '{ x: number; y: number; }'. 3573 3574```TypeScript 3575interface Point { x: number; y: number; } 3576 3577var a = { x: 0, y: <number> undefined }; 3578var b: Point = { x: 0, y: undefined }; 3579var c = <Point> { x: 0, y: undefined }; 3580var d: { x: number; y: number; } = { x: 0, y: undefined }; 3581var e = <{ x: number; y: number; }> { x: 0, y: undefined }; 3582``` 3583 3584### <a name="5.2.2"/>5.2.2 Destructuring Variable Declarations 3585 3586A ***destructuring variable declaration*** introduces zero or more named variables and initializes them with values extracted from properties of an object or elements of an array. 3587 3588  *DestructuringVariableDeclaration:* 3589   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer* 3590 3591Each binding property or element that specifies an identifier introduces a variable by that name. The type of the variable is the widened form (section [3.12](#3.12)) of the type associated with the binding property or element, as defined in the following. 3592 3593*TODO: Document destructuring an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array*. 3594 3595The type *T* associated with a destructuring variable declaration is determined as follows: 3596 3597* If the declaration includes a type annotation, *T* is that type. 3598* Otherwise, if the declaration includes an initializer expression, *T* is the type of that initializer expression. 3599* Otherwise, *T* is the Any type. 3600 3601The type *T* associated with a binding property is determined as follows: 3602 3603* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. 3604* If *S* is the Any type: 3605 * If the binding property specifies an initializer expression, *T* is the type of that initializer expression. 3606 * Otherwise, *T* is the Any type. 3607* Let *P* be the property name specified in the binding property. 3608* If *S* has an apparent property with the name *P*, *T* is the type of that property. 3609* Otherwise, if *S* has a numeric index signature and *P* is a numerical name, *T* is the type of the numeric index signature. 3610* Otherwise, if *S* has a string index signature, *T* is the type of the string index signature. 3611* Otherwise, no type is associated with the binding property and an error occurs. 3612 3613The type *T* associated with a binding element is determined as follows: 3614 3615* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. 3616* If *S* is the Any type: 3617 * If the binding element specifies an initializer expression, *T* is the type of that initializer expression. 3618 * Otherwise, *T* is the Any type. 3619* If *S* is not an array-like type (section [3.3.2](#3.3.2)), no type is associated with the binding property and an error occurs. 3620* If the binding element is a rest element, *T* is an array type with an element type *E*, where *E* is the type of the numeric index signature of *S*. 3621* Otherwise, if *S* is a tuple-like type (section [3.3.3](#3.3.3)): 3622 * Let *N* be the zero-based index of the binding element in the array binding pattern. 3623 * If *S* has a property with the numerical name *N*, *T* is the type of that property. 3624 * Otherwise, no type is associated with the binding element and an error occurs. 3625* Otherwise, if *S* has a numeric index signature, *T* is the type of the numeric index signature. 3626* Otherwise, no type is associated with the binding element and an error occurs. 3627 3628When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element. 3629 3630*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*. 3631 3632When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. 3633 3634When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form 3635 3636```TypeScript 3637var { x, p: y, q: z = false } = getSomeObject(); 3638``` 3639 3640is rewritten to the simple variable declarations 3641 3642```TypeScript 3643var _a = getSomeObject(), 3644 x = _a.x, 3645 y = _a.p, 3646 _b = _a.q, 3647 z = _b === void 0 ? false : _b; 3648``` 3649 3650The '_a' and '_b' temporary variables exist to ensure the assigned expression is evaluated only once, and the expression 'void 0' simply denotes the JavaScript value 'undefined'. 3651 3652Similarly, an array destructuring declaration of the form 3653 3654```TypeScript 3655var [x, y, z = 10] = getSomeArray(); 3656``` 3657 3658is rewritten to the simple variable declarations 3659 3660```TypeScript 3661var _a = getSomeArray(), 3662 x = _a[0], 3663 y = _a[1], 3664 _b = _a[2], 3665 z = _b === void 0 ? 10 : _b; 3666``` 3667 3668Combining both forms of destructuring, the example 3669 3670```TypeScript 3671var { x, p: [y, z = 10] = getSomeArray() } = getSomeObject(); 3672``` 3673 3674is rewritten to 3675 3676```TypeScript 3677var _a = getSomeObject(), 3678 x = _a.x, 3679 _b = _a.p, 3680 _c = _b === void 0 ? getSomeArray() : _b, 3681 y = _c[0], 3682 _d = _c[1], 3683 z = _d === void 0 ? 10 : _d; 3684``` 3685 3686### <a name="5.2.3"/>5.2.3 Implied Type 3687 3688A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows: 3689 3690* If the declaration specifies an object binding pattern, the implied type is an object type with a set of properties corresponding to the specified binding property declarations. The type of each property is the type implied by its binding property declaration, and a property is optional when its binding property declaration specifies an initializer expression. 3691* If the declaration specifies an array binding pattern without a rest element, the implied type is a tuple type with elements corresponding to the specified binding element declarations. The type of each element is the type implied by its binding element declaration. 3692* If the declaration specifies an array binding pattern with a rest element, the implied type is an array type with an element type of Any. 3693 3694The implied type of a binding property or binding element declaration is 3695 3696* the type of the declaration's initializer expression, if any, or otherwise 3697* the implied type of the binding pattern specified in the declaration, if any, or otherwise 3698* the type Any. 3699 3700In the example 3701 3702```TypeScript 3703function f({ a, b = "hello", c = 1 }) { ... } 3704``` 3705 3706the implied type of the binding pattern in the function's parameter is '{ a: any; b?: string; c?: number; }'. Since the parameter has no type annotation, this becomes the type of the parameter. 3707 3708In the example 3709 3710```TypeScript 3711var [a, b, c] = [1, "hello", true]; 3712``` 3713 3714the array literal initializer expression is contextually typed by the implied type of the binding pattern, specifically the tuple type '[any, any, any]'. Because the contextual type is a tuple type, the resulting type of the array literal is the tuple type '[number, string, boolean]', and the destructuring declaration thus gives the types number, string, and boolean to a, b, and c respectively. 3715 3716## <a name="5.3"/>5.3 Let and Const Declarations 3717 3718Let and const declarations are extended to include optional type annotations. 3719 3720  *LexicalBinding:* *( Modified )* 3721   *SimpleLexicalBinding* 3722   *DestructuringLexicalBinding* 3723 3724  *SimpleLexicalBinding:* 3725   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 3726 3727  *DestructuringLexicalBinding:* 3728   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 3729 3730*TODO: Document scoping and types of [let and const declarations](https://github.com/Microsoft/TypeScript/pull/904)*. 3731 3732## <a name="5.4"/>5.4 If, Do, and While Statements 3733 3734Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean). 3735 3736## <a name="5.5"/>5.5 For Statements 3737 3738Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.2](#5.2)). 3739 3740## <a name="5.6"/>5.6 For-In Statements 3741 3742In a 'for-in' statement of the form 3743 3744```TypeScript 3745for (v in expr) statement 3746``` 3747 3748*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. 3749 3750In a 'for-in' statement of the form 3751 3752```TypeScript 3753for (var v in expr) statement 3754``` 3755 3756*v* must be a variable declaration without a type annotation that declares a variable of type Any, and *expr* must be an expression of type Any, an object type, or a type parameter type. 3757 3758## <a name="5.7"/>5.7 For-Of Statements 3759 3760*TODO: Document [for-of statements](https://github.com/Microsoft/TypeScript/issues/7)*. 3761 3762## <a name="5.8"/>5.8 Continue Statements 3763 3764A '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. 3765 3766## <a name="5.9"/>5.9 Break Statements 3767 3768A '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. 3769 3770## <a name="5.10"/>5.10 Return Statements 3771 3772It 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 namespace bodies. 3773 3774A '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. 3775 3776When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.23](#4.23)) 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. 3777 3778In 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). 3779 3780In the example 3781 3782```TypeScript 3783function f(): (x: string) => number { 3784 return s => s.length; 3785} 3786``` 3787 3788the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'. 3789 3790## <a name="5.11"/>5.11 With Statements 3791 3792Use 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. 3793 3794## <a name="5.12"/>5.12 Switch Statements 3795 3796In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.11.4](#3.11.4)) the type of the 'switch' expression. 3797 3798## <a name="5.13"/>5.13 Throw Statements 3799 3800The expression specified in a 'throw' statement can be of any type. 3801 3802## <a name="5.14"/>5.14 Try Statements 3803 3804The 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. 3805 3806<br/> 3807 3808# <a name="6"/>6 Functions 3809 3810TypeScript extends JavaScript functions to include type parameters, parameter and return type annotations, overloads, default parameter values, and rest parameters. 3811 3812## <a name="6.1"/>6.1 Function Declarations 3813 3814Function declarations are extended to permit the function body to be omitted in overload declarations. 3815 3816  *FunctionDeclaration:* *( Modified )* 3817   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}` 3818   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `;` 3819 3820A *FunctionDeclaration* introduces a named value of a function type in the containing declaration space. The *BindingIdentifier* is optional only when the function declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). 3821 3822Function declarations that specify a body are called ***function implementations*** and function declarations without a body are called ***function overloads***. It is possible to specify multiple overloads for the same function (i.e. for the same name in the same declaration space), but a function can have at most one implementation. All declarations for the same function must specify the same set of modifiers (i.e. the same combination of `declare`, `export`, and `default`). 3823 3824When a function has overload declarations, the overloads determine the call signatures of the type given to the function object and the function implementation signature (if any) must be assignable to that type. Otherwise, the function implementation itself determines the call signature. 3825 3826When a function has both overloads and an implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. 3827 3828## <a name="6.2"/>6.2 Function Overloads 3829 3830Function 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.15](#4.15). 3831 3832Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost. 3833 3834The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the `?` form when specifying optional parameters. 3835 3836The following is an example of a function with overloads. 3837 3838```TypeScript 3839function attr(name: string): string; 3840function attr(name: string, value: string): Accessor; 3841function attr(map: any): Accessor; 3842function attr(nameOrMap: any, value?: string): any { 3843 if (nameOrMap && typeof nameOrMap === "string") { 3844 // handle string case 3845 } 3846 else { 3847 // handle map case 3848 } 3849} 3850``` 3851 3852Note that each overload and the final implementation specify the same identifier. The type of the local variable 'attr' introduced by this declaration is 3853 3854```TypeScript 3855var attr: { 3856 (name: string): string; 3857 (name: string, value: string): Accessor; 3858 (map: any): Accessor; 3859}; 3860``` 3861 3862Note that the signature of the actual function implementation is not included in the type. 3863 3864## <a name="6.3"/>6.3 Function Implementations 3865 3866A 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: 3867 3868* If there are no return statements with expressions in *f*'s function body, the inferred return type is Void. 3869* 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. 3870* Otherwise, if *f* is a contextually typed function expression (section [4.10](#4.10)), the inferred return type is the union type (section [3.4](#3.4)) of the types of the return statement expressions in the function body, ignoring return statements with no expressions. 3871* 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.11.3](#3.11.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. 3872 3873In the example 3874 3875```TypeScript 3876function f(x: number) { 3877 if (x <= 0) return x; 3878 return g(x); 3879} 3880 3881function g(x: number) { 3882 return f(x - 1); 3883} 3884``` 3885 3886the 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. 3887 3888An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent 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. 3889 3890The type of 'this' in a function implementation is the Any type. 3891 3892In 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.23](#4.23)) 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.12](#3.12)) of the type of the initializer expression. 3893 3894Initializer expressions are evaluated in the scope of the function body but are not permitted to reference local variables and are only permitted to access parameters that are declared to the left of the parameter they initialize, unless the parameter reference occurs in a nested function expression. 3895 3896When the output target is ECMAScript 3 or 5, for each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section [6.6](#6.6). The example 3897 3898```TypeScript 3899function strange(x: number, y = x * 2, z = x + y) { 3900 return z; 3901} 3902``` 3903 3904generates JavaScript that is equivalent to 3905 3906```TypeScript 3907function strange(x, y, z) { 3908 if (y === void 0) { y = x * 2; } 3909 if (z === void 0) { z = x + y; } 3910 return z; 3911} 3912``` 3913 3914In the example 3915 3916```TypeScript 3917var x = 1; 3918function f(a = x) { 3919 var x = "hello"; 3920} 3921``` 3922 3923the 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. 3924 3925## <a name="6.4"/>6.4 Destructuring Parameter Declarations 3926 3927Parameter declarations can specify binding patterns (section [3.9.2.2](#3.9.2.2)) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [5.2.2](#5.2.2)), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter. 3928 3929The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type *T* associated with a destructuring parameter declaration is determined as follows: 3930 3931* If the declaration includes a type annotation, *T* is that type. 3932* If the declaration occurs in a function expression for which a contextual signature is available (section [4.10](#4.10)), *T* is the type obtained from the contextual signature. 3933* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.12](#3.12)) of the type of the initializer expression. 3934* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.2.3](#5.2.3)). 3935* Otherwise, if the parameter is a rest parameter, *T* is `any[]`. 3936* Otherwise, *T* is `any`. 3937 3938When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. 3939 3940The example 3941 3942```TypeScript 3943function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) { 3944 // Draw text 3945} 3946``` 3947 3948declares a function `drawText` that takes a single parameter of the type 3949 3950```TypeScript 3951{ text?: string; location?: [number, number]; bold?: boolean; } 3952``` 3953 3954When the output target is ECMAScript 3 or 5, the function is rewritten to 3955 3956```TypeScript 3957function drawText(_a) { 3958 var _b = _a.text, 3959 text = _b === void 0 ? "" : _b, 3960 _c = _a.location, 3961 _d = _c === void 0 ? [0, 0] : _c, 3962 x = _d[0], 3963 y = _d[1], 3964 _e = _a.bold, 3965 bold = _e === void 0 ? false : _e; 3966 // Draw text 3967} 3968``` 3969 3970Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example 3971 3972```TypeScript 3973interface DrawTextInfo { 3974 text?: string; 3975 location?: [number, number]; 3976 bold?: boolean; 3977} 3978 3979function drawText({ text, location: [x, y], bold }: DrawTextInfo) { 3980 // Draw text 3981} 3982``` 3983 3984## <a name="6.5"/>6.5 Generic Functions 3985 3986A function implementation may include type parameters in its signature (section [3.9.2.1](#3.9.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. 3987 3988Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation. 3989 3990The following is an example of a generic function: 3991 3992```TypeScript 3993interface Comparable { 3994 localeCompare(other: any): number; 3995} 3996 3997function compare<T extends Comparable>(x: T, y: T): number { 3998 if (x == null) return y == null ? 0 : -1; 3999 if (y == null) return 1; 4000 return x.localeCompare(y); 4001} 4002``` 4003 4004Note 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.6.1](#3.6.1). 4005 4006The 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.15.2](#4.15.2)) from the types of the regular arguments in the call. In the example 4007 4008```TypeScript 4009class Person { 4010 name: string; 4011 localeCompare(other: Person) { 4012 return compare(this.name, other.name); 4013 } 4014} 4015``` 4016 4017the type argument to 'compare' is automatically inferred to be the String type because the two arguments are strings. 4018 4019## <a name="6.6"/>6.6 Code Generation 4020 4021A function declaration generates JavaScript code that is equivalent to: 4022 4023```TypeScript 4024function <FunctionName>(<FunctionParameters>) { 4025 <DefaultValueAssignments> 4026 <FunctionStatements> 4027} 4028``` 4029 4030*FunctionName* is the name of the function (or nothing in the case of a function expression). 4031 4032*FunctionParameters* is a comma separated list of the function's parameter names. 4033 4034*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 4035 4036```TypeScript 4037if (<Parameter> === void 0) { <Parameter> = <Default>; } 4038``` 4039 4040where *Parameter* is the parameter name and *Default* is the default value expression. 4041 4042*FunctionStatements* is the code generated for the statements specified in the function body. 4043 4044## <a name="6.7"/>6.7 Generator Functions 4045 4046*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*. 4047 4048## <a name="6.8"/>6.8 Asynchronous Functions 4049 4050*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*. 4051 4052## <a name="6.9"/>6.9 Type Guard Functions 4053 4054*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*. 4055 4056<br/> 4057 4058# <a name="7"/>7 Interfaces 4059 4060Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones. 4061 4062Interfaces 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. 4063 4064Because 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.11.2](#3.11.2)). 4065 4066Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces. 4067 4068## <a name="7.1"/>7.1 Interface Declarations 4069 4070An interface declaration declares an ***interface type***. 4071 4072  *InterfaceDeclaration:* 4073   `interface` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *InterfaceExtendsClause<sub>opt</sub>* *ObjectType* 4074 4075  *InterfaceExtendsClause:* 4076   `extends` *ClassOrInterfaceTypeList* 4077 4078  *ClassOrInterfaceTypeList:* 4079   *ClassOrInterfaceType* 4080   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* 4081 4082  *ClassOrInterfaceType:* 4083   *TypeReference* 4084 4085An *InterfaceDeclaration* introduces a named type (section [3.7](#3.7)) in the containing declaration space. The *BindingIdentifier* of an interface declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). 4086 4087An interface may optionally have type parameters (section [3.6.1](#3.6.1)) that serve as placeholders for actual types to be provided when the interface is referenced in type references. An interface with type parameters is called a ***generic interface***. The type parameters of a generic interface declaration are in scope in the entire declaration and may be referenced in the *InterfaceExtendsClause* and *ObjectType* body. 4088 4089An 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. 4090 4091An 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: 4092 4093* A property declaration hides a public base type property with the same name. 4094* A string index signature declaration hides a base type string index signature. 4095* A numeric index signature declaration hides a base type numeric index signature. 4096 4097The following constraints must be satisfied by an interface declaration or otherwise a compile-time error occurs: 4098 4099* An interface declaration may not, directly or indirectly, specify a base type that originates in the same declaration. In other words an interface cannot, directly or indirectly, be a base type of itself, regardless of type arguments. 4100* An interface cannot declare a property with the same name as an inherited private or protected property. 4101* Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)). 4102* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.9.4](#3.9.4). 4103* The this-type (section [3.6.3](#3.6.3)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references. 4104 4105An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member. 4106 4107Below is an example of two interfaces that contain properties with the same name but different types: 4108 4109```TypeScript 4110interface Mover { 4111 move(): void; 4112 getStatus(): { speed: number; }; 4113} 4114 4115interface Shaker { 4116 shake(): void; 4117 getStatus(): { frequency: number; }; 4118} 4119``` 4120 4121An 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': 4122 4123```TypeScript 4124interface MoverShaker extends Mover, Shaker { 4125 getStatus(): { speed: number; frequency: number; }; 4126} 4127``` 4128 4129Since function and constructor types are just object types containing call and construct signatures, interfaces can be used to declare named function and constructor types. For example: 4130 4131```TypeScript 4132interface StringComparer { (a: string, b: string): number; } 4133``` 4134 4135This declares type 'StringComparer' to be a function type taking two strings and returning a number. 4136 4137## <a name="7.2"/>7.2 Declaration Merging 4138 4139Interfaces 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. 4140 4141When 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. 4142 4143In an interface with multiple declarations, the `extends` clauses are merged into a single set of base types and the bodies of the interface declarations are merged into a single object type. Declaration merging produces a declaration order that corresponds to *prepending* the members of each interface declaration, in the order the members are written, to the combined list of members in the order of the interface declarations. Thus, members declared in the last interface declaration will appear first in the declaration order of the merged type. 4144 4145For example, a sequence of declarations in this order: 4146 4147```TypeScript 4148interface Document { 4149 createElement(tagName: any): Element; 4150} 4151 4152interface Document { 4153 createElement(tagName: string): HTMLElement; 4154} 4155 4156interface Document { 4157 createElement(tagName: "div"): HTMLDivElement; 4158 createElement(tagName: "span"): HTMLSpanElement; 4159 createElement(tagName: "canvas"): HTMLCanvasElement; 4160} 4161``` 4162 4163is equivalent to the following single declaration: 4164 4165```TypeScript 4166interface Document { 4167 createElement(tagName: "div"): HTMLDivElement; 4168 createElement(tagName: "span"): HTMLSpanElement; 4169 createElement(tagName: "canvas"): HTMLCanvasElement; 4170 createElement(tagName: string): HTMLElement; 4171 createElement(tagName: any): Element; 4172} 4173``` 4174 4175Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved. 4176 4177*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*. 4178 4179## <a name="7.3"/>7.3 Interfaces Extending Classes 4180 4181When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example: 4182 4183```TypeScript 4184class Control { 4185 private state: any; 4186} 4187 4188interface SelectableControl extends Control { 4189 select(): void; 4190} 4191 4192class Button extends Control { 4193 select() { } 4194} 4195 4196class TextBox extends Control { 4197 select() { } 4198} 4199 4200class Image extends Control { 4201} 4202 4203class Location { 4204 select() { } 4205} 4206``` 4207 4208In 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.11](#3.11)). 4209 4210Within 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. 4211 4212## <a name="7.4"/>7.4 Dynamic Type Checks 4213 4214TypeScript 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: 4215 4216```TypeScript 4217var obj: any = getSomeObject(); 4218if (obj && obj.move && obj.shake && obj.getStatus) { 4219 var moverShaker = <MoverShaker> obj; 4220 ... 4221} 4222``` 4223 4224If such a check is used often it can be abstracted into a function: 4225 4226```TypeScript 4227function asMoverShaker(obj: any): MoverShaker { 4228 return obj && obj.move && obj.shake && obj.getStatus ? obj : null; 4229} 4230``` 4231 4232<br/> 4233 4234# <a name="8"/>8 Classes 4235 4236TypeScript extends JavaScript classes to include type parameters, implements clauses, accessibility modifiers, member variable declarations, and parameter property declarations in constructors. 4237 4238*TODO: Document [abstract classes](https://github.com/Microsoft/TypeScript/issues/3578)*. 4239 4240## <a name="8.1"/>8.1 Class Declarations 4241 4242A class declaration declares a ***class type*** and a ***constructor function***. 4243 4244  *ClassDeclaration:* *( Modified )* 4245   `class` *BindingIdentifier<sub>opt</sub>* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *ClassBody* `}` 4246 4247A *ClassDeclaration* introduces a named type (the class type) and a named value (the constructor function) in the containing declaration space. The class type is formed from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is given an anonymous type formed from the constructor declaration, the static member declarations in the class body, and the static members inherited from the base class. The constructor function initializes and returns an instance of the class type. 4248 4249The *BindingIdentifier* of a class declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). The *BindingIdentifier* is optional only when the class declaration occurs in an export default declaration (section [11.3.4.2](#11.3.4.2)). 4250 4251A class may optionally have type parameters (section [3.6.1](#3.6.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*. 4252 4253The following example introduces both a named type called 'Point' (the class type) and a named value called 'Point' (the constructor function) in the containing declaration space. 4254 4255```TypeScript 4256class Point { 4257 constructor(public x: number, public y: number) { } 4258 public length() { return Math.sqrt(this.x * this.x + this.y * this.y); } 4259 static origin = new Point(0, 0); 4260} 4261``` 4262 4263The named type 'Point' is exactly equivalent to 4264 4265```TypeScript 4266interface Point { 4267 x: number; 4268 y: number; 4269 length(): number; 4270} 4271``` 4272 4273The named value 'Point' is a constructor function whose type corresponds to the declaration 4274 4275```TypeScript 4276var Point: { 4277 new(x: number, y: number): Point; 4278 origin: Point; 4279}; 4280``` 4281 4282The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement 4283 4284```TypeScript 4285var p: Point = new Point(10, 20); 4286``` 4287 4288the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. 4289 4290### <a name="8.1.1"/>8.1.1 Class Heritage Specification 4291 4292*TODO: Update this section to reflect [expressions in class extends clauses](https://github.com/Microsoft/TypeScript/pull/3516)*. 4293 4294The heritage specification of a class consists of optional `extends` and `implements` clauses. The `extends` clause specifies the base class of the class and the `implements` clause specifies a set of interfaces for which to validate the class provides an implementation. 4295 4296  *ClassHeritage:* *( Modified )* 4297   *ClassExtendsClause<sub>opt</sub>* *ImplementsClause<sub>opt</sub>* 4298 4299  *ClassExtendsClause:* 4300   `extends`  *ClassType* 4301 4302  *ClassType:* 4303   *TypeReference* 4304 4305  *ImplementsClause:* 4306   `implements` *ClassOrInterfaceTypeList* 4307 4308A 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. 4309 4310The following constraints must be satisfied by the class heritage specification or otherwise a compile-time error occurs: 4311 4312* If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression. 4313* A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments. 4314* The this-type (section [3.6.3](#3.6.3)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause. 4315* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures. 4316 4317The following example illustrates a situation in which the first rule above would be violated: 4318 4319```TypeScript 4320class A { a: number; } 4321 4322namespace Foo { 4323 var A = 1; 4324 class B extends A { b: string; } 4325} 4326``` 4327 4328When 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'). 4329 4330The 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. 4331 4332Note 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. 4333 4334### <a name="8.1.2"/>8.1.2 Class Body 4335 4336The 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. 4337 4338  *ClassElement:* *( Modified )* 4339   *ConstructorDeclaration* 4340   *PropertyMemberDeclaration* 4341   *IndexMemberDeclaration* 4342 4343The body of class may optionally contain a single constructor declaration. Constructor declarations are described in section [8.3](#8.3). 4344 4345Member declarations are used to declare instance and static members of the class. Property member declarations are described in section [8.4](#8.4) and index member declarations are described in section [8.5](#8.5). 4346 4347## <a name="8.2"/>8.2 Members 4348 4349The members of a class consist of the members introduced through member declarations in the class body and the members inherited from the base class. 4350 4351### <a name="8.2.1"/>8.2.1 Instance and Static Members 4352 4353Members are either ***instance members*** or ***static members***. 4354 4355Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of the class. 4356 4357Static members are declared using the `static` modifier and are members of the constructor function type (section [8.2.5](#8.2.5)). Within static member functions and static member accessors, the type of `this` is the constructor function type. 4358 4359Class type parameters cannot be referenced in static member declarations. 4360 4361### <a name="8.2.2"/>8.2.2 Accessibility 4362 4363Property members have either ***public***, ***private***, or ***protected*** accessibility. The default is public accessibility, but property member declarations may include a `public`, `private`, or `protected` modifier to explicitly specify the desired accessibility. 4364 4365Public property members can be accessed everywhere without restrictions. 4366 4367Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*. 4368 4369Protected 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 or a subclass thereof. 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. 4370 4371Private 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. 4372 4373The following example demonstrates private and protected accessibility: 4374 4375```TypeScript 4376class A { 4377 private x: number; 4378 protected y: number; 4379 static f(a: A, b: B) { 4380 a.x = 1; // Ok 4381 b.x = 1; // Ok 4382 a.y = 1; // Ok 4383 b.y = 1; // Ok 4384 } 4385} 4386 4387class B extends A { 4388 static f(a: A, b: B) { 4389 a.x = 1; // Error, x only accessible within A 4390 b.x = 1; // Error, x only accessible within A 4391 a.y = 1; // Error, y must be accessed through instance of B 4392 b.y = 1; // Ok 4393 } 4394} 4395``` 4396 4397In 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'. 4398 4399### <a name="8.2.3"/>8.2.3 Inheritance and Overriding 4400 4401A 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. 4402 4403A 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.11.4](#3.11.4)) to the type of the overridden property member, or otherwise a compile-time error occurs. 4404 4405Base class instance member functions can be overridden by derived class instance member functions, but not by other kinds of members. 4406 4407Base class instance member variables and accessors can be overridden by derived class instance member variables and accessors, but not by other kinds of members. 4408 4409Base class static property members can be overridden by derived class static property members of any kind as long as the types are compatible, as described above. 4410 4411An index member in a derived class is said to override an index member in a base class when the derived class index member is of the same index kind (string or numeric) as the base class index member. The type of an overriding index member must be assignable (section [3.11.4](#3.11.4)) to the type of the overridden index member, or otherwise a compile-time error occurs. 4412 4413### <a name="8.2.4"/>8.2.4 Class Types 4414 4415A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of that class type. The class type has the following members: 4416 4417* A property for each instance member variable declaration in the class body. 4418* A property of a function type for each instance member function declaration in the class body. 4419* A property for each uniquely named instance member accessor declaration in the class body. 4420* A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier. 4421* An index signature for each instance index member declaration in the class body. 4422* All base class instance property or index members that are not overridden in the class. 4423 4424All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). 4425 4426In the example 4427 4428```TypeScript 4429class A { 4430 public x: number; 4431 public f() { } 4432 public g(a: any) { return undefined; } 4433 static s: string; 4434} 4435 4436class B extends A { 4437 public y: number; 4438 public g(b: boolean) { return false; } 4439} 4440``` 4441 4442the class type of 'A' is equivalent to 4443 4444```TypeScript 4445interface A { 4446 x: number; 4447 f: () => void; 4448 g: (a: any) => any; 4449} 4450``` 4451 4452and the class type of 'B' is equivalent to 4453 4454```TypeScript 4455interface B { 4456 x: number; 4457 y: number; 4458 f: () => void; 4459 g: (b: boolean) => boolean; 4460} 4461``` 4462 4463Note that static declarations in a class do not contribute to the class 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'. 4464 4465### <a name="8.2.5"/>8.2.5 Constructor Function Types 4466 4467The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members: 4468 4469* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. 4470* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. 4471* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. 4472* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. 4473* A property for each static member variable declaration in the class body. 4474* A property of a function type for each static member function declaration in the class body. 4475* A property for each uniquely named static member accessor declaration in the class body. 4476* 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. 4477* All base class constructor function type properties that are not overridden in the class. 4478 4479Every 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. 4480 4481The example 4482 4483```TypeScript 4484class Pair<T1, T2> { 4485 constructor(public item1: T1, public item2: T2) { } 4486} 4487 4488class TwoArrays<T> extends Pair<T[], T[]> { } 4489``` 4490 4491introduces two named types corresponding to 4492 4493```TypeScript 4494interface Pair<T1, T2> { 4495 item1: T1; 4496 item2: T2; 4497} 4498 4499interface TwoArrays<T> { 4500 item1: T[]; 4501 item2: T[]; 4502} 4503``` 4504 4505and two constructor functions corresponding to 4506 4507```TypeScript 4508var Pair: { 4509 new <T1, T2>(item1: T1, item2: T2): Pair<T1, T2>; 4510} 4511 4512var TwoArrays: { 4513 new <T>(item1: T[], item2: T[]): TwoArrays<T>; 4514} 4515``` 4516 4517Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. 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. 4518 4519## <a name="8.3"/>8.3 Constructor Declarations 4520 4521A constructor declaration declares the constructor function of a class. 4522 4523  *ConstructorDeclaration:* 4524   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `{` *FunctionBody* `}` 4525   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;` 4526 4527Constructor declarations that specify a body are called ***constructor implementations*** and constructor declarations without a body are called ***constructor overloads***. It is possible to specify multiple constructor overloads in a class, but a class can have at most one constructor implementation. All constructor declarations in a class must specify the same set of modifiers. Only public constructors are supported and private or protected constructors result in an error. 4528 4529In a class with no constructor declaration, an automatic constructor is provided, as described in section [8.3.3](#8.3.3). 4530 4531When a class has constructor overloads, the overloads determine the construct signatures of the type given to the constructor function object, and the constructor implementation signature (if any) must be assignable to that type. Otherwise, the constructor implementation itself determines the construct signature. This exactly parallels the way overloads are processed in a function declaration (section [6.2](#6.2)). 4532 4533When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. 4534 4535The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [3.6.3](#3.6.3)) of the class. 4536 4537The type parameters of a generic class are in scope and accessible in a constructor declaration. 4538 4539### <a name="8.3.1"/>8.3.1 Constructor Parameters 4540 4541Similar to functions, only the constructor implementation (and not constructor overloads) can specify default value expressions for optional parameters. It is a compile-time error for such default value expressions to reference `this`. When the output target is ECMAScript 3 or 5, for each parameter with a default value, a statement that substitutes the default value for an omitted argument is included in the JavaScript generated for the constructor function. 4542 4543A parameter of a *ConstructorImplementation* may be prefixed with a `public`, `private`, or `protected` modifier. This is called a ***parameter property declaration*** and is shorthand for declaring a property with the same name as the parameter and initializing it with the value of the parameter. For example, the declaration 4544 4545```TypeScript 4546class Point { 4547 constructor(public x: number, public y: number) { 4548 // Constructor body 4549 } 4550} 4551``` 4552 4553is equivalent to writing 4554 4555```TypeScript 4556class Point { 4557 public x: number; 4558 public y: number; 4559 constructor(x: number, y: number) { 4560 this.x = x; 4561 this.y = y; 4562 // Constructor body 4563 } 4564} 4565``` 4566 4567A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [3.3.6](#3.3.6)). 4568 4569### <a name="8.3.2"/>8.3.2 Super Calls 4570 4571Super calls (section [4.9.1](#4.9.1)) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example: 4572 4573```TypeScript 4574class ColoredPoint extends Point { 4575 constructor(x: number, y: number, public color: string) { 4576 super(x, y); 4577 } 4578} 4579``` 4580 4581Constructors of classes with no `extends` clause may not contain super calls, whereas constructors of derived classes must contain at least one super call somewhere in their function body. Super calls are not permitted outside constructors or in local functions inside constructors. 4582 4583The first statement in the body of a constructor *must* be a super call if both of the following are true: 4584 4585* The containing class is a derived class. 4586* The constructor declares parameter properties or the containing class declares instance member variables with initializers. 4587 4588In such a required super call, it is a compile-time error for argument expressions to reference `this`. 4589 4590Initialization of parameter properties and instance member variables with initializers takes place immediately at the beginning of the constructor body if the class has no base class, or immediately following the super call if the class is a derived class. 4591 4592### <a name="8.3.3"/>8.3.3 Automatic Constructors 4593 4594If a class omits a constructor declaration, an ***automatic constructor*** is provided. 4595 4596In a class with no `extends` clause, the automatic constructor has no parameters and performs no action other than executing the instance member variable initializers (section [8.4.1](#8.4.1)), if any. 4597 4598In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor. The automatically provided constructor first forwards the call to the base class constructor using a call equivalent to 4599 4600```TypeScript 4601BaseClass.apply(this, arguments); 4602``` 4603 4604and then executes the instance member variable initializers, if any. 4605 4606## <a name="8.4"/>8.4 Property Member Declarations 4607 4608Property member declarations can be member variable declarations, member function declarations, or member accessor declarations. 4609 4610  *PropertyMemberDeclaration:* 4611   *MemberVariableDeclaration* 4612   *MemberFunctionDeclaration* 4613   *MemberAccessorDeclaration* 4614 4615Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name. 4616 4617Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [8.2.5](#8.2.5)), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name. 4618 4619Note that the declaration spaces of instance and static property members are separate. Thus, it is possible to have instance and static property members with the same name. 4620 4621Except 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. 4622 4623Every 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'. 4624 4625Below is an example of a class containing both instance and static property member declarations: 4626 4627```TypeScript 4628class Point { 4629 constructor(public x: number, public y: number) { } 4630 public distance(p: Point) { 4631 var dx = this.x - p.x; 4632 var dy = this.y - p.y; 4633 return Math.sqrt(dx * dx + dy * dy); 4634 } 4635 static origin = new Point(0, 0); 4636 static distance(p1: Point, p2: Point) { return p1.distance(p2); } 4637} 4638``` 4639 4640The class type 'Point' has the members: 4641 4642```TypeScript 4643interface Point { 4644 x: number; 4645 y: number; 4646 distance(p: Point); 4647} 4648``` 4649 4650and the constructor function 'Point' has a type corresponding to the declaration: 4651 4652```TypeScript 4653var Point: { 4654 new(x: number, y: number): Point; 4655 origin: Point; 4656 distance(p1: Point, p2: Point): number; 4657} 4658``` 4659 4660### <a name="8.4.1"/>8.4.1 Member Variable Declarations 4661 4662A member variable declaration declares an instance member variable or a static member variable. 4663 4664  *MemberVariableDeclaration:* 4665   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* `;` 4666 4667The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)). 4668 4669An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. 4670 4671A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded. 4672 4673Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. This effectively means that entities from outer scopes by the same name as a constructor parameter or local variable are inaccessible in initializer expressions for instance member variables. 4674 4675Since instance member variable initializers are equivalent to assignments to properties of `this` in the constructor, the example 4676 4677```TypeScript 4678class Employee { 4679 public name: string; 4680 public address: string; 4681 public retired = false; 4682 public manager: Employee = null; 4683 public reports: Employee[] = []; 4684} 4685``` 4686 4687is equivalent to 4688 4689```TypeScript 4690class Employee { 4691 public name: string; 4692 public address: string; 4693 public retired: boolean; 4694 public manager: Employee; 4695 public reports: Employee[]; 4696 constructor() { 4697 this.retired = false; 4698 this.manager = null; 4699 this.reports = []; 4700 } 4701} 4702``` 4703 4704### <a name="8.4.2"/>8.4.2 Member Function Declarations 4705 4706A member function declaration declares an instance member function or a static member function. 4707 4708  *MemberFunctionDeclaration:* 4709   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `{` *FunctionBody* `}` 4710   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;` 4711 4712A member function declaration is processed in the same manner as an ordinary function declaration (section [6](#6)), except that in a member function `this` has a known type. 4713 4714All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static). 4715 4716An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. 4717 4718A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type. 4719 4720A member function can access overridden base class members using a super property access (section [4.9.2](#4.9.2)). For example 4721 4722```TypeScript 4723class Point { 4724 constructor(public x: number, public y: number) { } 4725 public toString() { 4726 return "x=" + this.x + " y=" + this.y; 4727 } 4728} 4729 4730class ColoredPoint extends Point { 4731 constructor(x: number, y: number, public color: string) { 4732 super(x, y); 4733 } 4734 public toString() { 4735 return super.toString() + " color=" + this.color; 4736 } 4737} 4738``` 4739 4740In 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: 4741 4742```TypeScript 4743class A { 4744 a = 1; 4745 static create() { 4746 return new this(); 4747 } 4748} 4749 4750class B extends A { 4751 b = 2; 4752} 4753 4754var x = A.create(); // new A() 4755var y = B.create(); // new B() 4756``` 4757 4758Note 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 4759 4760```TypeScript 4761class B extends A { 4762 constructor(public b: number) { 4763 super(); 4764 } 4765} 4766``` 4767 4768does 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'). 4769 4770### <a name="8.4.3"/>8.4.3 Member Accessor Declarations 4771 4772A member accessor declaration declares an instance member accessor or a static member accessor. 4773 4774  *MemberAccessorDeclaration:* 4775   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *GetAccessor* 4776   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *SetAccessor* 4777 4778Get and set accessors are processed in the same manner as in an object literal (section [4.5](#4.5)), except that a contextual type is never available in a member accessor declaration. 4779 4780Accessors for the same member name must specify the same accessibility. 4781 4782An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. 4783 4784A 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. 4785 4786Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.7.1](#8.7.1). 4787 4788### <a name="8.4.4"/>8.4.4 Dynamic Property Declarations 4789 4790If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations: 4791 4792* A dynamic property declaration does not introduce a property in the class type or constructor function type. 4793* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. 4794* The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. 4795 4796## <a name="8.5"/>8.5 Index Member Declarations 4797 4798An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class type. 4799 4800  *IndexMemberDeclaration:* 4801   *IndexSignature* `;` 4802 4803Index member declarations have no body and cannot specify an accessibility modifier. 4804 4805A class declaration can have at most one string index member declaration and one numeric index member declaration. All instance property members of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). 4806 4807It is not possible to declare index members for the static side of a class. 4808 4809Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner. 4810 4811## <a name="8.6"/>8.6 Decorators 4812 4813*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*. 4814 4815## <a name="8.7"/>8.7 Code Generation 4816 4817When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section. 4818 4819### <a name="8.7.1"/>8.7.1 Classes Without Extends Clauses 4820 4821A class with no `extends` clause generates JavaScript equivalent to the following: 4822 4823```TypeScript 4824var <ClassName> = (function () { 4825 function <ClassName>(<ConstructorParameters>) { 4826 <DefaultValueAssignments> 4827 <ParameterPropertyAssignments> 4828 <MemberVariableAssignments> 4829 <ConstructorStatements> 4830 } 4831 <MemberFunctionStatements> 4832 <StaticVariableAssignments> 4833 return <ClassName>; 4834})(); 4835``` 4836 4837*ClassName* is the name of the class. 4838 4839*ConstructorParameters* is a comma separated list of the constructor's parameter names. 4840 4841*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.6](#6.6). 4842 4843*ParameterPropertyAssignments* is a sequence of assignments, one for each parameter property declaration in the constructor, in order they are declared, of the form 4844 4845```TypeScript 4846this.<ParameterName> = <ParameterName>; 4847``` 4848 4849where *ParameterName* is the name of a parameter property. 4850 4851*MemberVariableAssignments* is a sequence of assignments, one for each instance member variable declaration with an initializer, in the order they are declared, of the form 4852 4853```TypeScript 4854this.<MemberName> = <InitializerExpression>; 4855``` 4856 4857where *MemberName* is the name of the member variable and *InitializerExpression* is the code generated for the initializer expression. 4858 4859*ConstructorStatements* is the code generated for the statements specified in the constructor body. 4860 4861*MemberFunctionStatements* is a sequence of statements, one for each member function declaration or member accessor declaration, in the order they are declared. 4862 4863An instance member function declaration generates a statement of the form 4864 4865```TypeScript 4866<ClassName>.prototype.<MemberName> = function (<FunctionParameters>) { 4867 <DefaultValueAssignments> 4868 <FunctionStatements> 4869} 4870``` 4871 4872and static member function declaration generates a statement of the form 4873 4874```TypeScript 4875<ClassName>.<MemberName> = function (<FunctionParameters>) { 4876 <DefaultValueAssignments> 4877 <FunctionStatements> 4878} 4879``` 4880 4881where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [6.6](#6.6). 4882 4883A get or set instance member accessor declaration, or a pair of get and set instance member accessor declarations with the same name, generates a statement of the form 4884 4885```TypeScript 4886Object.defineProperty(<ClassName>.prototype, "<MemberName>", { 4887 get: function () { 4888 <GetAccessorStatements> 4889 }, 4890 set: function (<ParameterName>) { 4891 <SetAccessorStatements> 4892 }, 4893 enumerable: true, 4894 configurable: true 4895}; 4896``` 4897 4898and a get or set static member accessor declaration, or a pair of get and set static member accessor declarations with the same name, generates a statement of the form 4899 4900```TypeScript 4901Object.defineProperty(<ClassName>, "<MemberName>", { 4902 get: function () { 4903 <GetAccessorStatements> 4904 }, 4905 set: function (<ParameterName>) { 4906 <SetAccessorStatements> 4907 }, 4908 enumerable: true, 4909 configurable: true 4910}; 4911``` 4912 4913where *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. 4914 4915*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 4916 4917```TypeScript 4918<ClassName>.<MemberName> = <InitializerExpression>; 4919``` 4920 4921where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression. 4922 4923### <a name="8.7.2"/>8.7.2 Classes With Extends Clauses 4924 4925A class with an `extends` clause generates JavaScript equivalent to the following: 4926 4927```TypeScript 4928var <ClassName> = (function (_super) { 4929 __extends(<ClassName>, _super); 4930 function <ClassName>(<ConstructorParameters>) { 4931 <DefaultValueAssignments> 4932 <SuperCallStatement> 4933 <ParameterPropertyAssignments> 4934 <MemberVariableAssignments> 4935 <ConstructorStatements> 4936 } 4937 <MemberFunctionStatements> 4938 <StaticVariableAssignments> 4939 return <ClassName>; 4940})(<BaseClassName>); 4941``` 4942 4943In 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. 4944 4945```TypeScript 4946var __extends = this.__extends || function(d, b) { 4947 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; 4948 function f() { this.constructor = d; } 4949 f.prototype = b.prototype; 4950 d.prototype = new f(); 4951} 4952``` 4953 4954*BaseClassName* is the class name specified in the `extends` clause. 4955 4956If the class has no explicitly declared constructor, the *SuperCallStatement* takes the form 4957 4958```TypeScript 4959_super.apply(this, arguments); 4960``` 4961 4962Otherwise the *SuperCallStatement* is present if the constructor function is required to start with a super call, as discussed in section [8.3.2](#8.3.2), and takes the form 4963 4964```TypeScript 4965_super.call(this, <SuperCallArguments>) 4966``` 4967 4968where *SuperCallArguments* is the argument list specified in the super call. Note that this call precedes the code generated for parameter properties and member variables with initializers. Super calls elsewhere in the constructor generate similar code, but the code generated for such calls will be part of the *ConstructorStatements* section. 4969 4970A super property access in the constructor, an instance member function, or an instance member accessor generates JavaScript equivalent to 4971 4972```TypeScript 4973_super.prototype.<PropertyName> 4974``` 4975 4976where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to 4977 4978```TypeScript 4979_super.prototype.<PropertyName>.call(this, <Arguments>) 4980``` 4981 4982where Arguments is the code generated for the argument list specified in the function call. 4983 4984A super property access in a static member function or a static member accessor generates JavaScript equivalent to 4985 4986```TypeScript 4987_super.<PropertyName> 4988``` 4989 4990where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to 4991 4992```TypeScript 4993_super.<PropertyName>.call(this, <Arguments>) 4994``` 4995 4996where Arguments is the code generated for the argument list specified in the function call. 4997 4998<br/> 4999 5000# <a name="9"/>9 Enums 5001 5002An enum type is a distinct subtype of the Number primitive type with an associated set of named constants that define the possible values of the enum type. 5003 5004## <a name="9.1"/>9.1 Enum Declarations 5005 5006An enum declaration declares an ***enum type*** and an ***enum object***. 5007 5008  *EnumDeclaration:* 5009   `const`*<sub>opt</sub>* `enum` *BindingIdentifier* `{` *EnumBody<sub>opt</sub>* `}` 5010 5011An *EnumDeclaration* introduces a named type (the enum type) and a named value (the enum object) in the containing declaration space. The enum type is a distinct subtype of the Number primitive type. The enum object is a value 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'. 5012 5013The *BindingIdentifier* of an enum declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)). 5014 5015When an enum declaration includes a `const` modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section [9.4](#9.4). 5016 5017The example 5018 5019```TypeScript 5020enum Color { Red, Green, Blue } 5021``` 5022 5023declares a subtype of the Number primitive type called 'Color' and introduces a variable 'Color' with a type that corresponds to the declaration 5024 5025```TypeScript 5026var Color: { 5027 [x: number]: string; 5028 Red: Color; 5029 Green: Color; 5030 Blue: Color; 5031}; 5032``` 5033 5034The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.5](#9.5). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example 5035 5036```TypeScript 5037var c = Color.Red; 5038console.log(Color[c]); // Outputs "Red" 5039``` 5040 5041## <a name="9.2"/>9.2 Enum Members 5042 5043The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration. 5044 5045  *EnumBody:* 5046   *EnumMemberList* `,`*<sub>opt</sub>* 5047 5048  *EnumMemberList:* 5049   *EnumMember* 5050   *EnumMemberList* `,` *EnumMember* 5051 5052  *EnumMember:* 5053   *PropertyName* 5054   *PropertyName* = *EnumValue* 5055 5056  *EnumValue:* 5057   *AssignmentExpression* 5058 5059The *PropertyName* of an enum member cannot be a computed property name ([2.2.3](#2.2.3)). 5060 5061Enum members are either ***constant members*** or ***computed members***. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members. 5062 5063An enum member is classified as follows: 5064 5065* If the member declaration specifies no value, the member is considered a constant enum member. If the member is the first member in the enum declaration, it is assigned the value zero. Otherwise, it is assigned the value of the immediately preceding member plus one, and an error occurs if the immediately preceding member is not a constant enum member. 5066* If the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member. 5067* Otherwise, the member is considered a computed enum member. 5068 5069Enum value expressions must be of type Any, the Number primitive type, or the enum type itself. 5070 5071A ***constant enum expression*** is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following: 5072 5073* A numeric literal. 5074* An identifier or property access that denotes a previously declared member in the same constant enum declaration. 5075* A parenthesized constant enum expression. 5076* A +, –, or ~ unary operator applied to a constant enum expression. 5077* A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions. 5078 5079In the example 5080 5081```TypeScript 5082enum Test { 5083 A, 5084 B, 5085 C = Math.floor(Math.random() * 1000), 5086 D = 10, 5087 E 5088} 5089``` 5090 5091'A', 'B', 'D', and 'E' are constant members with values 0, 1, 10, and 11 respectively, and 'C' is a computed member. 5092 5093In the example 5094 5095```TypeScript 5096enum Style { 5097 None = 0, 5098 Bold = 1, 5099 Italic = 2, 5100 Underline = 4, 5101 Emphasis = Bold | Italic, 5102 Hyperlink = Bold | Underline 5103} 5104``` 5105 5106all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values. 5107 5108## <a name="9.3"/>9.3 Declaration Merging 5109 5110Enums 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. 5111 5112It 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. 5113 5114When enum declarations are merged, they must either all specify a `const` modifier or all specify no `const` modifier. 5115 5116## <a name="9.4"/>9.4 Constant Enum Declarations 5117 5118An enum declaration that specifies a `const` modifier is a ***constant enum declaration***. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn't classified as a constant enum expression. 5119 5120Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum's members. For example: 5121 5122```TypeScript 5123const enum Comparison { 5124 LessThan = -1, 5125 EqualTo = 0, 5126 GreaterThan = 1 5127} 5128 5129var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code 5130var y = Comparison[Comparison.EqualTo]; // Error 5131var z = Comparison; // Error 5132``` 5133 5134The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value. 5135 5136## <a name="9.5"/>9.5 Code Generation 5137 5138An enum declaration generates JavaScript equivalent to the following: 5139 5140```TypeScript 5141var <EnumName>; 5142(function (<EnumName>) { 5143 <EnumMemberAssignments> 5144})(<EnumName>||(<EnumName>={})); 5145``` 5146 5147*EnumName* is the name of the enum. 5148 5149*EnumMemberAssignments* is a sequence of assignments, one for each enum member, in order they are declared, of the form 5150 5151```TypeScript 5152<EnumName>[<EnumName>["<MemberName>"] = <Value>] = "<MemberName>"; 5153``` 5154 5155where *MemberName* is the name of the enum member and *Value* is the assigned constant value or the code generated for the computed value expression. 5156 5157For example, the 'Color' enum example from section [9.1](#9.1) generates the following JavaScript: 5158 5159```TypeScript 5160var Color; 5161(function (Color) { 5162 Color[Color["Red"] = 0] = "Red"; 5163 Color[Color["Green"] = 1] = "Green"; 5164 Color[Color["Blue"] = 2] = "Blue"; 5165})(Color||(Color={})); 5166``` 5167 5168<br/> 5169 5170# <a name="10"/>10 Namespaces 5171 5172Namespaces provide a mechanism for organizing code and declarations in hierarchies of named containers. Namespaces have named members that each denote a value, a type, or a namespace, or some combination thereof, and those members may be local or exported. The body of a namespace corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. Namespaces can be thought of as a formalization of the [immediately-invoked function expression](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (IIFE) pattern. 5173 5174## <a name="10.1"/>10.1 Namespace Declarations 5175 5176A namespace declaration introduces a name with a namespace meaning and, in the case of an instantiated namespace, a value meaning in the containing declaration space. 5177 5178  *NamespaceDeclaration:* 5179   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` 5180 5181  *IdentifierPath:* 5182   *BindingIdentifier* 5183   *IdentifierPath* `.` *BindingIdentifier* 5184 5185Namespaces are declared using the `namespace` keyword, but for backward compatibility of earlier versions of TypeScript a `module` keyword can also be used. 5186 5187Namespaces are either ***instantiated*** or ***non-instantiated***. A non-instantiated namespace is a namespace containing only interface types, type aliases, and other non-instantiated namespace. An instantiated namespace is a namespace that doesn't meet this definition. In intuitive terms, an instantiated namespace is one for which a namespace instance is created, whereas a non-instantiated namespace is one for which no code is generated. 5188 5189When a namespace identifier is referenced as a *NamespaceName* (section [3.8.2](#3.8.2)) it denotes a container of namespace and type names, and when a namespace identifier is referenced as a *PrimaryExpression* (section [4.3](#4.3)) it denotes the singleton namespace instance. For example: 5190 5191```TypeScript 5192namespace M { 5193 export interface P { x: number; y: number; } 5194 export var a = 1; 5195} 5196 5197var p: M.P; // M used as NamespaceName 5198var m = M; // M used as PrimaryExpression 5199var x1 = M.a; // M used as PrimaryExpression 5200var x2 = m.a; // Same as M.a 5201var q: m.P; // Error 5202``` 5203 5204Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *NamespaceName* 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. 5205 5206If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated namespace and it would be an error to reference 'M' as a *PrimaryExpression*. 5207 5208A namespace declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier namespace declarations where all but the outermost are automatically exported. For example: 5209 5210```TypeScript 5211namespace A.B.C { 5212 export var x = 1; 5213} 5214``` 5215 5216corresponds to 5217 5218```TypeScript 5219namespace A { 5220 export namespace B { 5221 export namespace C { 5222 export var x = 1; 5223 } 5224 } 5225} 5226``` 5227 5228The hierarchy formed by namespace and named type names partially mirrors that formed by namespace instances and members. The example 5229 5230```TypeScript 5231namespace A { 5232 export namespace B { 5233 export class C { } 5234 } 5235} 5236``` 5237 5238introduces 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 5239 5240```TypeScript 5241var c: A.B.C = new A.B.C(); 5242``` 5243 5244the 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. 5245 5246## <a name="10.2"/>10.2 Namespace Body 5247 5248The body of a namespace corresponds to a function that is executed once to initialize the namespace instance. 5249 5250  *NamespaceBody:* 5251   *NamespaceElements<sub>opt</sub>* 5252 5253  *NamespaceElements:* 5254   *NamespaceElement* 5255   *NamespaceElements* *NamespaceElement* 5256 5257  *NamespaceElement:* 5258   *Statement* 5259   *LexicalDeclaration* 5260   *FunctionDeclaration* 5261   *GeneratorDeclaration* 5262   *ClassDeclaration* 5263   *InterfaceDeclaration* 5264   *TypeAliasDeclaration* 5265   *EnumDeclaration* 5266   *NamespaceDeclaration 5267   AmbientDeclaration 5268   ImportAliasDeclaration 5269   ExportNamespaceElement* 5270 5271  *ExportNamespaceElement:* 5272   `export` *VariableStatement* 5273   `export` *LexicalDeclaration* 5274   `export` *FunctionDeclaration* 5275   `export` *GeneratorDeclaration* 5276   `export` *ClassDeclaration* 5277   `export` *InterfaceDeclaration* 5278   `export` *TypeAliasDeclaration* 5279   `export` *EnumDeclaration* 5280   `export` *NamespaceDeclaration* 5281   `export` *AmbientDeclaration* 5282   `export` *ImportAliasDeclaration* 5283 5284## <a name="10.3"/>10.3 Import Alias Declarations 5285 5286Import alias declarations are used to create local aliases for entities in other namespaces. 5287 5288  *ImportAliasDeclaration:* 5289   `import` *BindingIdentifier* `=` *EntityName* `;` 5290 5291  *EntityName:* 5292   *NamespaceName* 5293   *NamespaceName* `.` *IdentifierReference* 5294 5295An *EntityName* consisting of a single identifier is resolved as a *NamespaceName* and is thus required to reference a namespace. The resulting local alias references the given namespace and is itself classified as a namespace. 5296 5297An *EntityName* consisting of more than one identifier is resolved as a *NamespaceName* followed by an identifier that names an exported entity in the given namespace. The resulting local alias has all the meanings of the referenced entity. (As many as three distinct meanings are possible for an entity name—value, type, and namespace.) In effect, it is as if the imported entity was declared locally with the local alias name. 5298 5299In the example 5300 5301```TypeScript 5302namespace A { 5303 export interface X { s: string } 5304 export var X: X; 5305} 5306 5307namespace B { 5308 interface A { n: number } 5309 import Y = A; // Alias for namespace A 5310 import Z = A.X; // Alias for type and value A.X 5311 var v: Z = Z; 5312} 5313``` 5314 5315within 'B', 'Y' is an alias only for namespace '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. 5316 5317If the *NamespaceName* portion of an *EntityName* references an instantiated namespace, the *NamespaceName* is required to reference the namespace instance when evaluated as an expression. In the example 5318 5319```TypeScript 5320namespace A { 5321 export interface X { s: string } 5322} 5323 5324namespace B { 5325 var A = 1; 5326 import Y = A; 5327} 5328``` 5329 5330'Y' is a local alias for the non-instantiated namespace 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated namespace, 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 namespace instance of namespace 'A'. 5331 5332When an import statement includes an export modifier, all meanings of the local alias are exported. 5333 5334## <a name="10.4"/>10.4 Export Declarations 5335 5336An export declaration declares an externally accessible namespace member. An export declaration is simply a regular declaration prefixed with the keyword `export`. 5337 5338The members of a namespace's export declaration space (section [2.3](#2.3)) constitute the namespace's ***export member set***. A namespace's ***instance type*** is an object type with a property for each member in the namespace's export member set that denotes a value. 5339 5340An exported member depends on a (possibly empty) set of named types (section [3.7](#3.7)). Those named types must be at least as accessible as the exported member, or otherwise an error occurs. 5341 5342The named types upon which a member depends are the named types occurring in the transitive closure of the ***directly depends on*** relationship defined as follows: 5343 5344* A variable directly depends on the *Type* specified in its type annotation. 5345* A function directly depends on each *Type* specified in a parameter or return type annotation. 5346* A class directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base class or implemented interface, and each *Type* specified in a constructor parameter type annotation, public member variable type annotation, public member function parameter or return type annotation, public member accessor parameter or return type annotation, or index signature type annotation. 5347* An interface directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base interface, and the *ObjectType* specified as its body. 5348* A namespace directly depends on its exported members. 5349* A *Type* or *ObjectType* directly depends on every *TypeReference* that occurs within the type at any level of nesting. 5350* A *TypeReference* directly depends on the type it references and on each *Type* specified as a type argument. 5351 5352A named type *T* having a root namespace *R* (section [2.3](#2.3)) is said to be ***at least as accessible as*** a member *M* if 5353 5354* *R* is the global namespace or a module, or 5355* *R* is a namespace in the parent namespace chain of *M*. 5356 5357In the example 5358 5359```TypeScript 5360interface A { x: string; } 5361 5362namespace M { 5363 export interface B { x: A; } 5364 export interface C { x: B; } 5365 export function foo(c: C) { … } 5366} 5367``` 5368 5369the '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 I t is declared in a parent namespace of foo's namespace. 5370 5371## <a name="10.5"/>10.5 Declaration Merging 5372 5373Namespaces are "open-ended" and namespace declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single namespace. For example, the following two declarations of a namespace 'outer' might be located in separate source files. 5374 5375File a.ts: 5376 5377```TypeScript 5378namespace outer { 5379 var local = 1; // Non-exported local variable 5380 export var a = local; // outer.a 5381 export namespace inner { 5382 export var x = 10; // outer.inner.x 5383 } 5384} 5385``` 5386 5387File b.ts: 5388 5389```TypeScript 5390namespace outer { 5391 var local = 2; // Non-exported local variable 5392 export var b = local; // outer.b 5393 export namespace inner { 5394 export var y = 20; // outer.inner.y 5395 } 5396} 5397``` 5398 5399Assuming the two source files are part of the same program, the two declarations will have the global namespace as their common root and will therefore contribute to the same namespace instance, the instance type of which will be: 5400 5401```TypeScript 5402{ 5403 a: number; 5404 b: number; 5405 inner: { 5406 x: number; 5407 y: number; 5408 }; 5409} 5410``` 5411 5412Declaration merging does not apply to local aliases created by import alias declarations. In other words, it is not possible have an import alias declaration and a namespace declaration for the same name within the same namespace body. 5413 5414*TODO: Clarify rules for [alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. 5415 5416Declaration merging also extends to namespace declarations with the same qualified name relative to a common root as a function, class, or enum declaration: 5417 5418* When merging a function and a namespace, the type of the function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the function provide the call signatures and the exported members of the namespace provide the properties of the combined type. 5419* When merging a class and a namespace, the type of the constructor function object is merged with the instance type of the namespace. 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 namespace provide the properties of the combined type. It is an error to have static class members and exported namespace members with the same name. 5420* When merging an enum and a namespace, the type of the enum object is merged with the instance type of the namespace. In effect, the members of the enum and the exported members of the namespace provide the properties of the combined type. It is an error to have enum members and exported namespace members with the same name. 5421 5422When merging a non-ambient function or class declaration and a non-ambient namespace declaration, the function or class declaration must be located prior to the namespace 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.) 5423 5424The example 5425 5426```TypeScript 5427interface Point { 5428 x: number; 5429 y: number; 5430} 5431 5432function point(x: number, y: number): Point { 5433 return { x: x, y: y }; 5434} 5435 5436namespace point { 5437 export var origin = point(0, 0); 5438 export function equals(p1: Point, p2: Point) { 5439 return p1.x == p2.x && p1.y == p2.y; 5440 } 5441} 5442 5443var p1 = point(0, 0); 5444var p2 = point.origin; 5445var b = point.equals(p1, p2); 5446``` 5447 5448declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the namespace declaration for 'point' is located after the function declaration. 5449 5450## <a name="10.6"/>10.6 Code Generation 5451 5452A namespace generates JavaScript code that is equivalent to the following: 5453 5454```TypeScript 5455var <NamespaceName>; 5456(function(<NamespaceName>) { 5457 <NamespaceStatements> 5458})(<NamespaceName>||(<NamespaceName>={})); 5459``` 5460 5461where *NamespaceName* is the name of the namespace and *NamespaceStatements* is the code generated for the statements in the namespace body. The *NamespaceName* 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 namespace 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 namespace instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that namespaces can extend each other. 5462 5463An import statement generates code of the form 5464 5465```TypeScript 5466var <Alias> = <EntityName>; 5467``` 5468 5469This code is emitted only if the imported entity is referenced as a *PrimaryExpression* somewhere in the body of the importing namespace. If an imported entity is referenced only as a *TypeName* or *NamespaceName*, nothing is emitted. This ensures that types declared in one namespace can be referenced through an import alias in another namespace with no run-time overhead. 5470 5471When a variable is exported, all references to the variable in the body of the namespace are replaced with 5472 5473```TypeScript 5474<NamespaceName>.<VariableName> 5475``` 5476 5477This effectively promotes the variable to be a property on the namespace instance and ensures that all references to the variable become references to the property. 5478 5479When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form 5480 5481```TypeScript 5482<NamespaceName>.<EntityName> = <EntityName>; 5483``` 5484 5485This copies a reference to the entity into a property on the namespace instance. 5486 5487<br/> 5488 5489# <a name="11"/>11 Scripts and Modules 5490 5491TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems. 5492 5493## <a name="11.1"/>11.1 Programs and Source Files 5494 5495A TypeScript ***program*** consists of one or more source files. 5496 5497  *SourceFile:* 5498   *ImplementationSourceFile* 5499   *DeclarationSourceFile* 5500 5501  *ImplementationSourceFile:* 5502   *ImplementationScript* 5503   *ImplementationModule* 5504 5505  *DeclarationSourceFile:* 5506   *DeclarationScript* 5507   *DeclarationModule* 5508 5509Source files with extension '.ts' are ***implementation source files*** containing statements and declarations, and source files with extension '.d.ts' are ***declaration source files*** containing declarations only. 5510 5511Declaration source files are a strict subset of implementation source files and are 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. 5512 5513When 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. 5514 5515### <a name="11.1.1"/>11.1.1 Source Files Dependencies 5516 5517The 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 module import declarations as follows: 5518 5519* A comment of the form /// <reference path="…"/> that occurs before the first token in a source file 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. 5520* A module import declaration that specifies a relative module name (section [11.3.1](#11.3.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. 5521* A module import declaration that specifies a top-level module name (section [11.3.1](#11.3.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. 5522 5523Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined. 5524 5525## <a name="11.2"/>11.2 Scripts 5526 5527Source files that contain no module import or export declarations are classified as ***scripts***. Scripts form the single ***global namespace*** and entities declared in scripts are in scope everywhere in a program. 5528 5529  *ImplementationScript:* 5530   *ImplementationScriptElements<sub>opt</sub>* 5531 5532  *ImplementationScriptElements:* 5533   *ImplementationScriptElement* 5534   *ImplementationScriptElements* *ImplementationScriptElement* 5535 5536  *ImplementationScriptElement:* 5537   *ImplementationElement* 5538   *AmbientModuleDeclaration* 5539 5540  *ImplementationElement:* 5541   *Statement* 5542   *LexicalDeclaration* 5543   *FunctionDeclaration* 5544   *GeneratorDeclaration* 5545   *ClassDeclaration* 5546   *InterfaceDeclaration* 5547   *TypeAliasDeclaration* 5548   *EnumDeclaration* 5549   *NamespaceDeclaration* 5550   *AmbientDeclaration* 5551   *ImportAliasDeclaration* 5552 5553  *DeclarationScript:* 5554   *DeclarationScriptElements<sub>opt</sub>* 5555 5556  *DeclarationScriptElements:* 5557   *DeclarationScriptElement* 5558   *DeclarationScriptElements* *DeclarationScriptElement* 5559 5560  *DeclarationScriptElement:* 5561   *DeclarationElement* 5562   *AmbientModuleDeclaration* 5563 5564  *DeclarationElement:* 5565   *InterfaceDeclaration* 5566   *TypeAliasDeclaration* 5567   *NamespaceDeclaration* 5568   *AmbientDeclaration* 5569   *ImportAliasDeclaration* 5570 5571The initialization order of the scripts that make up the global namespace ultimately depends on the order in which the generated JavaScript files are loaded at run-time (which, for example, may be controlled by <script/> tags that reference the generated JavaScript files). 5572 5573## <a name="11.3"/>11.3 Modules 5574 5575Source files that contain at least one module import or export declaration are considered separate ***modules***. Non-exported entities declared in a module are in scope only in that module, but exported entities can be imported into other modules using import declarations. 5576 5577  *ImplementationModule:* 5578   *ImplementationModuleElements<sub>opt</sub>* 5579 5580  *ImplementationModuleElements:* 5581   *ImplementationModuleElement* 5582   *ImplementationModuleElements* *ImplementationModuleElement* 5583 5584  *ImplementationModuleElement:* 5585   *ImplementationElement* 5586   *ImportDeclaration* 5587   *ImportAliasDeclaration* 5588   *ImportRequireDeclaration* 5589   *ExportImplementationElement* 5590   *ExportDefaultImplementationElement* 5591   *ExportListDeclaration* 5592   *ExportAssignment* 5593 5594  *DeclarationModule:* 5595   *DeclarationModuleElements<sub>opt</sub>* 5596 5597  *DeclarationModuleElements:* 5598   *DeclarationModuleElement* 5599   *DeclarationModuleElements* *DeclarationModuleElement* 5600 5601  *DeclarationModuleElement:* 5602   *DeclarationElement* 5603   *ImportDeclaration* 5604   *ImportAliasDeclaration* 5605   *ExportDeclarationElement* 5606   *ExportDefaultDeclarationElement* 5607   *ExportListDeclaration* 5608   *ExportAssignment* 5609 5610Initialization order of modules is determined by the module loader being used and is not specified by the TypeScript language. However, it is generally the case that non-circularly dependent modules are automatically loaded and initialized in the correct order. 5611 5612Modules can additionally be declared using *AmbientModuleDeclarations* in declaration scripts that directly specify the module names as string literals. This is described further in section [12.2](#12.2). 5613 5614Below is an example of two modules written in separate source files: 5615 5616```TypeScript 5617// -------- main.ts -------- 5618import { message } from "./log"; 5619message("hello"); 5620 5621// -------- log.ts -------- 5622export function message(s: string) { 5623 console.log(s); 5624} 5625``` 5626 5627The 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. 5628 5629TypeScript supports multiple patterns of JavaScript code generation for modules: 5630 5631* CommonJS. This format is used by server frameworks such as node.js. 5632* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS. 5633* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders. 5634* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments. 5635 5636The 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 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. 5637 5638### <a name="11.3.1"/>11.3.1 Module Names 5639 5640Modules are identified and referenced using module names. The following definition is aligned with that provided in the [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) 1.0 specification. 5641 5642* A module name is a string of terms delimited by forward slashes. 5643* Module names may not have file-name extensions like ".js". 5644* Module names may be relative or top-level. A module name is relative if the first term is "." or "..". 5645* Top-level names are resolved off the conceptual module name space root. 5646* Relative names are resolved relative to the name of the module in which they occur. 5647 5648For purposes of resolving module references, TypeScript associates a file path with every module. The file path is simply the path of the module's source file without the file extension. For example, a module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and a module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'. 5649 5650A module name in an import declaration is resolved as follows: 5651 5652* If the import declaration specifies a relative 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 module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'. 5653* If the import declaration specifies a top-level module name and the program contains an *AmbientModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, then the import declaration references that ambient module. 5654* If the import declaration specifies a top-level module name and the program contains no *AmbientModuleDeclaration* (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. 5655 5656### <a name="11.3.2"/>11.3.2 Import Declarations 5657 5658Import declarations are used to import entities from other modules and provide bindings for them in the current module. 5659 5660An import declaration of the form 5661 5662```TypeScript 5663import * as m from "mod"; 5664``` 5665 5666imports the module with the given name and creates a local binding for the module itself. The local binding is classified as a value (representing the module instance) and a namespace (representing a container of types and namespaces). 5667 5668An import declaration of the form 5669 5670```TypeScript 5671import { x, y, z } from "mod"; 5672``` 5673 5674imports a given module and creates local bindings for a specified list of exported members of the module. The specified names must each reference an entity in the export member set ([11.3.4.4](#11.3.4.4)) of the given module. The local bindings have the same names and classifications as the entities they represent unless `as` clauses are used to that specify different local names: 5675 5676```TypeScript 5677import { x as a, y as b } from "mod"; 5678``` 5679 5680An import declaration of the form 5681 5682```TypeScript 5683import d from "mod"; 5684``` 5685 5686is exactly equivalent to the import declaration 5687 5688```TypeScript 5689import { default as d } from "mod"; 5690``` 5691 5692An import declaration of the form 5693 5694```TypeScript 5695import "mod"; 5696``` 5697 5698imports the given module without creating any local bindings (this is useful only if the imported module has side effects). 5699 5700### <a name="11.3.3"/>11.3.3 Import Require Declarations 5701 5702Import require declarations exist for backward compatibility with earlier versions of TypeScript. 5703 5704  *ImportRequireDeclaration:* 5705   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` 5706 5707An import require declaration introduces a local identifier that references a given module. The string literal specified in an import require declaration is interpreted as a module name (section [11.3.1](#11.3.1)). The local identifier introduced by the declaration becomes an alias for, and is classified exactly like, the entity exported from the referenced module. Specifically, if the referenced module contains no export assignment the identifier is classified as a value and a namespace, and if the referenced module contains an export assignment the identifier is classified exactly like the entity named in the export assignment. 5708 5709An import require declaration of the form 5710 5711```TypeScript 5712import m = require("mod"); 5713``` 5714 5715is equivalent to the ECMAScript 2015 import declaration 5716 5717```TypeScript 5718import * as m from "mod"; 5719``` 5720 5721provided the referenced module contains no export assignment. 5722 5723### <a name="11.3.4"/>11.3.4 Export Declarations 5724 5725An export declaration declares one or more exported module members. The exported members of a module can be imported in other modules using import declarations ([11.3.2](#11.3.2)). 5726 5727#### <a name="11.3.4.1"/>11.3.4.1 Export Modifiers 5728 5729In the body of a module, a declaration can export the declared entity by including an `export` modifier. 5730 5731  *ExportImplementationElement:* 5732   `export` *VariableStatement* 5733   `export` *LexicalDeclaration* 5734   `export` *FunctionDeclaration* 5735   `export` *GeneratorDeclaration* 5736   `export` *ClassDeclaration* 5737   `export` *InterfaceDeclaration* 5738   `export` *TypeAliasDeclaration* 5739   `export` *EnumDeclaration* 5740   `export` *NamespaceDeclaration* 5741   `export` *AmbientDeclaration* 5742   `export` *ImportAliasDeclaration* 5743 5744  *ExportDeclarationElement:* 5745   `export` *InterfaceDeclaration* 5746   `export` *TypeAliasDeclaration* 5747   `export` *AmbientDeclaration* 5748   `export` *ImportAliasDeclaration* 5749 5750In addition to introducing a name in the local declaration space of the module, an exported declaration introduces the same name with the same classification in the module's export declaration space. For example, the declaration 5751 5752```TypeScript 5753export function point(x: number, y: number) { 5754 return { x, y }; 5755} 5756``` 5757 5758introduces a local name `point` and an exported name `point` that both reference the function. 5759 5760#### <a name="11.3.4.2"/>11.3.4.2 Export Default Declarations 5761 5762Export default declarations provide short-hand syntax for exporting an entity named `default`. 5763 5764  *ExportDefaultImplementationElement:* 5765   `export` `default` *FunctionDeclaration* 5766   `export` `default` *GeneratorDeclaration* 5767   `export` `default` *ClassDeclaration* 5768   `export` `default` *AssignmentExpression* `;` 5769 5770  *ExportDefaultDeclarationElement:* 5771   `export` `default` *AmbientFunctionDeclaration* 5772   `export` `default` *AmbientClassDeclaration* 5773   `export` `default` *IdentifierReference* `;` 5774 5775An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for a function, generator, or class introduces a value named `default`, and in the case of a class, a type named `default`, in the containing module's export declaration space. The declaration may optionally specify a local name for the exported function, generator, or class. For example, the declaration 5776 5777```TypeScript 5778export default function point(x: number, y: number) { 5779 return { x, y }; 5780} 5781``` 5782 5783introduces a local name `point` and an exported name `default` that both reference the function. The declaration is effectively equivalent to 5784 5785```TypeScript 5786function point(x: number, y: number) { 5787 return { x, y }; 5788} 5789 5790export default point; 5791``` 5792 5793which again is equivalent to 5794 5795```TypeScript 5796function point(x: number, y: number) { 5797 return { x, y }; 5798} 5799 5800export { point as default }; 5801``` 5802 5803An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for an expression consisting of a single identifier must name an entity declared in the current module or the global namespace. The declaration introduces an entity named `default`, with the same classification as the referenced entity, in the containing module's export declaration space. For example, the declarations 5804 5805```TypeScript 5806interface Point { 5807 x: number; 5808 y: number; 5809} 5810 5811function Point(x: number, y: number): Point { 5812 return { x, y }; 5813} 5814 5815export default Point; 5816``` 5817 5818introduce a local name `Point` and an exported name `default`, both with a value and a type meaning. 5819 5820An *ExportDefaultImplementationElement* for any expression but a single identifier introduces a value named `default` in the containing module's export declaration space. For example, the declaration 5821 5822```TypeScript 5823export default "hello"; 5824``` 5825 5826introduces an exported value named `default` of type string. 5827 5828#### <a name="11.3.4.3"/>11.3.4.3 Export List Declarations 5829 5830An export list declaration exports one or more entities from the current module or a specified module. 5831 5832  *ExportListDeclaration:* 5833   `export` `*` *FromClause* `;` 5834   `export` *ExportClause* *FromClause* `;` 5835   `export` *ExportClause* `;` 5836 5837An *ExportListDeclaration* without a *FromClause* exports entities from the current module. In a declaration of the form 5838 5839```TypeScript 5840export { x }; 5841``` 5842 5843the name `x` must reference an entity declared in the current module or the global namespace, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. 5844 5845An *ExportListDeclaration* with a *FromClause* re-exports entities from a specified module. In a declaration of the form 5846 5847```TypeScript 5848export { x } from "mod"; 5849``` 5850 5851the name `x` must reference an entity in the export member set of the specified module, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. No local bindings are created for `x`. 5852 5853The *ExportClause* of an *ExportListDeclaration* can specify multiple entities and may optionally specify different names to be used for the exported entities. For example, the declaration 5854 5855```TypeScript 5856export { x, y as b, z as c }; 5857``` 5858 5859introduces entities named `x`, `b`, and `c` in the containing module's export declaration space with the same meaning as the local entities named `x`, `y`, and `z` respectively. 5860 5861An *ExportListDeclaration* that specifies `*` instead of an *ExportClause* is called an ***export star*** declaration. An export star declaration re-exports all members of a specified module. 5862 5863```TypeScript 5864export * from "mod"; 5865``` 5866 5867Explicitly exported members take precedence over members re-exported using export star declarations, as described in the following section. 5868 5869#### <a name="11.3.4.4"/>11.3.4.4 Export Member Set 5870 5871The ***export member set*** of a particular module is determined by starting with an empty set of members *E* and an empty set of processed modules *P*, and then processing the module as described below to form the full set of exported members in *E*. Processing a module *M* consists of these steps: 5872 5873* Add *M* to *P*. 5874* Add to *E* each member in the export declaration space of *M* with a name that isn't already in *E*. 5875* For each export star declaration in *M*, in order of declaration, process the referenced module if it is not already in *P*. 5876 5877A module's ***instance type*** is an object type with a property for each member in the module's export member set that denotes a value. 5878 5879If a module contains an export assignment it is an error for the module to also contain export declarations. The two types of exports are mutually exclusive. 5880 5881### <a name="11.3.5"/>11.3.5 Export Assignments 5882 5883Export assignments exist for backward compatibility with earlier versions of TypeScript. An export assignment designates a module member as the entity to be exported in place of the module itself. 5884 5885  *ExportAssignment:* 5886   `export` `=` *IdentifierReference* `;` 5887 5888A module containing an export assignment can be imported using an import require declaration ([11.3.3](#11.3.3)), and the local alias introduced by the import require declaration then takes on all meanings of the identifier named in the export assignment. 5889 5890A module containing an export assignment can also be imported using a regular import declaration ([11.3.2](#11.3.2)) provided the entity referenced in the export assignment is declared as a namespace or as a variable with a type annotation. 5891 5892Assume the following example resides in the file 'point.ts': 5893 5894```TypeScript 5895export = Point; 5896 5897class Point { 5898 constructor(public x: number, public y: number) { } 5899 static origin = new Point(0, 0); 5900} 5901``` 5902 5903When 'point.ts' is imported in another module, the import alias references the exported class and can be used both as a type and as a constructor function: 5904 5905```TypeScript 5906import Pt = require("./point"); 5907 5908var p1 = new Pt(10, 20); 5909var p2 = Pt.origin; 5910``` 5911 5912Note that there is no requirement that the import alias use the same name as the exported entity. 5913 5914### <a name="11.3.6"/>11.3.6 CommonJS Modules 5915 5916The [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) 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 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. 5917 5918The 'main' and 'log' example from section [11.3](#11.3) above generates the following JavaScript code when compiled for the CommonJS Modules pattern: 5919 5920File main.js: 5921 5922```TypeScript 5923var log_1 = require("./log"); 5924log_1.message("hello"); 5925``` 5926 5927File log.js: 5928 5929```TypeScript 5930function message(s) { 5931 console.log(s); 5932} 5933exports.message = message; 5934``` 5935 5936A module 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 *NamespaceName* or *TypeQueryExpression*, nothing is emitted. 5937 5938An example: 5939 5940File geometry.ts: 5941 5942```TypeScript 5943export interface Point { x: number; y: number }; 5944 5945export function point(x: number, y: number): Point { 5946 return { x, y }; 5947} 5948``` 5949 5950File game.ts: 5951 5952```TypeScript 5953import * as g from "./geometry"; 5954let p = g.point(10, 20); 5955``` 5956 5957The '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: 5958 5959```TypeScript 5960var g = require("./geometry"); 5961var p = g.point(10, 20); 5962``` 5963 5964Had the 'game' module instead been written to only reference 'geometry' in a type position 5965 5966```TypeScript 5967import * as g from "./geometry"; 5968let p: g.Point = { x: 10, y: 20 }; 5969``` 5970 5971the emitted JavaScript would have no dependency on the 'geometry' module and would simply be 5972 5973```TypeScript 5974var p = { x: 10, y: 20 }; 5975``` 5976 5977### <a name="11.3.7"/>11.3.7 AMD Modules 5978 5979The [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) (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 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. 5980 5981The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern. 5982 5983File main.js: 5984 5985```TypeScript 5986define(["require", "exports", "./log"], function(require, exports, log_1) { 5987 log_1.message("hello"); 5988} 5989``` 5990 5991File log.js: 5992 5993```TypeScript 5994define(["require", "exports"], function(require, exports) { 5995 function message(s) { 5996 console.log(s); 5997 } 5998 exports.message = message; 5999} 6000``` 6001 6002The 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 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 *NamespaceName*, no dependency is generated for that module. 6003 6004<br/> 6005 6006# <a name="12"/>12 Ambients 6007 6008Ambient 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 namespaces, 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. 6009 6010## <a name="12.1"/>12.1 Ambient Declarations 6011 6012Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, namespaces, or modules. 6013 6014  *AmbientDeclaration:* 6015   `declare` *AmbientVariableDeclaration* 6016   `declare` *AmbientFunctionDeclaration* 6017   `declare` *AmbientClassDeclaration* 6018   `declare` *AmbientEnumDeclaration* 6019   `declare` *AmbientNamespaceDeclaration* 6020 6021### <a name="12.1.1"/>12.1.1 Ambient Variable Declarations 6022 6023An ambient variable declaration introduces a variable in the containing declaration space. 6024 6025  *AmbientVariableDeclaration:* 6026   `var` *AmbientBindingList* `;` 6027   `let` *AmbientBindingList* `;` 6028   `const` *AmbientBindingList* `;` 6029 6030  *AmbientBindingList:* 6031   *AmbientBinding* 6032   *AmbientBindingList* `,` *AmbientBinding* 6033 6034  *AmbientBinding:* 6035   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* 6036 6037An ambient variable declaration may optionally include a type annotation. If no type annotation is present, the variable is assumed to have type Any. 6038 6039An ambient variable declaration does not permit an initializer expression to be present. 6040 6041### <a name="12.1.2"/>12.1.2 Ambient Function Declarations 6042 6043An ambient function declaration introduces a function in the containing declaration space. 6044 6045  *AmbientFunctionDeclaration:* 6046   `function` *BindingIdentifier* *CallSignature* `;` 6047 6048Ambient functions may be overloaded by specifying multiple ambient function declarations with the same name, but it is an error to declare multiple overloads that are considered identical (section [3.11.2](#3.11.2)) or differ only in their return types. 6049 6050Ambient function declarations cannot specify a function bodies and do not permit default parameter values. 6051 6052### <a name="12.1.3"/>12.1.3 Ambient Class Declarations 6053 6054An ambient class declaration declares a class type and a constructor function in the containing declaration space. 6055 6056  *AmbientClassDeclaration:* 6057   `class` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *AmbientClassBody* `}` 6058 6059  *AmbientClassBody:* 6060   *AmbientClassBodyElements<sub>opt</sub>* 6061 6062  *AmbientClassBodyElements:* 6063   *AmbientClassBodyElement* 6064   *AmbientClassBodyElements* *AmbientClassBodyElement* 6065 6066  *AmbientClassBodyElement:* 6067   *AmbientConstructorDeclaration* 6068   *AmbientPropertyMemberDeclaration* 6069   *IndexSignature* 6070 6071  *AmbientConstructorDeclaration:* 6072   `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;` 6073 6074  *AmbientPropertyMemberDeclaration:* 6075   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* `;` 6076   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;` 6077 6078### <a name="12.1.4"/>12.1.4 Ambient Enum Declarations 6079 6080An ambient enum is grammatically equivalent to a non-ambient enum declaration. 6081 6082  *AmbientEnumDeclaration:* 6083   *EnumDeclaration* 6084 6085Ambient enum declarations differ from non-ambient enum declarations in two ways: 6086 6087* In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions. 6088* In ambient enum declarations that specify no `const` modifier, enum member declarations that omit a value are considered computed members (as opposed to having auto-incremented values assigned). 6089 6090Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations. 6091 6092### <a name="12.1.5"/>12.1.5 Ambient Namespace Declarations 6093 6094An ambient namespace declaration declares a namespace. 6095 6096  *AmbientNamespaceDeclaration:* 6097   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` 6098 6099  *AmbientNamespaceBody:* 6100   *AmbientNamespaceElements<sub>opt</sub>* 6101 6102  *AmbientNamespaceElements:* 6103   *AmbientNamespaceElement* 6104   *AmbientNamespaceElements* *AmbientNamespaceElement* 6105 6106  *AmbientNamespaceElement:* 6107   `export`*<sub>opt</sub>* *AmbientVariableDeclaration* 6108   `export`*<sub>opt</sub>* *AmbientLexicalDeclaration* 6109   `export`*<sub>opt</sub>* *AmbientFunctionDeclaration* 6110   `export`*<sub>opt</sub>* *AmbientClassDeclaration* 6111   `export`*<sub>opt</sub>* *InterfaceDeclaration* 6112   `export`*<sub>opt</sub>* *AmbientEnumDeclaration* 6113   `export`*<sub>opt</sub>* *AmbientNamespaceDeclaration* 6114   `export`*<sub>opt</sub>* *ImportAliasDeclaration* 6115 6116Except for *ImportAliasDeclarations*, *AmbientNamespaceElements* always declare exported entities regardless of whether they include the optional `export` modifier. 6117 6118## <a name="12.2"/>12.2 Ambient Module Declarations 6119 6120An *AmbientModuleDeclaration* declares a module. This type of declaration is permitted only at the top level in a source file that contributes to the global namespace (section [11.1](#11.1)). The *StringLiteral* must specify a top-level module name. Relative module names are not permitted. 6121 6122  *AmbientModuleDeclaration:* 6123   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` 6124 6125An *ImportRequireDeclaration* in an *AmbientModuleDeclaration* may reference other modules only through top-level module names. Relative module names are not permitted. 6126 6127If an ambient 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 module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier. 6128 6129Ambient modules are "open-ended" and ambient module declarations with the same string literal name contribute to a single module. For example, the following two declarations of a module 'io' might be located in separate source files. 6130 6131```TypeScript 6132declare module "io" { 6133 export function readFile(filename: string): string; 6134} 6135 6136declare module "io" { 6137 export function writeFile(filename: string, data: string): void; 6138} 6139``` 6140 6141This has the same effect as a single combined declaration: 6142 6143```TypeScript 6144declare module "io" { 6145 export function readFile(filename: string): string; 6146 export function writeFile(filename: string, data: string): void; 6147} 6148``` 6149 6150<br/> 6151 6152# <a name="A"/>A Grammar 6153 6154This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar. 6155 6156## <a name="A.1"/>A.1 Types 6157 6158  *TypeParameters:* 6159   `<` *TypeParameterList* `>` 6160 6161  *TypeParameterList:* 6162   *TypeParameter* 6163   *TypeParameterList* `,` *TypeParameter* 6164 6165  *TypeParameter:* 6166   *BindingIdentifier* *Constraint<sub>opt</sub>* 6167 6168  *Constraint:* 6169   `extends` *Type* 6170 6171  *TypeArguments:* 6172   `<` *TypeArgumentList* `>` 6173 6174  *TypeArgumentList:* 6175   *TypeArgument* 6176   *TypeArgumentList* `,` *TypeArgument* 6177 6178  *TypeArgument:* 6179   *Type* 6180 6181  *Type:* 6182   *UnionOrIntersectionOrPrimaryType* 6183   *FunctionType* 6184   *ConstructorType* 6185 6186  *UnionOrIntersectionOrPrimaryType:* 6187   *UnionType* 6188   *IntersectionOrPrimaryType* 6189 6190  *IntersectionOrPrimaryType:* 6191   *IntersectionType* 6192   *PrimaryType* 6193 6194  *PrimaryType:* 6195   *ParenthesizedType* 6196   *PredefinedType* 6197   *TypeReference* 6198   *ObjectType* 6199   *ArrayType* 6200   *TupleType* 6201   *TypeQuery* 6202   *ThisType* 6203 6204  *ParenthesizedType:* 6205   `(` *Type* `)` 6206 6207  *PredefinedType:* 6208   `any` 6209   `number` 6210   `boolean` 6211   `string` 6212   `symbol` 6213   `void` 6214 6215  *TypeReference:* 6216   *TypeName* *[no LineTerminator here]* *TypeArguments<sub>opt</sub>* 6217 6218  *TypeName:* 6219   *IdentifierReference* 6220   *NamespaceName* `.` *IdentifierReference* 6221 6222  *NamespaceName:* 6223   *IdentifierReference* 6224   *NamespaceName* `.` *IdentifierReference* 6225 6226  *ObjectType:* 6227   `{` *TypeBody<sub>opt</sub>* `}` 6228 6229  *TypeBody:* 6230   *TypeMemberList* `;`*<sub>opt</sub>* 6231   *TypeMemberList* `,`*<sub>opt</sub>* 6232 6233  *TypeMemberList:* 6234   *TypeMember* 6235   *TypeMemberList* `;` *TypeMember* 6236   *TypeMemberList* `,` *TypeMember* 6237 6238  *TypeMember:* 6239   *PropertySignature* 6240   *CallSignature* 6241   *ConstructSignature* 6242   *IndexSignature* 6243   *MethodSignature* 6244 6245  *ArrayType:* 6246   *PrimaryType* *[no LineTerminator here]* `[` `]` 6247 6248  *TupleType:* 6249   `[` *TupleElementTypes* `]` 6250 6251  *TupleElementTypes:* 6252   *TupleElementType* 6253   *TupleElementTypes* `,` *TupleElementType* 6254 6255  *TupleElementType:* 6256   *Type* 6257 6258  *UnionType:* 6259   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* 6260 6261  *IntersectionType:* 6262   *IntersectionOrPrimaryType* `&` *PrimaryType* 6263 6264  *FunctionType:* 6265   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type* 6266 6267  *ConstructorType:* 6268   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type* 6269 6270  *TypeQuery:* 6271   `typeof` *TypeQueryExpression* 6272 6273  *TypeQueryExpression:* 6274   *IdentifierReference* 6275   *TypeQueryExpression* `.` *IdentifierName* 6276 6277  *ThisType:* 6278   `this` 6279 6280  *PropertySignature:* 6281   *PropertyName* `?`*<sub>opt</sub>* *TypeAnnotation<sub>opt</sub>* 6282 6283  *PropertyName:* 6284   *IdentifierName* 6285   *StringLiteral* 6286   *NumericLiteral* 6287 6288  *TypeAnnotation:* 6289   `:` *Type* 6290 6291  *CallSignature:* 6292   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>* 6293 6294  *ParameterList:* 6295   *RequiredParameterList* 6296   *OptionalParameterList* 6297   *RestParameter* 6298   *RequiredParameterList* `,` *OptionalParameterList* 6299   *RequiredParameterList* `,` *RestParameter* 6300   *OptionalParameterList* `,` *RestParameter* 6301   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter* 6302 6303  *RequiredParameterList:* 6304   *RequiredParameter* 6305   *RequiredParameterList* `,` *RequiredParameter* 6306 6307  *RequiredParameter:* 6308   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* 6309   *BindingIdentifier* `:` *StringLiteral* 6310 6311  *AccessibilityModifier:* 6312   `public` 6313   `private` 6314   `protected` 6315 6316  *BindingIdentifierOrPattern:* 6317   *BindingIdentifier* 6318   *BindingPattern* 6319 6320  *OptionalParameterList:* 6321   *OptionalParameter* 6322   *OptionalParameterList* `,` *OptionalParameter* 6323 6324  *OptionalParameter:* 6325   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* `?` *TypeAnnotation<sub>opt</sub>* 6326   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* *Initializer* 6327   *BindingIdentifier* `?` `:` *StringLiteral* 6328 6329  *RestParameter:* 6330   `...` *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* 6331 6332  *ConstructSignature:* 6333   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>* 6334 6335  *IndexSignature:* 6336   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation* 6337   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation* 6338 6339  *MethodSignature:* 6340   *PropertyName* `?`*<sub>opt</sub>* *CallSignature* 6341 6342  *TypeAliasDeclaration:* 6343   `type` *BindingIdentifier* *TypeParameters<sub>opt</sub>* `=` *Type* `;` 6344 6345## <a name="A.2"/>A.2 Expressions 6346 6347  *PropertyDefinition:* *( Modified )* 6348   *IdentifierReference* 6349   *CoverInitializedName* 6350   *PropertyName* `:` *AssignmentExpression* 6351   *PropertyName* *CallSignature* `{` *FunctionBody* `}` 6352   *GetAccessor* 6353   *SetAccessor* 6354 6355  *GetAccessor:* 6356   `get` *PropertyName* `(` `)` *TypeAnnotation<sub>opt</sub>* `{` *FunctionBody* `}` 6357 6358  *SetAccessor:* 6359   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* `)` `{` *FunctionBody* `}` 6360 6361  *FunctionExpression:* *( Modified )* 6362   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}` 6363 6364  *ArrowFormalParameters:* *( Modified )* 6365   *CallSignature* 6366 6367  *Arguments:* *( Modified )* 6368   *TypeArguments<sub>opt</sub>* `(` *ArgumentList<sub>opt</sub>* `)` 6369 6370  *UnaryExpression:* *( Modified )* 6371   … 6372   `<` *Type* `>` *UnaryExpression* 6373 6374## <a name="A.3"/>A.3 Statements 6375 6376  *Declaration:* *( Modified )* 6377   … 6378   *InterfaceDeclaration* 6379   *TypeAliasDeclaration* 6380   *EnumDeclaration* 6381 6382  *VariableDeclaration:* *( Modified )* 6383   *SimpleVariableDeclaration* 6384   *DestructuringVariableDeclaration* 6385 6386  *SimpleVariableDeclaration:* 6387   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 6388 6389  *DestructuringVariableDeclaration:* 6390   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer* 6391 6392  *LexicalBinding:* *( Modified )* 6393   *SimpleLexicalBinding* 6394   *DestructuringLexicalBinding* 6395 6396  *SimpleLexicalBinding:* 6397   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 6398 6399  *DestructuringLexicalBinding:* 6400   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* 6401 6402## <a name="A.4"/>A.4 Functions 6403 6404  *FunctionDeclaration:* *( Modified )* 6405   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}` 6406   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `;` 6407 6408## <a name="A.5"/>A.5 Interfaces 6409 6410  *InterfaceDeclaration:* 6411   `interface` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *InterfaceExtendsClause<sub>opt</sub>* *ObjectType* 6412 6413  *InterfaceExtendsClause:* 6414   `extends` *ClassOrInterfaceTypeList* 6415 6416  *ClassOrInterfaceTypeList:* 6417   *ClassOrInterfaceType* 6418   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType* 6419 6420  *ClassOrInterfaceType:* 6421   *TypeReference* 6422 6423## <a name="A.6"/>A.6 Classes 6424 6425  *ClassDeclaration:* *( Modified )* 6426   `class` *BindingIdentifier<sub>opt</sub>* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *ClassBody* `}` 6427 6428  *ClassHeritage:* *( Modified )* 6429   *ClassExtendsClause<sub>opt</sub>* *ImplementsClause<sub>opt</sub>* 6430 6431  *ClassExtendsClause:* 6432   `extends`  *ClassType* 6433 6434  *ClassType:* 6435   *TypeReference* 6436 6437  *ImplementsClause:* 6438   `implements` *ClassOrInterfaceTypeList* 6439 6440  *ClassElement:* *( Modified )* 6441   *ConstructorDeclaration* 6442   *PropertyMemberDeclaration* 6443   *IndexMemberDeclaration* 6444 6445  *ConstructorDeclaration:* 6446   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `{` *FunctionBody* `}` 6447   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;` 6448 6449  *PropertyMemberDeclaration:* 6450   *MemberVariableDeclaration* 6451   *MemberFunctionDeclaration* 6452   *MemberAccessorDeclaration* 6453 6454  *MemberVariableDeclaration:* 6455   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* `;` 6456 6457  *MemberFunctionDeclaration:* 6458   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `{` *FunctionBody* `}` 6459   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;` 6460 6461  *MemberAccessorDeclaration:* 6462   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *GetAccessor* 6463   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *SetAccessor* 6464 6465  *IndexMemberDeclaration:* 6466   *IndexSignature* `;` 6467 6468## <a name="A.7"/>A.7 Enums 6469 6470  *EnumDeclaration:* 6471   `const`*<sub>opt</sub>* `enum` *BindingIdentifier* `{` *EnumBody<sub>opt</sub>* `}` 6472 6473  *EnumBody:* 6474   *EnumMemberList* `,`*<sub>opt</sub>* 6475 6476  *EnumMemberList:* 6477   *EnumMember* 6478   *EnumMemberList* `,` *EnumMember* 6479 6480  *EnumMember:* 6481   *PropertyName* 6482   *PropertyName* = *EnumValue* 6483 6484  *EnumValue:* 6485   *AssignmentExpression* 6486 6487## <a name="A.8"/>A.8 Namespaces 6488 6489  *NamespaceDeclaration:* 6490   `namespace` *IdentifierPath* `{` *NamespaceBody* `}` 6491 6492  *IdentifierPath:* 6493   *BindingIdentifier* 6494   *IdentifierPath* `.` *BindingIdentifier* 6495 6496  *NamespaceBody:* 6497   *NamespaceElements<sub>opt</sub>* 6498 6499  *NamespaceElements:* 6500   *NamespaceElement* 6501   *NamespaceElements* *NamespaceElement* 6502 6503  *NamespaceElement:* 6504   *Statement* 6505   *LexicalDeclaration* 6506   *FunctionDeclaration* 6507   *GeneratorDeclaration* 6508   *ClassDeclaration* 6509   *InterfaceDeclaration* 6510   *TypeAliasDeclaration* 6511   *EnumDeclaration* 6512   *NamespaceDeclaration 6513   AmbientDeclaration 6514   ImportAliasDeclaration 6515   ExportNamespaceElement* 6516 6517  *ExportNamespaceElement:* 6518   `export` *VariableStatement* 6519   `export` *LexicalDeclaration* 6520   `export` *FunctionDeclaration* 6521   `export` *GeneratorDeclaration* 6522   `export` *ClassDeclaration* 6523   `export` *InterfaceDeclaration* 6524   `export` *TypeAliasDeclaration* 6525   `export` *EnumDeclaration* 6526   `export` *NamespaceDeclaration* 6527   `export` *AmbientDeclaration* 6528   `export` *ImportAliasDeclaration* 6529 6530  *ImportAliasDeclaration:* 6531   `import` *BindingIdentifier* `=` *EntityName* `;` 6532 6533  *EntityName:* 6534   *NamespaceName* 6535   *NamespaceName* `.` *IdentifierReference* 6536 6537## <a name="A.9"/>A.9 Scripts and Modules 6538 6539  *SourceFile:* 6540   *ImplementationSourceFile* 6541   *DeclarationSourceFile* 6542 6543  *ImplementationSourceFile:* 6544   *ImplementationScript* 6545   *ImplementationModule* 6546 6547  *DeclarationSourceFile:* 6548   *DeclarationScript* 6549   *DeclarationModule* 6550 6551  *ImplementationScript:* 6552   *ImplementationScriptElements<sub>opt</sub>* 6553 6554  *ImplementationScriptElements:* 6555   *ImplementationScriptElement* 6556   *ImplementationScriptElements* *ImplementationScriptElement* 6557 6558  *ImplementationScriptElement:* 6559   *ImplementationElement* 6560   *AmbientModuleDeclaration* 6561 6562  *ImplementationElement:* 6563   *Statement* 6564   *LexicalDeclaration* 6565   *FunctionDeclaration* 6566   *GeneratorDeclaration* 6567   *ClassDeclaration* 6568   *InterfaceDeclaration* 6569   *TypeAliasDeclaration* 6570   *EnumDeclaration* 6571   *NamespaceDeclaration* 6572   *AmbientDeclaration* 6573   *ImportAliasDeclaration* 6574 6575  *DeclarationScript:* 6576   *DeclarationScriptElements<sub>opt</sub>* 6577 6578  *DeclarationScriptElements:* 6579   *DeclarationScriptElement* 6580   *DeclarationScriptElements* *DeclarationScriptElement* 6581 6582  *DeclarationScriptElement:* 6583   *DeclarationElement* 6584   *AmbientModuleDeclaration* 6585 6586  *DeclarationElement:* 6587   *InterfaceDeclaration* 6588   *TypeAliasDeclaration* 6589   *NamespaceDeclaration* 6590   *AmbientDeclaration* 6591   *ImportAliasDeclaration* 6592 6593  *ImplementationModule:* 6594   *ImplementationModuleElements<sub>opt</sub>* 6595 6596  *ImplementationModuleElements:* 6597   *ImplementationModuleElement* 6598   *ImplementationModuleElements* *ImplementationModuleElement* 6599 6600  *ImplementationModuleElement:* 6601   *ImplementationElement* 6602   *ImportDeclaration* 6603   *ImportAliasDeclaration* 6604   *ImportRequireDeclaration* 6605   *ExportImplementationElement* 6606   *ExportDefaultImplementationElement* 6607   *ExportListDeclaration* 6608   *ExportAssignment* 6609 6610  *DeclarationModule:* 6611   *DeclarationModuleElements<sub>opt</sub>* 6612 6613  *DeclarationModuleElements:* 6614   *DeclarationModuleElement* 6615   *DeclarationModuleElements* *DeclarationModuleElement* 6616 6617  *DeclarationModuleElement:* 6618   *DeclarationElement* 6619   *ImportDeclaration* 6620   *ImportAliasDeclaration* 6621   *ExportDeclarationElement* 6622   *ExportDefaultDeclarationElement* 6623   *ExportListDeclaration* 6624   *ExportAssignment* 6625 6626  *ImportRequireDeclaration:* 6627   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;` 6628 6629  *ExportImplementationElement:* 6630   `export` *VariableStatement* 6631   `export` *LexicalDeclaration* 6632   `export` *FunctionDeclaration* 6633   `export` *GeneratorDeclaration* 6634   `export` *ClassDeclaration* 6635   `export` *InterfaceDeclaration* 6636   `export` *TypeAliasDeclaration* 6637   `export` *EnumDeclaration* 6638   `export` *NamespaceDeclaration* 6639   `export` *AmbientDeclaration* 6640   `export` *ImportAliasDeclaration* 6641 6642  *ExportDeclarationElement:* 6643   `export` *InterfaceDeclaration* 6644   `export` *TypeAliasDeclaration* 6645   `export` *AmbientDeclaration* 6646   `export` *ImportAliasDeclaration* 6647 6648  *ExportDefaultImplementationElement:* 6649   `export` `default` *FunctionDeclaration* 6650   `export` `default` *GeneratorDeclaration* 6651   `export` `default` *ClassDeclaration* 6652   `export` `default` *AssignmentExpression* `;` 6653 6654  *ExportDefaultDeclarationElement:* 6655   `export` `default` *AmbientFunctionDeclaration* 6656   `export` `default` *AmbientClassDeclaration* 6657   `export` `default` *IdentifierReference* `;` 6658 6659  *ExportListDeclaration:* 6660   `export` `*` *FromClause* `;` 6661   `export` *ExportClause* *FromClause* `;` 6662   `export` *ExportClause* `;` 6663 6664  *ExportAssignment:* 6665   `export` `=` *IdentifierReference* `;` 6666 6667## <a name="A.10"/>A.10 Ambients 6668 6669  *AmbientDeclaration:* 6670   `declare` *AmbientVariableDeclaration* 6671   `declare` *AmbientFunctionDeclaration* 6672   `declare` *AmbientClassDeclaration* 6673   `declare` *AmbientEnumDeclaration* 6674   `declare` *AmbientNamespaceDeclaration* 6675 6676  *AmbientVariableDeclaration:* 6677   `var` *AmbientBindingList* `;` 6678   `let` *AmbientBindingList* `;` 6679   `const` *AmbientBindingList* `;` 6680 6681  *AmbientBindingList:* 6682   *AmbientBinding* 6683   *AmbientBindingList* `,` *AmbientBinding* 6684 6685  *AmbientBinding:* 6686   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* 6687 6688  *AmbientFunctionDeclaration:* 6689   `function` *BindingIdentifier* *CallSignature* `;` 6690 6691  *AmbientClassDeclaration:* 6692   `class` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *AmbientClassBody* `}` 6693 6694  *AmbientClassBody:* 6695   *AmbientClassBodyElements<sub>opt</sub>* 6696 6697  *AmbientClassBodyElements:* 6698   *AmbientClassBodyElement* 6699   *AmbientClassBodyElements* *AmbientClassBodyElement* 6700 6701  *AmbientClassBodyElement:* 6702   *AmbientConstructorDeclaration* 6703   *AmbientPropertyMemberDeclaration* 6704   *IndexSignature* 6705 6706  *AmbientConstructorDeclaration:* 6707   `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;` 6708 6709  *AmbientPropertyMemberDeclaration:* 6710   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* `;` 6711   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;` 6712 6713  *AmbientEnumDeclaration:* 6714   *EnumDeclaration* 6715 6716  *AmbientNamespaceDeclaration:* 6717   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}` 6718 6719  *AmbientNamespaceBody:* 6720   *AmbientNamespaceElements<sub>opt</sub>* 6721 6722  *AmbientNamespaceElements:* 6723   *AmbientNamespaceElement* 6724   *AmbientNamespaceElements* *AmbientNamespaceElement* 6725 6726  *AmbientNamespaceElement:* 6727   `export`*<sub>opt</sub>* *AmbientVariableDeclaration* 6728   `export`*<sub>opt</sub>* *AmbientLexicalDeclaration* 6729   `export`*<sub>opt</sub>* *AmbientFunctionDeclaration* 6730   `export`*<sub>opt</sub>* *AmbientClassDeclaration* 6731   `export`*<sub>opt</sub>* *InterfaceDeclaration* 6732   `export`*<sub>opt</sub>* *AmbientEnumDeclaration* 6733   `export`*<sub>opt</sub>* *AmbientNamespaceDeclaration* 6734   `export`*<sub>opt</sub>* *ImportAliasDeclaration* 6735 6736  *AmbientModuleDeclaration:* 6737   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}` 6738 6739