diff --git a/Jakefile.js b/Jakefile.js
index 8fbefe1b2cc..396f15e2730 100644
--- a/Jakefile.js
+++ b/Jakefile.js
@@ -17,7 +17,7 @@ var docDirectory = "doc/";
var builtDirectory = "built/";
var builtLocalDirectory = "built/local/";
-var LKGDirectory = "bin/";
+var LKGDirectory = "lib/";
var copyright = "CopyrightNotice.txt";
var thirdParty = "ThirdPartyNoticeText.txt";
@@ -141,7 +141,9 @@ var harnessSources = harnessCoreSources.concat([
"session.ts",
"versionCache.ts",
"convertToBase64.ts",
- "transpile.ts"
+ "transpile.ts",
+ "reuseProgramStructure.ts",
+ "cachingInServerLSHost.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@@ -218,7 +220,7 @@ var compilerFilename = "tsc.js";
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) {
file(outFile, prereqs, function() {
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
- var options = "--module commonjs -noImplicitAny";
+ var options = "--module commonjs --noImplicitAny --noEmitOnError";
// Keep comments when specifically requested
// or when in debug mode.
@@ -339,10 +341,10 @@ file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson],
complete();
});
ex.run();
-}, {async: true});
+}, {async: true});
desc("Generates a diagnostic file in TypeScript based on an input JSON file");
-task("generate-diagnostics", [diagnosticInfoMapTs]);
+task("generate-diagnostics", [diagnosticInfoMapTs]);
// Publish nightly
@@ -479,11 +481,11 @@ file(specMd, [word2mdJs, specWord], function () {
child_process.exec(cmd, function () {
complete();
});
-}, {async: true});
+}, {async: true});
desc("Generates a Markdown version of the Language Specification");
-task("generate-spec", [specMd]);
+task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
@@ -615,7 +617,7 @@ task("runtests", ["tests", builtLocalDirectory], function() {
exec(cmd, deleteTemporaryProjectOutput);
}, {async: true});
-desc("Generates code coverage data via instanbul");
+desc("Generates code coverage data via instanbul");
task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
console.log(cmd);
@@ -658,7 +660,7 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function(
function getDiffTool() {
var program = process.env['DIFF']
if (!program) {
- fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
+ fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
return program;
}
@@ -667,14 +669,14 @@ function getDiffTool() {
desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff', function () {
var cmd = '"' + getDiffTool() + '" ' + refBaseline + ' ' + localBaseline;
- console.log(cmd);
+ console.log(cmd);
exec(cmd);
}, {async: true});
desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff-rwc', function () {
var cmd = '"' + getDiffTool() + '" ' + refRwcBaseline + ' ' + localRwcBaseline;
- console.log(cmd);
+ console.log(cmd);
exec(cmd);
}, {async: true});
diff --git a/bin/tsc b/bin/tsc
index 3c0dab574f2..19c62bf7a00 100755
--- a/bin/tsc
+++ b/bin/tsc
@@ -1,2 +1,2 @@
#!/usr/bin/env node
-require('./tsc.js')
+require('../lib/tsc.js')
diff --git a/bin/tsserver b/bin/tsserver
old mode 100644
new mode 100755
index 003eb0d22af..7143b6a73ab
--- a/bin/tsserver
+++ b/bin/tsserver
@@ -1,2 +1,2 @@
#!/usr/bin/env node
-require('./tsserver.js')
+require('../lib/tsserver.js')
diff --git a/doc/TypeScript Language Specification (Change Markup).docx b/doc/TypeScript Language Specification (Change Markup).docx
index fd2688234c3..893f2e7ed22 100644
Binary files a/doc/TypeScript Language Specification (Change Markup).docx and b/doc/TypeScript Language Specification (Change Markup).docx differ
diff --git a/doc/TypeScript Language Specification (Change Markup).pdf b/doc/TypeScript Language Specification (Change Markup).pdf
index 7cb0009047b..1b4faab62e1 100644
Binary files a/doc/TypeScript Language Specification (Change Markup).pdf and b/doc/TypeScript Language Specification (Change Markup).pdf differ
diff --git a/doc/TypeScript Language Specification.docx b/doc/TypeScript Language Specification.docx
index 62604fa5bc4..4aaa3bf92fe 100644
Binary files a/doc/TypeScript Language Specification.docx and b/doc/TypeScript Language Specification.docx differ
diff --git a/doc/TypeScript Language Specification.pdf b/doc/TypeScript Language Specification.pdf
index e28d6f2d7f4..277fcecf2de 100644
Binary files a/doc/TypeScript Language Specification.pdf and b/doc/TypeScript Language Specification.pdf differ
diff --git a/doc/spec.md b/doc/spec.md
index cff436d5fc0..fe2147be477 100644
--- a/doc/spec.md
+++ b/doc/spec.md
@@ -1,12 +1,12 @@
# TypeScript Language Specification
-Version 1.5
+Version 1.6
-February, 2015
+August, 2015
-Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0.
+Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at [http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0](http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0).
TypeScript is a trademark of Microsoft Corporation.
@@ -24,10 +24,14 @@ TypeScript is a trademark of Microsoft Corporation.
* [1.7 Enum Types](#1.7)
* [1.8 Overloading on String Parameters](#1.8)
* [1.9 Generic Types and Functions](#1.9)
- * [1.10 Modules](#1.10)
+ * [1.10 Namespaces](#1.10)
+ * [1.11 Modules](#1.11)
* [2 Basic Concepts](#2)
* [2.1 Grammar Conventions](#2.1)
- * [2.2 Namespaces and Named Types](#2.2)
+ * [2.2 Names](#2.2)
+ * [2.2.1 Reserved Words](#2.2.1)
+ * [2.2.2 Property Names](#2.2.2)
+ * [2.2.3 Computed Property Names](#2.2.3)
* [2.3 Declarations](#2.3)
* [2.4 Scopes](#2.4)
* [3 Types](#3)
@@ -36,11 +40,12 @@ TypeScript is a trademark of Microsoft Corporation.
* [3.2.1 The Number Type](#3.2.1)
* [3.2.2 The Boolean Type](#3.2.2)
* [3.2.3 The String Type](#3.2.3)
- * [3.2.4 The Void Type](#3.2.4)
- * [3.2.5 The Null Type](#3.2.5)
- * [3.2.6 The Undefined Type](#3.2.6)
- * [3.2.7 Enum Types](#3.2.7)
- * [3.2.8 String Literal Types](#3.2.8)
+ * [3.2.4 The Symbol Type](#3.2.4)
+ * [3.2.5 The Void Type](#3.2.5)
+ * [3.2.6 The Null Type](#3.2.6)
+ * [3.2.7 The Undefined Type](#3.2.7)
+ * [3.2.8 Enum Types](#3.2.8)
+ * [3.2.9 String Literal Types](#3.2.9)
* [3.3 Object Types](#3.3)
* [3.3.1 Named Type References](#3.3.1)
* [3.3.2 Array Types](#3.3.2)
@@ -49,38 +54,40 @@ TypeScript is a trademark of Microsoft Corporation.
* [3.3.5 Constructor Types](#3.3.5)
* [3.3.6 Members](#3.3.6)
* [3.4 Union Types](#3.4)
- * [3.4.1 Contextual Union Types](#3.4.1)
- * [3.5 Type Parameters](#3.5)
- * [3.5.1 Type Parameter Lists](#3.5.1)
- * [3.5.2 Type Argument Lists](#3.5.2)
- * [3.6 Named Types](#3.6)
- * [3.6.1 Instance Types](#3.6.1)
- * [3.7 Specifying Types](#3.7)
- * [3.7.1 Predefined Types](#3.7.1)
- * [3.7.2 Type References](#3.7.2)
- * [3.7.3 Object Type Literals](#3.7.3)
- * [3.7.4 Array Type Literals](#3.7.4)
- * [3.7.5 Tuple Type Literals](#3.7.5)
- * [3.7.6 Union Type Literals](#3.7.6)
- * [3.7.7 Function Type Literals](#3.7.7)
- * [3.7.8 Constructor Type Literals](#3.7.8)
- * [3.7.9 Type Queries](#3.7.9)
- * [3.8 Specifying Members](#3.8)
- * [3.8.1 Property Signatures](#3.8.1)
- * [3.8.2 Call Signatures](#3.8.2)
- * [3.8.3 Construct Signatures](#3.8.3)
- * [3.8.4 Index Signatures](#3.8.4)
- * [3.8.5 Method Signatures](#3.8.5)
- * [3.9 Type Aliases](#3.9)
- * [3.10 Type Relationships](#3.10)
- * [3.10.1 Apparent Members](#3.10.1)
- * [3.10.2 Type and Member Identity](#3.10.2)
- * [3.10.3 Subtypes and Supertypes](#3.10.3)
- * [3.10.4 Assignment Compatibility](#3.10.4)
- * [3.10.5 Contextual Signature Instantiation](#3.10.5)
- * [3.10.6 Type Inference](#3.10.6)
- * [3.10.7 Recursive Types](#3.10.7)
- * [3.11 Widened Types](#3.11)
+ * [3.5 Intersection Types](#3.5)
+ * [3.6 Type Parameters](#3.6)
+ * [3.6.1 Type Parameter Lists](#3.6.1)
+ * [3.6.2 Type Argument Lists](#3.6.2)
+ * [3.7 Named Types](#3.7)
+ * [3.7.1 Instance Types](#3.7.1)
+ * [3.8 Specifying Types](#3.8)
+ * [3.8.1 Predefined Types](#3.8.1)
+ * [3.8.2 Type References](#3.8.2)
+ * [3.8.3 Object Type Literals](#3.8.3)
+ * [3.8.4 Array Type Literals](#3.8.4)
+ * [3.8.5 Tuple Type Literals](#3.8.5)
+ * [3.8.6 Union Type Literals](#3.8.6)
+ * [3.8.7 Intersection Type Literals](#3.8.7)
+ * [3.8.8 Function Type Literals](#3.8.8)
+ * [3.8.9 Constructor Type Literals](#3.8.9)
+ * [3.8.10 Type Queries](#3.8.10)
+ * [3.9 Specifying Members](#3.9)
+ * [3.9.1 Property Signatures](#3.9.1)
+ * [3.9.2 Call Signatures](#3.9.2)
+ * [3.9.3 Construct Signatures](#3.9.3)
+ * [3.9.4 Index Signatures](#3.9.4)
+ * [3.9.5 Method Signatures](#3.9.5)
+ * [3.10 Type Aliases](#3.10)
+ * [3.11 Type Relationships](#3.11)
+ * [3.11.1 Apparent Members](#3.11.1)
+ * [3.11.2 Type and Member Identity](#3.11.2)
+ * [3.11.3 Subtypes and Supertypes](#3.11.3)
+ * [3.11.4 Assignment Compatibility](#3.11.4)
+ * [3.11.5 Excess Properties](#3.11.5)
+ * [3.11.6 Contextual Signature Instantiation](#3.11.6)
+ * [3.11.7 Type Inference](#3.11.7)
+ * [3.11.8 Recursive Types](#3.11.8)
+ * [3.12 Widened Types](#3.12)
* [4 Expressions](#4)
* [4.1 Values and References](#4.1)
* [4.2 The this Keyword](#4.2)
@@ -88,57 +95,61 @@ TypeScript is a trademark of Microsoft Corporation.
* [4.4 Literals](#4.4)
* [4.5 Object Literals](#4.5)
* [4.6 Array Literals](#4.6)
- * [4.7 Parentheses](#4.7)
- * [4.8 The super Keyword](#4.8)
- * [4.8.1 Super Calls](#4.8.1)
- * [4.8.2 Super Property Access](#4.8.2)
- * [4.9 Function Expressions](#4.9)
- * [4.9.1 Standard Function Expressions](#4.9.1)
- * [4.9.2 Arrow Function Expressions](#4.9.2)
- * [4.9.3 Contextually Typed Function Expressions](#4.9.3)
- * [4.10 Property Access](#4.10)
- * [4.11 The new Operator](#4.11)
- * [4.12 Function Calls](#4.12)
- * [4.12.1 Overload Resolution](#4.12.1)
- * [4.12.2 Type Argument Inference](#4.12.2)
- * [4.12.3 Grammar Ambiguities](#4.12.3)
- * [4.13 Type Assertions](#4.13)
- * [4.14 Unary Operators](#4.14)
- * [4.14.1 The ++ and -- operators](#4.14.1)
- * [4.14.2 The +, –, and ~ operators](#4.14.2)
- * [4.14.3 The ! operator](#4.14.3)
- * [4.14.4 The delete Operator](#4.14.4)
- * [4.14.5 The void Operator](#4.14.5)
- * [4.14.6 The typeof Operator](#4.14.6)
- * [4.15 Binary Operators](#4.15)
- * [4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.15.1)
- * [4.15.2 The + operator](#4.15.2)
- * [4.15.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.15.3)
- * [4.15.4 The instanceof operator](#4.15.4)
- * [4.15.5 The in operator](#4.15.5)
- * [4.15.6 The && operator](#4.15.6)
- * [4.15.7 The || operator](#4.15.7)
- * [4.16 The Conditional Operator](#4.16)
- * [4.17 Assignment Operators](#4.17)
- * [4.17.1 Destructuring Assignment](#4.17.1)
- * [4.18 The Comma Operator](#4.18)
- * [4.19 Contextually Typed Expressions](#4.19)
- * [4.20 Type Guards](#4.20)
+ * [4.7 Template Literals](#4.7)
+ * [4.8 Parentheses](#4.8)
+ * [4.9 The super Keyword](#4.9)
+ * [4.9.1 Super Calls](#4.9.1)
+ * [4.9.2 Super Property Access](#4.9.2)
+ * [4.10 Function Expressions](#4.10)
+ * [4.11 Arrow Functions](#4.11)
+ * [4.12 Class Expressions](#4.12)
+ * [4.13 Property Access](#4.13)
+ * [4.14 The new Operator](#4.14)
+ * [4.15 Function Calls](#4.15)
+ * [4.15.1 Overload Resolution](#4.15.1)
+ * [4.15.2 Type Argument Inference](#4.15.2)
+ * [4.15.3 Grammar Ambiguities](#4.15.3)
+ * [4.16 Type Assertions](#4.16)
+ * [4.17 JSX Expressions](#4.17)
+ * [4.18 Unary Operators](#4.18)
+ * [4.18.1 The ++ and -- operators](#4.18.1)
+ * [4.18.2 The +, –, and ~ operators](#4.18.2)
+ * [4.18.3 The ! operator](#4.18.3)
+ * [4.18.4 The delete Operator](#4.18.4)
+ * [4.18.5 The void Operator](#4.18.5)
+ * [4.18.6 The typeof Operator](#4.18.6)
+ * [4.19 Binary Operators](#4.19)
+ * [4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators](#4.19.1)
+ * [4.19.2 The + operator](#4.19.2)
+ * [4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators](#4.19.3)
+ * [4.19.4 The instanceof operator](#4.19.4)
+ * [4.19.5 The in operator](#4.19.5)
+ * [4.19.6 The && operator](#4.19.6)
+ * [4.19.7 The || operator](#4.19.7)
+ * [4.20 The Conditional Operator](#4.20)
+ * [4.21 Assignment Operators](#4.21)
+ * [4.21.1 Destructuring Assignment](#4.21.1)
+ * [4.22 The Comma Operator](#4.22)
+ * [4.23 Contextually Typed Expressions](#4.23)
+ * [4.24 Type Guards](#4.24)
* [5 Statements](#5)
- * [5.1 Variable Statements](#5.1)
- * [5.1.1 Simple Variable Declarations](#5.1.1)
- * [5.1.2 Destructuring Variable Declarations](#5.1.2)
- * [5.1.3 Implied Type](#5.1.3)
- * [5.2 If, Do, and While Statements](#5.2)
- * [5.3 For Statements](#5.3)
- * [5.4 For-In Statements](#5.4)
- * [5.5 Continue Statements](#5.5)
- * [5.6 Break Statements](#5.6)
- * [5.7 Return Statements](#5.7)
- * [5.8 With Statements](#5.8)
- * [5.9 Switch Statements](#5.9)
- * [5.10 Throw Statements](#5.10)
- * [5.11 Try Statements](#5.11)
+ * [5.1 Blocks](#5.1)
+ * [5.2 Variable Statements](#5.2)
+ * [5.2.1 Simple Variable Declarations](#5.2.1)
+ * [5.2.2 Destructuring Variable Declarations](#5.2.2)
+ * [5.2.3 Implied Type](#5.2.3)
+ * [5.3 Let and Const Declarations](#5.3)
+ * [5.4 If, Do, and While Statements](#5.4)
+ * [5.5 For Statements](#5.5)
+ * [5.6 For-In Statements](#5.6)
+ * [5.7 For-Of Statements](#5.7)
+ * [5.8 Continue Statements](#5.8)
+ * [5.9 Break Statements](#5.9)
+ * [5.10 Return Statements](#5.10)
+ * [5.11 With Statements](#5.11)
+ * [5.12 Switch Statements](#5.12)
+ * [5.13 Throw Statements](#5.13)
+ * [5.14 Try Statements](#5.14)
* [6 Functions](#6)
* [6.1 Function Declarations](#6.1)
* [6.2 Function Overloads](#6.2)
@@ -146,6 +157,8 @@ TypeScript is a trademark of Microsoft Corporation.
* [6.4 Destructuring Parameter Declarations](#6.4)
* [6.5 Generic Functions](#6.5)
* [6.6 Code Generation](#6.6)
+ * [6.7 Generator Functions](#6.7)
+ * [6.8 Type Guard Functions](#6.8)
* [7 Interfaces](#7)
* [7.1 Interface Declarations](#7.1)
* [7.2 Declaration Merging](#7.2)
@@ -169,6 +182,7 @@ TypeScript is a trademark of Microsoft Corporation.
* [8.4.1 Member Variable Declarations](#8.4.1)
* [8.4.2 Member Function Declarations](#8.4.2)
* [8.4.3 Member Accessor Declarations](#8.4.3)
+ * [8.4.4 Dynamic Property Declarations](#8.4.4)
* [8.5 Index Member Declarations](#8.5)
* [8.6 Code Generation](#8.6)
* [8.6.1 Classes Without Extends Clauses](#8.6.1)
@@ -179,31 +193,33 @@ TypeScript is a trademark of Microsoft Corporation.
* [9.3 Declaration Merging](#9.3)
* [9.4 Constant Enum Declarations](#9.4)
* [9.5 Code Generation](#9.5)
-* [10 Internal Modules](#10)
- * [10.1 Module Declarations](#10.1)
- * [10.2 Module Body](#10.2)
- * [10.3 Import Declarations](#10.3)
+* [10 Namespaces](#10)
+ * [10.1 Namespace Declarations](#10.1)
+ * [10.2 Namespace Body](#10.2)
+ * [10.3 Import Alias Declarations](#10.3)
* [10.4 Export Declarations](#10.4)
* [10.5 Declaration Merging](#10.5)
* [10.6 Code Generation](#10.6)
-* [11 Source Files and External Modules](#11)
- * [11.1 Source Files](#11.1)
+* [11 Scripts and Modules](#11)
+ * [11.1 Programs and Source Files](#11.1)
* [11.1.1 Source Files Dependencies](#11.1.1)
- * [11.2 External Modules](#11.2)
- * [11.2.1 External Module Names](#11.2.1)
- * [11.2.2 External Import Declarations](#11.2.2)
- * [11.2.3 Export Declarations](#11.2.3)
- * [11.2.4 Export Assignments](#11.2.4)
- * [11.2.5 CommonJS Modules](#11.2.5)
- * [11.2.6 AMD Modules](#11.2.6)
+ * [11.2 Scripts](#11.2)
+ * [11.3 Modules](#11.3)
+ * [11.3.1 Module Names](#11.3.1)
+ * [11.3.2 Import Declarations](#11.3.2)
+ * [11.3.3 Import Require Declarations](#11.3.3)
+ * [11.3.4 Export Declarations](#11.3.4)
+ * [11.3.5 Export Assignments](#11.3.5)
+ * [11.3.6 CommonJS Modules](#11.3.6)
+ * [11.3.7 AMD Modules](#11.3.7)
* [12 Ambients](#12)
* [12.1 Ambient Declarations](#12.1)
* [12.1.1 Ambient Variable Declarations](#12.1.1)
* [12.1.2 Ambient Function Declarations](#12.1.2)
* [12.1.3 Ambient Class Declarations](#12.1.3)
* [12.1.4 Ambient Enum Declarations](#12.1.4)
- * [12.1.5 Ambient Module Declarations](#12.1.5)
- * [12.2 Ambient External Module Declarations](#12.2)
+ * [12.1.5 Ambient Namespace Declarations](#12.1.5)
+ * [12.2 Ambient Module Declarations](#12.2)
* [A Grammar](#A)
* [A.1 Types](#A.1)
* [A.2 Expressions](#A.2)
@@ -212,8 +228,8 @@ TypeScript is a trademark of Microsoft Corporation.
* [A.5 Interfaces](#A.5)
* [A.6 Classes](#A.6)
* [A.7 Enums](#A.7)
- * [A.8 Internal Modules](#A.8)
- * [A.9 Source Files and External Modules](#A.9)
+ * [A.8 Namespaces](#A.8)
+ * [A.9 Scripts and Modules](#A.9)
* [A.10 Ambients](#A.10)
@@ -222,9 +238,11 @@ TypeScript is a trademark of Microsoft Corporation.
JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring.
-TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of Ecmascript 5 (ES5) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development.
+TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 6 (ES6) 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.
-TypeScript syntax includes several proposed features of Ecmascript 6 (ES6), including classes and modules. Classes 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.
+TypeScript syntax includes all features of ECMAScript 6 (ES6), including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code.
+
+Classes 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.
TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables.
@@ -314,7 +332,7 @@ In this example, the second parameter to 'vote' has the function type
which means the second parameter is a function returning type 'any' that has a single parameter of type 'string' named 'result'.
-Section [3.8.2](#3.8.2) provides additional information about function types.
+Section [3.9.2](#3.9.2) provides additional information about function types.
## 1.3 Object Types
@@ -426,7 +444,7 @@ getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not match
```
-See section [3.10](#3.10) for more information about type comparisons.
+See section [3.11](#3.11) for more information about type comparisons.
## 1.5 Contextual Typing
@@ -452,13 +470,13 @@ $.get("http://mysite.org/divContent",
Contextual 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.
-Section [4.19](#4.19) provides additional information about contextually typed expressions.
+Section [4.23](#4.23) provides additional information about contextually typed expressions.
## 1.6 Classes
-JavaScript practice has at least two common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice.
+JavaScript practice has 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 6 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.)
-This section and the module section below will show how TypeScript emits consistent, idiomatic JavaScript code to implement classes and modules that are closely aligned with the current ES6 proposal. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or module unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class.
+This section and the 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.
```TypeScript
class BankAccount {
@@ -556,7 +574,7 @@ Section [8](#8) provides additional information about classes.
TypeScript 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.
```TypeScript
-enum Operator {
+const enum Operator {
ADD,
DIV,
MUL,
@@ -571,7 +589,7 @@ function compute(op: Operator, a: number, b: number) {
In this example, the compute function logs the operator 'op' using a feature of enum types: reverse mapping from the enum value ('op') to the string corresponding to that value. For example, the declaration of 'Operator' automatically assigns integers, starting from zero, to the listed enum members. Section [9](#9) describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member.
-If all enum members have explicitly assigned literal integers, or if an enum has all members automatically assigned, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member's assigned value (annotated with a comment). This improves performance on many JavaScript engines.
+When 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.
For example, the 'compute' function could contain a switch statement like the following.
@@ -622,7 +640,7 @@ In the following screen shot, a programming tool combines information from overl
/
-Section [3.8.2.4](#3.8.2.4) provides details on how to use string literals in function signatures.
+Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures.
## 1.9 Generic Types and Functions
@@ -686,13 +704,13 @@ class List {
}
```
-Section [3.6](#3.6) provides further information about generic types.
+Section [3.7](#3.7) provides further information about generic types.
-## 1.10 Modules
+## 1.10 Namespaces
Classes and interfaces support large-scale JavaScript development by providing a mechanism for describing how to use a software component that can be separated from that component's implementation. TypeScript enforces *encapsulation* of implementation in classes at design time (by restricting use of private and protected members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide *private names* which would enable runtime enforcement of private and protected members.
-In the current version of JavaScript, the only way to enforce encapsulation at runtime is to use the module pattern: encapsulate private fields and methods using closure variables. The module pattern is a natural way to provide organizational structure and dynamic loading options by drawing a boundary around a software component. A module can also provide the ability to introduce namespaces, avoiding use of the global namespace for most software components.
+In 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.
The following example illustrates the JavaScript module pattern.
@@ -710,12 +728,12 @@ This example illustrates the two essential elements of the module pattern: a *mo
The example assumes that an outer lexical scope defines the functions 'generateSecretKey' and 'sendSecureMessage'; it also assumes that the outer scope has assigned the module object to the variable 'MessageModule'.
-TypeScript modules provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting modules and classes within an outer module.
+TypeScript 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.
-The following example shows the definition and use of a simple module.
+The following example shows the definition and use of a simple namespace.
```TypeScript
-module M {
+namespace M {
var s = "hello";
export function f() {
return s;
@@ -726,7 +744,7 @@ M.f();
M.s; // Error, s is not exported
```
-In this example, variable 's' is a private feature of the module, but function 'f' is exported from the module and accessible to code outside of the module. If we were to describe the effect of module 'M' in terms of interfaces and variables, we would write
+In this example, variable 's' is a private feature of the 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
```TypeScript
interface M {
@@ -736,9 +754,9 @@ interface M {
var M: M;
```
-The interface 'M' summarizes the externally visible behavior of module 'M'. In this example, we can use the same name for the interface as for the initialized variable because in TypeScript type names and variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see section [2.3](#2.3) for more details).
+The interface 'M' summarizes the externally visible behavior of 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).
-Module 'M' is an example of an *internal* module, because it is nested within the *global* module (see section [10](#10) for more details). The TypeScript compiler emits the following JavaScript code for this module.
+The TypeScript compiler emits the following JavaScript code for the namespace:
```TypeScript
var M;
@@ -751,110 +769,200 @@ var M;
})(M || (M = {}));
```
-In this case, the compiler assumes that the module object resides in global variable 'M', which may or may not have been initialized to the desired module object.
+In this case, the compiler assumes that the namespace object resides in global variable 'M', which may or may not have been initialized to the desired namespace object.
-TypeScript also supports *external* modules, which are files that contain top-level *export* and *import *directives. For this type of module the TypeScript compiler will emit code whose module closure and module object implementation vary according to the specified dynamic loading system, for example, the Asynchronous Module Definition system.
+## 1.11 Modules
+
+TypeScript also supports ECMAScript 6 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 6 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).
# 2 Basic Concepts
-The 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 Language Specification (specifically, the ECMA-262 Standard, 5th 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.
+The 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 Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (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.
## 2.1 Grammar Conventions
The syntactic grammar added by TypeScript language is specified throughout this document using the existing conventions and production names of the ECMAScript grammar. In places where TypeScript augments an existing grammar production it is so noted. For example:
- *CallExpression:* *( Modified )*
+ *Declaration:* *( Modified )*
…
- `super` `(` *ArgumentListopt* `)`
- `super` `.` *IdentifierName*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production.
Similar to the ECMAScript grammar, if the phrase "*[no LineTerminator here]*" appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position.
-## 2.2 Namespaces and Named Types
+## 2.2 Names
-TypeScript supports ***named types*** that can be organized in hierarchical ***namespaces***. Namespaces are introduced by module declarations and named types are introduced by class, interface, and enum declarations. Named types are denoted by qualified names that extend from some root module (possibly the global module) to the point of their declaration. The example
+A 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
+
+* an *IdentifierName*,
+* a *StringLiteral* in a property name,
+* a *NumericLiteral* in a property name, or
+* a *ComputedPropertyName* that denotes a well-known symbol ([2.2.3](#2.2.3)).
+
+Most commonly, names are written to conform with the *Identifier* production, which is any *IdentifierName* that isn't a reserved word.
+
+### 2.2.1 Reserved Words
+
+The following keywords are reserved and cannot be used as an *Identifier*:
```TypeScript
-module X {
- export module Y {
- export interface Z { }
- }
- export interface Y { }
+break case catch class
+const continue debugger default
+delete do else enum
+export extends false finally
+for function if import
+in instanceof new null
+return super switch this
+throw true try typeof
+var void while with
+```
+
+The following keywords cannot be used as identifiers in strict mode code, but are otherwise not restricted:
+
+```TypeScript
+implements interface let package
+private protected public static
+yield
+```
+
+The following keywords cannot be used as user defined type names, but are otherwise not restricted:
+
+```TypeScript
+any boolean number string
+symbol
+```
+
+The following keywords have special meaning in certain contexts, but are valid identifiers:
+
+```TypeScript
+abstract as async await
+constructor declare from get
+is module namespace of
+require set type
+```
+
+### 2.2.2 Property Names
+
+The *PropertyName* production from the ECMAScript grammar is reproduced below:
+
+ *PropertyName:*
+ *LiteralPropertyName*
+ *ComputedPropertyName*
+
+ *LiteralPropertyName:*
+ *IdentifierName*
+ *StringLiteral*
+ *NumericLiteral*
+
+ *ComputedPropertyName:*
+ `[` *AssignmentExpression* `]`
+
+A 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.
+
+### 2.2.3 Computed Property Names
+
+ECMAScript 6 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
+
+```TypeScript
+[ Symbol . xxx ]
+```
+
+In 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.
+
+In 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)).
+
+Below is an example of an interface that declares a property with a well-known symbol name:
+
+```TypeScript
+interface Iterable {
+ [Symbol.iterator](): Iterator;
}
```
-declares two interface types with the qualified names 'X.Y.Z' and 'X.Y' relative to the root module in which 'X' is declared.
-
-In a qualified type name all identifiers but the last one refer to namespaces and the last identifier refers to a named type. Named type and namespace names are in separate declaration spaces and it is therefore possible for a named type and a namespace to have the same name, as in the example above.
-
-The hierarchy formed by namespace and named type names partially mirrors that formed by module instances and members. The example
-
-```TypeScript
-module A {
- export module B {
- export class C { }
- }
-}
-```
-
-introduces a named type with the qualified name 'A.B.C' and also introduces a constructor function that can be accessed using the expression 'A.B.C'. Thus, in the example
-
-```TypeScript
-var c: A.B.C = new A.B.C();
-```
-
-the two occurrences of 'A.B.C' in fact refer to different entities. It is the context of the occurrences that determines whether 'A.B.C' is processed as a type name or an expression.
-
## 2.3 Declarations
-Declarations introduce names in the ***declaration spaces*** to which they belong. It is an error to have two names with same spelling in the same declaration space. Declaration spaces exist as follows:
-
-* The global module and each external or internal module has a declaration space for variables (including functions, modules, class constructor functions, and enum objects), a declaration space for named types (classes, interfaces, and enums), and a declaration space for namespaces (containers of named types). Every declaration (whether local or exported) in a module contributes to one or more of these declaration spaces.
-* Each external or internal module has a declaration space for exported members, a declaration space for exported named types, and a declaration space for exported namespaces. All export declarations in the module contribute to these declaration spaces. Each internal module's export declaration spaces are shared with other internal modules that have the same root module and the same qualified name starting from that root module.
-* Each class declaration has a declaration space for instance members, a declaration space for static members, and a declaration space for type parameters.
-* Each interface declaration has a declaration space for members and a declaration space for type parameters. An interface's declaration space is shared with other interfaces that have the same root module and the same qualified name starting from that root module.
-* Each enum declaration has a declaration space for its enum members. An enum's declaration space is shared with other enums that have the same root module and the same qualified name starting from that root module.
-* Each function declaration (including constructor, member function, and member accessor declarations) and each function expression has a declaration space for locals (introduced by parameter, variable, and function declarations) and a declaration space for type parameters.
-* Each object literal has a declaration space for its properties.
-* Each object type literal has a declaration space for its members.
-
-Top-level declarations in a source file with no top-level import or export declarations belong to the ***global module***. Top-level declarations in a source file with one or more top-level import or export declarations belong to the ***external module*** represented by that source file.
-
-An internal module declaration contributes a namespace name (representing a container of types) and possibly a member name (representing the module instance) to the containing module. A class declaration contributes both a member name (representing the constructor function) and a type name (representing the class type) to the containing module. An interface declaration contributes a type name to the containing module. An enum declaration contributes both a member name (representing the enum object) and a type name (representing the enum type) to the containing module. Any other declaration contributes a member name to the declaration space to which it belongs.
-
-The ***parent module*** of an entity is defined as follows:
-
-* The parent module of an entity declared in an internal module is that internal module.
-* The parent module of an entity declared in an external module is that external module.
-* The parent module of an entity declared in the global module is the global module.
-* The parent module of an external module is the global module.
-
-The ***root module*** of an entity is defined as follows:
-
-* The root module of a non-exported entity is the entity's parent module.
-* The root module of an exported entity is the root module of the entity's parent module.
-
-Intuitively, the root module of an entity is the outermost module body from within which the entity is reachable.
-
-Interfaces, enums, and internal modules are "open ended," meaning that interface, enum, and internal module declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [7.2](#7.2), [9.3](#9.3), and [10.5](#10.5).
-
-Namespace, type, and member names exist in separate declaration spaces. Furthermore, declarations of non-instantiated modules (modules that contain only interfaces or modules at all levels of nesting) do not introduce a member name in their containing declaration space. This means that the following is permitted, provided module 'X' contains only interface or module declarations at all levels of nesting:
+Declarations 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:
```TypeScript
-module M {
- module X { ... } // Namespace
- interface X { ... } // Type
- var X; // Member
+var X: string; // Value named X
+
+type X = number; // Type named X
+
+namespace X { // Namespace named X
+ type Y = string;
}
```
-If module 'X' above was an instantiated module (section [10.1](#10.1)) it would cause a member 'X' to be introduced in 'M'. This member would conflict with the variable 'X' and thus cause an error.
+A 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 one the left hand side of a dot in a type reference.
-Instance and static members in a class are likewise in separate declaration spaces. Thus the following is permitted:
+When a name with multiple meanings is referenced, the context in which the reference occurs determines the meaning. For example:
+
+```TypeScript
+var n: X; // X references type
+var s: X.Y = X; // First X references namespace, second X references value
+```
+
+In 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.
+
+Declarations introduce the following meanings for the name they declare:
+
+* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning.
+* An interface, type alias, or type parameter declaration introduces a type meaning.
+* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class instance type).
+* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type).
+* 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).
+* An import or export declaration introduces the meaning(s) of the imported or exported entity.
+
+Below are some examples of declarations that introduce multiple meanings for a name:
+
+```TypeScript
+class C { // Value and type named C
+ x: string;
+}
+
+namespace N { // Value and namespace named N
+ export var x: string;
+}
+```
+
+Declaration spaces exist as follows:
+
+* The global namespace, each module, and each declared namespace has a declaration space for its contained entities (whether local or exported).
+* Each module has a declaration space for its exported entities. All export declarations in the module contribute to this declaration space.
+* 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.
+* Each class declaration has a declaration space for instance members and type parameters, and a declaration space for static members.
+* 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.
+* 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.
+* Each type alias declaration has a declaration space for its type parameters.
+* 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.
+* Each statement block has a declaration space for local let, const, class, interface, type alias, and enum declarations that occur immediately within that block.
+* Each object literal has a declaration space for its properties.
+* Each object type literal has a declaration space for its members.
+
+Top-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.
+
+The ***container*** of an entity is defined as follows:
+
+* The container of an entity declared in a namespace declaration is that namespace declaration.
+* The container of an entity declared in a module is that module.
+* The container of an entity declared in the global namespace is the global namespace.
+* The container of a module is the global namespace.
+
+The ***root container*** of an entity is defined as follows:
+
+* The root container of a non-exported entity is the entity’s container.
+* The root container of an exported entity is the root container of the entity's container.
+
+Intuitively, the root container of an entity is the outermost module or namespace body from within which the entity is reachable.
+
+Interfaces, 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).
+
+Instance and static members in a class are in separate declaration spaces. Thus the following is permitted:
```TypeScript
class C {
@@ -867,37 +975,41 @@ class C {
The ***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:
-* The scope of an entity declared in the global module is the entire program text.
-* The scope of an entity declared in an external module is the source file of that external module.
-* The scope of an exported entity declared in an internal module is the body of that module and every internal module with the same root and the same qualified name relative to that root.
-* The scope of a non-exported entity declared within an internal module declaration is the body of that internal module declaration.
-* The scope of a type parameter 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.
-* The scope of a member 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.
-* The scope of a type parameter 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.
-* The scope of a local entity (parameter, variable, or function) declared within a function declaration (including a constructor, member function, or member accessor declaration) or function expression is the body of that function declaration or function expression.
+* The scope of a name declared in the global namespace is the entire program text.
+* The scope of a name declared in a module is the source file of that module.
+* 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.
+* The scope of a non-exported name declared within a namespace declaration is the body of that namespace declaration.
+* 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.
+* The scope of a type parameter name declared in a type alias declaration is that entire type alias declaration.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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.
-Scopes may overlap, for example through nesting of modules and functions. When the scopes of two entities with the same name overlap, the entity with the innermost declaration takes precedence and access to the outer entity is either not possible or only possible by qualifying its name.
+Scopes 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.
-When an identifier is resolved as a *TypeName* (section [3.7.2](#3.7.2)), only classes, interfaces, enums, and type parameters are considered and other entities in scope are ignored.
+When 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.
-When an identifier is resolved as a *ModuleName* (section [3.7.2](#3.7.2)), only modules are considered and other entities in scope are ignored.
+When 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.
-When an identifier is resolved as a *PrimaryExpression* (section [4.3](#4.3)), only instantiated modules (section [10.1](#10.1)), classes, enums, functions, variables, and parameters are considered and other entities in scope are ignored.
+When 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.
-Note that class and enum members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class instance or enum object. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`.
+Note that class members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class 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`.
-As the rules above imply, locally declared entities in an internal module are closer in scope than exported entities declared in other module declarations for the same internal module. For example:
+As 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:
```TypeScript
var x = 1;
-module M {
+namespace M {
export var x = 2;
console.log(x); // 2
}
-module M {
+namespace M {
console.log(x); // 2
}
-module M {
+namespace M {
var x = 3;
console.log(x); // 3
}
@@ -909,15 +1021,15 @@ module M {
TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript's *static* compile-time type system closely models the *dynamic* run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript's type analysis occurs entirely at compile-time and adds no run-time overhead to program execution.
-All types in TypeScript are subtypes of a single top type called the Any type. The `any` keyword references this type. The Any type is the one type that can represent *any* JavaScript value with no constraints. All other types are categorized as ***primitive types***, ***object types***, ***union types***, or ***type parameters***. These types introduce various static constraints on their values.
+All types in TypeScript are subtypes of a single top type called the Any type. The `any` keyword references this type. The Any type is the one type that can represent *any* JavaScript value with no constraints. All other types are categorized as ***primitive types***, ***object types***, ***union types***, ***intersection types***, or ***type parameters***. These types introduce various static constraints on their values.
-The primitive types are the Number, Boolean, String, Void, Null, and Undefined types along with user defined enum types. The `number`, `boolean`, `string`, and `void` keywords reference the Number, Boolean, String, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only *values* of those types can be referenced, using the `null` and `undefined` literals.
+The primitive types are the Number, Boolean, String, 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.
The 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.
-Union types represent values that can have one of multiple types.
+Union types represent values that have one of multiple types, and intersection types represent values that simultaneously have more than one type.
-Declarations of modules, 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 module declaration associates the module with an anonymous type containing a set of properties corresponding to the exported variables and functions in the module, 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
+Declarations 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
```TypeScript
var x: number;
@@ -953,7 +1065,7 @@ function f(x) { // Same as f(x: any): void
## 3.2 Primitive Types
-The primitive types are the Number, Boolean, String, Void, Null, and Undefined types and all user defined enum types.
+The primitive types are the Number, Boolean, String, Symbol, Void, Null, and Undefined types and all user defined enum types.
### 3.2.1 The Number Type
@@ -961,7 +1073,7 @@ The Number primitive type corresponds to the similarly named JavaScript primitiv
The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type.
-For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'.
+For purposes of determining type relationships (section [3.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'.
Some examples:
@@ -978,7 +1090,7 @@ The Boolean primitive type corresponds to the similarly named JavaScript primiti
The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values.
-For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'.
+For purposes of determining type relationships (section [3.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'.
Some examples:
@@ -994,7 +1106,7 @@ The String primitive type corresponds to the similarly named JavaScript primitiv
The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type.
-For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'.
+For purposes of determining type relationships (section [3.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'.
Some examples:
@@ -1005,7 +1117,24 @@ var abc = 'abc'; // Same as abc: string = "abc"
var c = abc.charAt(2); // Property of String interface
```
-### 3.2.4 The Void Type
+### 3.2.4 The Symbol Type
+
+The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties.
+
+The `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 6 environments.
+
+For 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'.
+
+Some examples:
+
+```TypeScript
+var secretKey = Symbol();
+var obj = {};
+obj[secretKey] = "secret message"; // Use symbol as property key
+obj[Symbol.toStringTag] = "test"; // Use of well-known symbol
+```
+
+### 3.2.5 The Void Type
The 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.
@@ -1013,13 +1142,13 @@ The only possible values for the Void type are `null` and `undefined`. The Void
*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*.
-### 3.2.5 The Null Type
+### 3.2.6 The Null Type
The Null type corresponds to the similarly named JavaScript primitive type and is the type of the `null` literal.
The `null` literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself.
-The 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, and type parameters, including even the Number and Boolean primitive types.
+The 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.
Some examples:
@@ -1029,13 +1158,13 @@ var x = null; // Same as x: any = null
var e: Null; // Error, can't reference Null type
```
-### 3.2.6 The Undefined Type
+### 3.2.7 The Undefined Type
The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the `undefined` literal.
The `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.
-The 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, and type parameters.
+The 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.
Some examples:
@@ -1045,15 +1174,15 @@ var x = undefined; // Same as x: any = undefined
var e: Undefined; // Error, can't reference Undefined type
```
-### 3.2.7 Enum Types
+### 3.2.8 Enum Types
-Enum 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.7.2](#3.7.2)).
+Enum 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)).
Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other.
-### 3.2.8 String Literal Types
+### 3.2.9 String Literal Types
-Specialized signatures (section [3.8.2.4](#3.8.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.
+Specialized 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.
All string literal types are subtypes of the String primitive type.
@@ -1061,26 +1190,26 @@ All string literal types are subtypes of the String primitive type.
Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members.
-Class and interface type references, array types, tuple types, union types, function types, and constructor types are all classified as object types. Multiple constructs in the TypeScript language create object types, including:
+Class 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:
-* Object type literals (section [3.7.3](#3.7.3)).
-* Array type literals (section [3.7.4](#3.7.4)).
-* Tuple type literals (section [3.7.5](#3.7.5)).
-* Function type literals (section [3.7.7](#3.7.7)).
-* Constructor type literals (section [3.7.8](#3.7.8)).
+* Object type literals (section [3.8.3](#3.8.3)).
+* Array type literals (section [3.8.4](#3.8.4)).
+* Tuple type literals (section [3.8.5](#3.8.5)).
+* Function type literals (section [3.8.8](#3.8.8)).
+* Constructor type literals (section [3.8.9](#3.8.9)).
* Object literals (section [4.5](#4.5)).
* Array literals (section [4.6](#4.6)).
-* Function expressions (section [4.9](#4.9)) and function declarations ([6.1](#6.1)).
+* Function expressions (section [4.10](#4.10)) and function declarations ([6.1](#6.1)).
* Constructor function types created by class declarations (section [8.2.5](#8.2.5)).
-* Module instance types created by module declarations (section [10.3](#10.3)).
+* Namespace instance types created by namespace declarations (section [10.3](#10.3)).
### 3.3.1 Named Type References
-Type references (section [3.7.2](#3.7.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.
+Type 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.
### 3.3.2 Array Types
-***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type 'Array' in the global module with the array element type as a type argument. Array type literals (section [3.7.4](#3.7.4)) provide a shorthand notation for creating such references.
+***Array types*** represent JavaScript arrays with a common element type. Array types are named type references created from the generic interface type 'Array' in the global 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.
The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members:
@@ -1098,11 +1227,11 @@ Array literals (section [4.6](#4.6)) may be used to create values of array types
var a: string[] = ["hello", "world"];
```
-A type is said to be an ***array-like type*** if it is assignable (section [3.10.4](#3.10.4)) to the type `any[]`.
+A type is said to be an ***array-like type*** if it is assignable (section [3.11.4](#3.11.4)) to the type `any[]`.
### 3.3.3 Tuple Types
-***Tuple types*** represent JavaScript arrays with individually tracked element types. Tuple types are written using tuple type literals (section [3.7.5](#3.7.5)). A tuple type combines a set of numerically named properties with the members of an array type. Specifically, a tuple type
+***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
```TypeScript
[ T0, T1, ..., Tn ]
@@ -1143,11 +1272,11 @@ A type is said to be a ***tuple-like type*** if it has a property with the numer
### 3.3.4 Function Types
-An 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.7.7](#3.7.7)) or by including call signatures in object type literals.
+An 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.
### 3.3.5 Constructor Types
-An 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.7.8](#3.7.8)) or by including construct signatures in object type literals.
+An 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.
### 3.3.6 Members
@@ -1160,22 +1289,16 @@ Every object type is composed from zero or more of the following kinds of member
Properties are either ***public***, ***private***, or ***protected*** and are either ***required*** or ***optional***:
-* 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.10](#3.10). 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.10](#3.10).
-* 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.10.4](#3.10.4).
+* 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).
+* 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).
-Call and construct signatures may be ***specialized*** (section [3.8.2.4](#3.8.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.
+Call 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.
## 3.4 Union Types
-***Union types*** represent values that may have one of several disjoint representations. A value of a union type *A* | *B* is a value that is *either* of type *A* or type *B*. Union types are written using union type literals (section [3.7.6](#3.7.6)).
+***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)).
-A union type encompasses an unordered set of unrelated types (that is, types that aren't subtypes of each other). The following rules govern union types:
-
-* *A* | *B* is equivalent to *A* if *B* is a subtype of *A*.
-* *A* | *B* is equivalent to *B* | *A*.
-* *AB* | *C* is equivalent to *A* | *BC*, where *AB* is *A* | *B* and *BC* is *B* | *C*.
-
-Union types are reduced to the smallest possible set of constituent types using these rules.
+A 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.
Union types have the following subtype relationships:
@@ -1187,9 +1310,9 @@ Similarly, union types have the following assignability relationships:
* A union type *U* is assignable to a type *T* if each type in *U* is assignable to *T*.
* A type *T* is assignable to a union type *U* if *T* is assignable to any type in *U*.
-The || and conditional operators (section [4.15.7](#4.15.7) and [4.16](#4.16)) 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.
+The || 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.
-Type guards (section [4.20](#4.20)) 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.
+Type 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.
In the example
@@ -1209,7 +1332,7 @@ it is possible to assign 'x' a value of type `string`, `number`, or the union ty
var n = typeof x === "string" ? x.length : x; // Type of n is number
```
-For purposes of property access and function calls, the apparent members (section [3.10.1](#3.10.1)) of a union type *U* 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.
+For 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.
```TypeScript
interface A {
@@ -1231,25 +1354,71 @@ var c = x.c; // Error, no property c in union type
Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'A' has a property 'c'.
-### 3.4.1 Contextual Union Types
+When 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.
-When used as a contextual type (section [4.19](#4.19)), a union type *U* 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:
+## 3.5 Intersection Types
-* Let *S* be the set of types in *U* that has a property *P*. If *S* is not empty, *U* has a property *P* of a union type of the types of *P* from each type in *S*.
-* Let *S* be the set of types in *U* that have call signatures. If *S* is not empty and the sets of call signatures of the types in *S* are identical ignoring return types, *U* has the same set of call signatures, but with return types that are unions of the return types of the respective call signatures from each type in *S*.
-* Let *S* be the set of types in *U* that have construct signatures. If *S* is not empty and the sets of construct signatures of the types in *S* are identical ignoring return types, *U* has the same set of construct signatures, but with return types that are unions of the return types of the respective construct signatures from each type in *S*.
-* Let *S* be the set of types in *U* that has a string index signature. If *S* is not empty, *U* has a string index signature of a union type of the types of the string index signatures from each type in *S*.
-* Let *S* be the set of types in *U* that has a numeric index signature. If *S* is not empty, *U* has a numeric index signature of a union type of the types of the numeric index signatures from each type in *S*.
+***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)).
-## 3.5 Type Parameters
+An 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.
+
+Intersection types have the following subtype relationships:
+
+* An intersection type *I* is a subtype of a type *T* if any type in *I* is a subtype of *T*.
+* A type *T* is a subtype of an intersection type *I* if *T* is a subtype of each type in *I*.
+
+Similarly, intersection types have the following assignability relationships:
+
+* An intersection type *I* is assignable to a type *T* if any type in *I* is assignable to *T*.
+* A type *T* is assignable to an intersection type *I* if *T* is assignable to each type in *I*.
+
+For 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.
+
+```TypeScript
+interface A { a: number }
+interface B { b: number }
+
+var ab: A & B = { a: 1, b: 1 };
+var a: A = ab; // A & B assignable to A
+var b: B = ab; // A & B assignable to B
+
+interface X { p: A }
+interface Y { p: B }
+
+var xy: X & Y = { p: ab }; // X & Y has property p of type A & B
+
+type F1 = (a: string, b: string) => void;
+type F2 = (a: number, b: number) => void;
+
+var f: F1 & F2 = (a: string | number, b: string | number) => { };
+f("hello", "world"); // Ok
+f(1, 2); // Ok
+f(1, "test"); // Error
+```
+
+The union and intersection type operators can be applied to type parameters. This capability can for example be used to model functions that merge objects:
+
+```TypeScript
+function extend(first: T, second: U): T & U {
+ // Extend first with properties of second
+}
+
+var x = extend({ a: "hello" }, { b: 42 });
+var s = x.a;
+var n = x.b;
+```
+
+It 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.
+
+## 3.6 Type Parameters
A 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.
Since 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.
-### 3.5.1 Type Parameter Lists
+### 3.6.1 Type Parameter Lists
-Class, interface, 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.
+Class, 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.
*TypeParameters:*
`<` *TypeParameterList* `>`
@@ -1259,7 +1428,7 @@ Class, interface, and function declarations may optionally include lists of type
*TypeParameterList* `,` *TypeParameter*
*TypeParameter:*
- *Identifier* *Constraintopt*
+ *BindingIdentifier* *Constraintopt*
*Constraint:*
`extends` *Type*
@@ -1268,7 +1437,7 @@ Type parameter names must be unique. A compile-time error occurs if two or more
The 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.
-Each type parameter has an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Omitting a constraint corresponds to specifying the empty object type `{}`. Type parameters declared in a particular type parameter list may not be referenced in constraints in that type parameter list.
+Each type parameter has an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Omitting a constraint or specifying type `any` as the constraint corresponds to specifying the empty object type `{}`. Type parameters declared in a particular type parameter list may not be referenced in constraints in that type parameter list.
The ***base constraint*** of a type parameter *T* is defined as follows:
@@ -1286,11 +1455,11 @@ interface G {
the base constraint of 'T' is the empty object type, and the base constraint of 'U' and 'V' is 'Function'.
-For purposes of determining type relationships (section [3.10](#3.10)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)), type parameters appear to have the members of their base constraint, but no other members.
+For 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.
-### 3.5.2 Type Argument Lists
+### 3.6.2 Type Argument Lists
-A type reference (section [3.7.2](#3.7.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.12](#4.12)) to a generic function may explicitly include a type argument list instead of relying on type inference.
+A 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.
*TypeArguments:*
`<` *TypeArgumentList* `>`
@@ -1302,7 +1471,7 @@ A type reference (section [3.7.2](#3.7.2)) to a generic type must include a list
*TypeArgument:*
*Type*
-Type 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 is required to ***satisfy*** the constraint of its corresponding type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.10.4](#3.10.4)) the constraint type once type arguments are substituted for type parameters.
+Type 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 is required to ***satisfy*** the constraint of its corresponding 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.
Given the declaration
@@ -1314,13 +1483,13 @@ a type reference of the form 'G<A, B>' places no requirements on 'A' but requ
The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters.
-## 3.6 Named Types
+## 3.7 Named Types
-Classes, 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.9](#3.9)). Class and interface types may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***.
+Classes, 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***.
Interface declarations only introduce named types, whereas class declarations introduce named types *and* constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can't declare optional members and interfaces can't declare private or protected members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations.
-Named types are referenced through ***type references*** (section [3.7.2](#3.7.2)) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type.
+Named types are 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.
Named types are technically not types—only *references* to named types are. This distinction is particularly evident with generic types: Generic types are "templates" from which multiple *actual* types can be created by writing type references that supply type arguments to substitute in place of the generic type's type parameters. This substitution process is known as ***instantiating*** a generic type. Only once a generic type is instantiated does it denote an actual type.
@@ -1342,7 +1511,7 @@ is indistinguishable from the type
{ first: string; second: Entity; }
```
-### 3.6.1 Instance Types
+### 3.7.1 Instance Types
Each class and interface has an associated actual type known as the ***instance type***. For a non-generic class or interface, the instance type is simply a type reference to the class or interface. For a generic class or interface, the instance type is an instantiation of the generic type where each of the type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the class or interface. Within the constructor and instance member functions of a class, the type of `this` is the instance type of the class.
@@ -1357,18 +1526,22 @@ class G { // Introduce type parameter T
}
```
-## 3.7 Specifying Types
+## 3.8 Specifying Types
Types 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.
*Type:*
- *PrimaryOrUnionType*
+ *UnionOrIntersectionOrPrimaryType*
*FunctionType*
*ConstructorType*
- *PrimaryOrUnionType:*
- *PrimaryType*
- *UnionType*
+ *UnionOrIntersectionOrPrimaryType:*
+ *UnionType*
+ *IntersectionOrPrimaryType*
+
+ *IntersectionOrPrimaryType:*
+ *IntersectionType*
+ *PrimaryType*
*PrimaryType:*
*ParenthesizedType*
@@ -1382,29 +1555,31 @@ Types are specified either by referencing their keyword or name, or by writing o
*ParenthesizedType:*
`(` *Type* `)`
-Parentheses are required around union, function, or constructor types when they are used as array element types, and parentheses are required around function or constructor types in union types. For example:
+Parentheses 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:
```TypeScript
(string | number)[]
-((x: string) => string) | ((x: number) => number)
+((x: string) => string) | ((x: number) => number)
+(A | B) & (C | D)
```
The different forms of type notations are described in the following sections.
-### 3.7.1 Predefined Types
+### 3.8.1 Predefined Types
-The `any`, `number`, `boolean`, `string`, and `void` keywords reference the Any type and the Number, Boolean, String, and Void primitive types respectively.
+The `any`, `number`, `boolean`, `string`, `symbol` and `void` keywords reference the Any type and the Number, Boolean, String, Symbol, and Void primitive types respectively.
*PredefinedType:*
`any`
`number`
`boolean`
`string`
+ `symbol`
`void`
The predefined type keywords are reserved and cannot be used as names of user defined types.
-### 3.7.2 Type References
+### 3.8.2 Type References
A 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.
@@ -1412,24 +1587,26 @@ A type reference references a named type or type parameter through its name and,
*TypeName* *[no LineTerminator here]* *TypeArgumentsopt*
*TypeName:*
- *Identifier*
- *ModuleName* `.` *Identifier*
+ *IdentifierReference*
+ *NamespaceName* `.` *IdentifierReference*
- *ModuleName:*
- *Identifier*
- *ModuleName* `.` *Identifier*
+ *NamespaceName:*
+ *IdentifierReference*
+ *NamespaceName* `.` *IdentifierReference*
-A *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.5.2](#3.5.2)).
+A *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)).
+
+A *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.
Resolution of a *TypeName* consisting of a single identifier is described in section [2.4](#2.4).
-Resolution of a *TypeName* of the form *M.N*, where *M* is a *ModuleName* and *N* is an *Identifier*, proceeds by first resolving the module name *M*. If the resolution of *M* is successful and the resulting module contains an exported named type *N*, then *M.N* refers to that member. Otherwise, *M.N* is undefined.
+Resolution 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.
-Resolution of a *ModuleName* consisting of a single identifier is described in section [2.4](#2.4).
+Resolution 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.
-Resolution of a *ModuleName* of the form *M.N*, where *M* is a *ModuleName* and *N* is an *Identifier*, proceeds by first resolving the module name *M*. If the resolution of *M* is successful and the resulting module contains an exported module member *N*, then *M.N* refers to that member. Otherwise, *M.N* is undefined.
+Resolution 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.
-A 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.10.4](#3.10.4)) the constraint of the corresponding type parameter or otherwise an error occurs. An example:
+A 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:
```TypeScript
interface A { a: string; }
@@ -1454,7 +1631,7 @@ var v7: G; // Error, no arguments
A type argument is simply a *Type* and may itself be a type reference to a generic type, as demonstrated by 'v4' in the example above.
-As described in section [3.6](#3.6), a type reference to a generic type *G* designates a type wherein all occurrences of *G*'s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of 'v1' above is equivalent to:
+As described in section [3.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:
```TypeScript
var v1: {
@@ -1463,7 +1640,7 @@ var v1: {
};
```
-### 3.7.3 Object Type Literals
+### 3.8.3 Object Type Literals
An 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.
@@ -1471,11 +1648,13 @@ An object type literal defines an object type by specifying the set of members t
`{` *TypeBodyopt* `}`
*TypeBody:*
- *TypeMemberList* `;`*opt*
+ *TypeMemberList* `;`*opt*
+ *TypeMemberList* `,`*opt*
*TypeMemberList:*
*TypeMember*
- *TypeMemberList* `;` *TypeMember*
+ *TypeMemberList* `;` *TypeMember*
+ *TypeMemberList* `,` *TypeMember*
*TypeMember:*
*PropertySignature*
@@ -1484,18 +1663,18 @@ An object type literal defines an object type by specifying the set of members t
*IndexSignature*
*MethodSignature*
-The 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.8](#3.8).
+The 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).
-### 3.7.4 Array Type Literals
+### 3.8.4 Array Type Literals
An array type literal is written as an element type followed by an open and close square bracket.
*ArrayType:*
*PrimaryType* *[no LineTerminator here]* `[` `]`
-An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type 'Array' in the global module with the element type as a type argument.
+An array type literal references an array type (section [3.3.2](#3.3.2)) with the given element type. An array type literal is simply shorthand notation for a reference to the generic interface type 'Array' in the global namespace with the element type as a type argument.
-When union, function, or constructor types are used as array element types they must be enclosed in parentheses. For example:
+When union, intersection, function, or constructor types are used as array element types they must be enclosed in parentheses. For example:
```TypeScript
(string | number)[]
@@ -1509,7 +1688,7 @@ Array
Array<() => string>
```
-### 3.7.5 Tuple Type Literals
+### 3.8.5 Tuple Type Literals
A tuple type literal is written as a sequence of element types, separated by commas and enclosed in square brackets.
@@ -1525,28 +1704,25 @@ A tuple type literal is written as a sequence of element types, separated by com
A tuple type literal references a tuple type (section [3.3.3](#3.3.3)).
-### 3.7.6 Union Type Literals
+### 3.8.6 Union Type Literals
A union type literal is written as a sequence of types separated by vertical bars.
*UnionType:*
- *PrimaryOrUnionType* `|` *PrimaryType*
+ *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType*
A union typle literal references a union type (section [3.4](#3.4)).
-When function or constructor types are included in union types they must be enclosed in parentheses. For example:
+### 3.8.7 Intersection Type Literals
-```TypeScript
-((x: string) => string) | ((x: number) => number)
-```
+An intersection type literal is written as a sequence of types separated by ampersands.
-Alternatively, function or constructor types in union types can be written using object literals:
+ *IntersectionType:*
+ *IntersectionOrPrimaryType* `&` *PrimaryType*
-```TypeScript
-{ (x: string): string } | { (x: number): number }
-```
+An intersection typle literal references an intersection type (section [3.5](#3.5)).
-### 3.7.7 Function Type Literals
+### 3.8.8 Function Type Literals
A function type literal specifies the type parameters, regular parameters, and return type of a call signature.
@@ -1567,7 +1743,7 @@ is exactly equivalent to the object type literal
Note 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.
-### 3.7.8 Constructor Type Literals
+### 3.8.9 Constructor Type Literals
A constructor type literal specifies the type parameters, regular parameters, and return type of a construct signature.
@@ -1588,7 +1764,7 @@ is exactly equivalent to the object type literal
Note that constructor types with multiple construct signatures cannot be written as constructor type literals but must instead be written as object type literals.
-### 3.7.9 Type Queries
+### 3.8.10 Type Queries
A type query obtains the type of an expression.
@@ -1596,12 +1772,12 @@ A type query obtains the type of an expression.
`typeof` *TypeQueryExpression*
*TypeQueryExpression:*
- *Identifier*
+ *IdentifierReference*
*TypeQueryExpression* `.` *IdentifierName*
-A 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.10](#4.10)), the widened type (section [3.11](#3.11)) 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.
+A 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.
-Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and module declarations. For example:
+Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and namespace declarations. For example:
```TypeScript
var a = { x: 10, y: 20 };
@@ -1628,48 +1804,44 @@ var h: () => typeof h;
Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type.
-## 3.8 Specifying Members
+## 3.9 Specifying Members
-The members of an object type literal (section [3.7.3](#3.7.3)) are specified as a combination of property, call, construct, index, and method signatures.
+The 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.
-### 3.8.1 Property Signatures
+### 3.9.1 Property Signatures
A property signature declares the name and type of a property member.
*PropertySignature:*
*PropertyName* `?`*opt* *TypeAnnotationopt*
- *PropertyName:*
- *IdentifierName*
- *StringLiteral*
- *NumericLiteral*
+ *TypeAnnotation:*
+ `:` *Type*
-The *PropertyName* production, reproduced above from the ECMAScript grammar, permits a property name to be any identifier (including a reserved word), a string literal, or a numeric literal. String literals can 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.
-
-The *PropertyName* of a property signature must be unique within its containing type. If the property name is followed by a question mark, the property is optional. Otherwise, the property is required.
+The *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.
If a property signature omits a *TypeAnnotation*, the Any type is assumed.
-### 3.8.2 Call Signatures
+### 3.9.2 Call Signatures
-A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section [4.12](#4.12)) to an instance of the containing type. A type may ***overload*** call operations by defining multiple different call signatures.
+A 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.
*CallSignature:*
*TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt*
-A call signature that includes *TypeParameters* (section [3.5.1](#3.5.1)) is called a ***generic call signature***. Conversely, a call signature with no *TypeParameters* is called a non-generic call signature.
+A 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.
-As well as being members of object type literals, call signatures occur in method signatures (section [3.8.5](#3.8.5)), function expressions (section [4.9](#4.9)), and function declarations (section [6.1](#6.1)).
+As 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)).
An object type containing call signatures is said to be a ***function type***.
-#### 3.8.2.1 Type Parameters
+#### 3.9.2.1 Type Parameters
-Type parameters (section [3.5.1](#3.5.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.
+Type 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.
Type 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.
-Type arguments (section [3.5.2](#3.5.2)) for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section [4.12.2](#4.12.2)) from the types of the regular arguments in the call. 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.
+Type 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.
Some examples of call signatures with type parameters follow below.
@@ -1697,7 +1869,7 @@ A function taking an array of one type and a function argument, returning an arr
(a: T[], f: (x: T) => U): U[]
```
-#### 3.8.2.2 Parameter List
+#### 3.9.2.2 Parameter List
A signature's parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter.
@@ -1715,16 +1887,16 @@ A signature's parameter list consists of zero or more required parameters, follo
*RequiredParameterList* `,` *RequiredParameter*
*RequiredParameter:*
- *AccessibilityModifieropt* *IdentifierOrPattern* *TypeAnnotationopt*
- *Identifier* `:` *StringLiteral*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt*
+ *BindingIdentifier* `:` *StringLiteral*
*AccessibilityModifier:*
`public`
`private`
`protected`
- *IdentifierOrPattern:*
- *Identifier*
+ *BindingIdentifierOrPattern:*
+ *BindingIdentifier*
*BindingPattern*
*OptionalParameterList:*
@@ -1732,20 +1904,20 @@ A signature's parameter list consists of zero or more required parameters, follo
*OptionalParameterList* `,` *OptionalParameter*
*OptionalParameter:*
- *AccessibilityModifieropt* *IdentifierOrPattern* `?` *TypeAnnotationopt*
- *AccessibilityModifieropt* *IdentifierOrPattern* *TypeAnnotationopt* *Initialiser*
- *Identifier* `?` `:` *StringLiteral*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer*
+ *BindingIdentifier* `?` `:` *StringLiteral*
*RestParameter:*
- `...` *Identifier* *TypeAnnotationopt*
+ `...` *BindingIdentifier* *TypeAnnotationopt*
-A parameter declaration may specify either an identifier or a binding pattern ([5.1.2](#5.1.2)). The identifiers specified in parameter declarations and binding patterns in a parameter list must be unique within that parameter list.
+A 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.
The type of a parameter in a signature is determined as follows:
* If the declaration includes a type annotation, the parameter is of that type.
-* 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.11](#3.11)) of the type of the initializer expression.
-* Otherwise, if the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section [5.1.3](#5.1.3)).
+* 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.
+* 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)).
* Otherwise, if the parameter is a rest parameter, the parameter type is `any[]`.
* Otherwise, the parameter type is `any`.
@@ -1753,11 +1925,13 @@ A parameter is permitted to include a `public`, `private`, or `protected` modifi
A type annotation for a rest parameter must denote an array type.
-When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.8.2.4](#3.8.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.
+When 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.
A 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.
-#### 3.8.2.3 Return Type
+*TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*.
+
+#### 3.9.2.3 Return Type
If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value.
@@ -1765,9 +1939,9 @@ When a call signature with no return type annotation occurs in a context without
When 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).
-#### 3.8.2.4 Specialized Signatures
+#### 3.9.2.4 Specialized Signatures
-When a parameter type annotation specifies a string literal type (section [3.2.8](#3.2.8)), 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
+When 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
```TypeScript
interface Document {
@@ -1780,13 +1954,13 @@ interface Document {
states that calls to 'createElement' with the string literals "div", "span", and "canvas" return values of type 'HTMLDivElement', 'HTMLSpanElement', and 'HTMLCanvasElement' respectively, and that calls with all other string expressions return values of type 'HTMLElement'.
-When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section [4.12.1](#4.12.1)) processes the candidates in declaration order and picks the first one that matches.
+When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section [4.15.1](#4.15.1)) processes the candidates in declaration order and picks the first one that matches.
Every specialized call or construct signature in an object type must be assignable to at least one non-specialized call or construct signature in the same object type (where a call signature *A* is considered assignable to another call signature *B* if an object type containing only *A* would be assignable to an object type containing only *B*). For example, the 'createElement' property in the example above is of a type that contains three specialized signatures, all of which are assignable to the non-specialized signature in the type.
-### 3.8.3 Construct Signatures
+### 3.9.3 Construct Signatures
-A construct signature defines the parameter list and return type associated with applying the `new` operator (section [4.11](#4.11)) to an instance of the containing type. A type may overload `new` operations by defining multiple construct signatures with different parameter lists.
+A 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.
*ConstructSignature:*
`new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt*
@@ -1795,33 +1969,33 @@ The type parameters, parameter list, and return type of a construct signature ar
A type containing construct signatures is said to be a ***constructor type***.
-### 3.8.4 Index Signatures
+### 3.9.4 Index Signatures
An index signature defines a type constraint for properties in the containing type.
*IndexSignature:*
- `[` *Identifier* `:` `string` `]` *TypeAnnotation*
- `[` *Identifier* `:` `number` `]` *TypeAnnotation*
+ `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation*
+ `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation*
There are two kinds of index signatures:
* ***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*.
* ***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*.
-A ***numerically named property*** is a property whose name is a valid numeric literal. Specifically, a property with a name *N* for which ToNumber(*N*) is not NaN, where ToNumber is the abstract operation defined in ECMAScript specification.
+A ***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.
An object type can contain at most one string index signature and one numeric index signature.
-Index 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.10](#4.10).
+Index 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).
-### 3.8.5 Method Signatures
+### 3.9.5 Method Signatures
A method signature is shorthand for declaring a property of a function type.
*MethodSignature:*
*PropertyName* `?`*opt* *CallSignature*
-If the identifier 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.
+If 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.
A method signature of the form
@@ -1878,24 +2052,26 @@ the properties 'func1', 'func2', and 'func3' are all of the same type, namely an
the properties 'func4' and 'func5' are of the same type, namely an object type with two call signatures taking and returning number and string respectively.
-## 3.9 Type Aliases
+## 3.10 Type Aliases
-A type alias declaration introduces a ***type alias*** in the containing module.
+A type alias declaration introduces a ***type alias*** in the containing declaration space.
*TypeAliasDeclaration:*
- `type` *Identifier* `=` *Type* `;`
+ `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;`
-A 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 types and union types.
+A 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.
-Type aliases are referenced using type references ([3.7.2](#3.7.2)). Writing a reference to a type alias has ***exactly*** the same effect as writing the aliased type itself.
+A 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*.
-The *Identifier* of a type alias declaration may not be one of the predefined type names (section [3.7.1](#3.7.1)).
+Type 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.
+
+The *BindingIdentifier* of a type alias declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)).
It is an error for the type specified in a type alias to depend on that type alias. Types have the following dependencies:
* A type alias *directly depends on* the type it aliases.
* A type reference *directly depends on* the referenced type and each of the type arguments, if any.
-* A union type *directly depends on* each of the constituent types.
+* A union or intersection type *directly depends on* each of the constituent types.
* An array type *directly depends on* its element type.
* A tuple type *directly depends on* each of its element types.
* A type query *directly depends on* the type of the referenced entity.
@@ -1907,11 +2083,12 @@ Some examples of type alias declarations:
```TypeScript
type StringOrNumber = string | number;
type Text = string | { text: string };
-type Coordinates = [number, number];
type NameLookup = Dictionary;
-type Callback = (data: string) => void;
-type RecFunc = () => RecFunc;
-type ObjectStatics = typeof Object;
+type ObjectStatics = typeof Object;
+type Callback = (data: T) => void;
+type Pair = [T, T];
+type Coordinates = Pair;
+type Tree = T | { left: Tree, right: Tree };
```
Interface 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
@@ -1936,29 +2113,34 @@ However, doing so means the following capabilities are lost:
* An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
* An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
-* An interface can have type parameters, but a type alias for an object type literal cannot.
-## 3.10 Type Relationships
+## 3.11 Type Relationships
Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections.
-### 3.10.1 Apparent Members
+### 3.11.1 Apparent Members
-The ***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.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)). The apparent members of a type are determined as follows:
+The ***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:
* The apparent members of the primitive types Number, Boolean, and String are the apparent members of the global interface types 'Number', 'Boolean', and 'String' respectively.
* The apparent members of an enum type are the apparent members of the global interface type 'Number'.
-* The apparent members of a type parameter are the apparent members of the base constraint (section [3.5.1](#3.5.1)) of that type parameter.
+* 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.
* The apparent members of an object type *T* are the combination of the following:
* The declared and/or inherited members of *T*.
* The properties of the global interface type 'Object' that aren't hidden by properties with the same name in *T*.
* 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*.
* The apparent members of a union type *U* are determined as follows:
- * If each type in *U* has an apparent property *P*, *U* has an apparent property *P* of a union type of the types of *P* from each type in *U*.
- * If each type in *U* has apparent call signatures and the sets of apparent call signatures are identical ignoring return types, *U* has the same set of call signatures, but with return types that are unions of the return types of the respective apparent call signatures from each type in *U*.
- * If each type in *U* has apparent construct signatures and the sets of apparent construct signatures are identical ignoring return types, *U* has the same set of construct signatures, but with return types that are unions of the return types of the respective apparent construct signatures from each type in *U*.
- * If each type in *U* has an apparent string index signature, *U* has a string index signature of a union type of the types of the apparent string index signatures from each type in *U*.
- * If each type in *U* has an apparent numeric index signature, *U* has a numeric index signature of a union type of the types of the apparent numeric index signatures from each type in *U*.
+ * 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.
+ * 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.
+ * 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.
+ * 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.
+ * 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.
+* The apparent members of an intersection type *I* are determined as follows:
+ * 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.
+ * 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*.
+ * 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*.
+ * 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.
+ * 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.
If a type is not one of the above, it is considered to have no apparent members.
@@ -1974,7 +2156,7 @@ var err: Object = { toString: 0 }; // Error
The last assignment is an error because the object literal has a 'toString' method that isn't compatible with that of 'Object'.
-### 3.10.2 Type and Member Identity
+### 3.11.2 Type and Member Identity
Two types are considered ***identical*** when
@@ -1982,6 +2164,7 @@ Two types are considered ***identical*** when
* they are the same primitive type,
* they are the same type parameter,
* they are union types with identical sets of constituent types, or
+* they are intersection types with identical sets of constituent types, or
* they are object types with identical sets of members.
Two members are considered identical when
@@ -2011,9 +2194,9 @@ var b: C;
the variables 'a' and 'b' are of identical types because the two type references to 'C' create types with a private member 'x' that originates in the same declaration, and because the two private 'x' members have types with identical sets of members once the type arguments 'X' and 'Y' are substituted.
-### 3.10.3 Subtypes and Supertypes
+### 3.11.3 Subtypes and Supertypes
-*S* is a ***subtype*** of a type *T*, and *T* is a ***supertype*** of *S*, if one of the following is true:
+*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:
* *S* and *T* are identical types.
* *T* is the Any type.
@@ -2021,10 +2204,12 @@ the variables 'a' and 'b' are of identical types because the two type references
* *S* is the Null type and *T* is not the Undefined type.
* *S* is an enum type and *T* is the primitive type Number.
* *S* is a string literal type and *T* is the primitive type String.
-* *S* and *T* are type parameters, and *S* is directly or indirectly constrained to *T*.
* *S* is a union type and each constituent type of *S* is a subtype of *T*.
+* *S* is an intersection type and at least one constituent type of *S* is a subtype of *T*.
* *T* is a union type and *S* is a subtype of at least one constituent type of *T*.
-* *S* is an object type, a type parameter, 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:
+* *T* is an intersection type and *S* is a subtype of each constituent type of *T*.
+* *S* is a type parameter and the constraint of *S* is a subtype of *T*.
+* *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:
* *M* is a property and *S* has an apparent property *N* where
* *M* and *N* have the same name,
* the type of *N* is a subtype of that of *M*,
@@ -2035,20 +2220,20 @@ the variables 'a' and 'b' are of identical types because the two type references
* *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*,
* for parameter positions that are present in both signatures, each parameter type in *N* is a subtype or supertype of the corresponding parameter type in *M*, and
* the result type of *M* is Void, or the result type of *N* is a subtype of that of *M*.
- * *M* is a string index signature of type *U* and *S* has an apparent string index signature of a type that is a subtype of *U*.
- * *M* is a numeric index signature of type *U* and *S* has an apparent string or numeric index signature of a type that is a subtype of *U*.
+ * *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*.
+ * *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*.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
-Note that specialized call and construct signatures (section [3.8.2.4](#3.8.2.4)) are not significant when determining subtype and supertype relationships.
+Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining subtype and supertype relationships.
Also 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*.
-### 3.10.4 Assignment Compatibility
+### 3.11.4 Assignment Compatibility
Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls.
-*S* is ***assignable to*** a type *T*, and *T* is ***assignable from*** *S*, if one of the following is true:
+*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:
* *S* and *T* are identical types.
* *S* or *T* is the Any type.
@@ -2056,10 +2241,12 @@ Types are required to be assignment compatible in certain circumstances, such as
* *S* is the Null type and *T* is not the Undefined type.
* *S* or *T* is an enum type and* *the other is the primitive type Number.
* *S* is a string literal type and *T* is the primitive type String.
-* *S* and *T* are type parameters, and *S* is directly or indirectly constrained to *T*.
* *S* is a union type and each constituent type of *S* is assignable to *T*.
+* *S* is an intersection type and at least one constituent type of *S* is assignable to *T*.
* *T* is a union type and *S* is assignable to at least one constituent type of *T*.
-* *S* is an object type, a type parameter, 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:
+* *T* is an intersection type and *S* is assignable to each constituent type of *T*.
+* *S* is a type parameter and the constraint of *S* is assignable to *T*.
+* *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:
* *M* is a property and *S* has an apparent property *N* where
* *M* and *N* have the same name,
* the type of *N* is assignable to that of *M*,
@@ -2076,7 +2263,7 @@ Types are required to be assignment compatible in certain circumstances, such as
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
-Note that specialized call and construct signatures (section [3.8.2.4](#3.8.2.4)) are not significant when determining assignment compatibility.
+Note that specialized call and construct signatures (section [3.9.2.4](#3.9.2.4)) are not significant when determining assignment compatibility.
The assignment compatibility and subtyping rules differ only in that
@@ -2095,23 +2282,80 @@ foo({ id: 1234, name: false }); // Error, name of wrong type
foo({ name: "hello" }); // Error, id required but missing
```
-### 3.10.5 Contextual Signature Instantiation
+### 3.11.5 Excess Properties
-During type argument inference in a function call (section [4.12.2](#4.12.2)) it is in certain circumstances necessary to instantiate a generic call signature of an argument expression in the context of a non-generic call signature of a parameter such that further inferences can be made. A generic call signature *A* is ***instantiated in the context of*** non-generic call signature *B* as follows:
+The 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.
-* Using the process described in [3.10.6](#3.10.6), inferences for *A*'s type parameters are made from each parameter type in *B* to the corresponding parameter type in *A* for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
+A source type *S* is considered to have excess properties with respect to a target type *T* if
+
+* *S* is a fresh object literal type, as defined below, and
+* *S* has one or more properties that aren't expected in *T*.
+
+A property *P* is said to be expected in a type *T* if one of the following is true:
+
+* *T* is not an object, union, or intersection type.
+* *T* is an object type and
+ * *T* has a property with the same name as *P*,
+ * *T* has a string or numeric index signature,
+ * *T* has no properties, or
+ * *T* is the global type 'Object'.
+* *T* is a union or intersection type and *P* is expected in at least one of the constituent types of *T*.
+
+The 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)).
+
+Consider the following example:
+
+```TypeScript
+interface CompilerOptions {
+ strict?: boolean;
+ sourcePath?: string;
+ targetPath?: string;
+}
+
+var options: CompilerOptions = {
+ strict: true,
+ sourcepath: "./src", // Error, excess or misspelled property
+ targetpath: "./bin" // Error, excess or misspelled property
+};
+```
+
+The '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).
+
+In cases where excess properties are expected, an index signature can be added to the target type as an indicator of intent:
+
+```TypeScript
+interface InputElement {
+ name: string;
+ visible?: boolean;
+ [x: string]: any; // Allow additional properties of any type
+}
+
+var address: InputElement = {
+ name: "Address",
+ visible: true,
+ help: "Enter address here", // Allowed because of index signature
+ shortcut: "Alt-A" // Allowed because of index signature
+};
+```
+
+### 3.11.6 Contextual Signature Instantiation
+
+During 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:
+
+* 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.
* The inferred type argument for each type parameter is the union type of the set of inferences made for that type parameter. However, if the union type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint.
-### 3.10.6 Type Inference
+### 3.11.7 Type Inference
In 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:
* If *T* is one of the type parameters for which inferences are being made, *S* is added to the set of inferences for that type parameter.
* Otherwise, if *S* and *T* are references to the same generic type, inferences are made from each type argument in *S* to each corresponding type argument in *T*.
-* Otherwise, if *T* is a union type:
+* 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*.
+* Otherwise, if *T* is a union or intersection type:
* First, inferences are made from *S* to each constituent type in *T* that isn't simply one of the type parameters for which inferences are being made.
- * If the first step produced no inferences and exactly one constituent type in *T* is simply a type parameter for which inferences are being made, inferences are made from *S* to that type parameter.
-* Otherwise, if *S* is a union type, inferences are made from each constituent type in *S* to *T*.
+ * 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.
+* Otherwise, if *S* is a union or intersection type, inferences are made from each constituent type in *S* to *T*.
* Otherwise, if *S* and *T* are object types, then for each member *M* in *T*:
* 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*.
* 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*.
@@ -2122,7 +2366,7 @@ In certain contexts, inferences for a given set of type parameters are made *fro
When 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.
-### 3.10.7 Recursive Types
+### 3.11.8 Recursive Types
Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type
@@ -2156,7 +2400,7 @@ interface List {
'List<T>' has a member 'owner' of type 'List<List<T>>', which has a member 'owner' of type 'List<List<List<T>>>', which has a member 'owner' of type 'List<List<List<List<T>>>>' and so on, ad infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to their full depth, in order to determine type relationships involving infinitely expanding generic types it may be necessary for the compiler to terminate the recursion at some point with the assumption that no further exploration will change the outcome.
-## 3.11 Widened Types
+## 3.12 Widened Types
In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example
@@ -2171,7 +2415,7 @@ The following example shows the results of widening types to produce inferred va
```TypeScript
var a = null; // var a: any
var b = undefined; // var b: any
-var c = { x: 0, y: null }; // var c: { x: number, y: any }
+var c = { x: 0, y: null }; // var c: { x: number, y: any }
var d = [ null, undefined ]; // var d: any[]
```
@@ -2185,17 +2429,15 @@ TypeScript's typing rules define a type for every expression construct. For exam
In addition to type inference and type checking, TypeScript augments JavaScript expressions with the following constructs:
-* Optional parameter and return type annotations in function expressions.
-* Default parameter values and rest parameters in function expressions.
-* Arrow function expressions.
-* Super calls and member access.
+* Optional parameter and return type annotations in function expressions and arrow functions.
+* Type arguments in function calls.
* Type assertions.
Unless otherwise noted in the sections that follow, TypeScript expressions and the JavaScript expressions generated from them are identical.
## 4.1 Values and References
-Expressions 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.7](#4.7)), and property accesses (section [4.10](#4.10)). All other expression constructs described in this chapter are classified as values.
+Expressions 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.
## 4.2 The this Keyword
@@ -2203,18 +2445,18 @@ The type of `this` in an expression depends on the location in which the referen
* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the class instance type of the containing class.
* In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class.
-* In a function declaration or a standard function expression, `this` is of type Any.
-* In the global module, `this` is of type Any.
+* In a function declaration or a function expression, `this` is of type Any.
+* In the global namespace, `this` is of type Any.
In all other contexts it is a compile-time error to reference `this`.
-In the body of an arrow function expression, references to `this` are rewritten in the generated JavaScript code, as described in section [4.9.2](#4.9.2).
+Note that an arrow function (section [4.11](#4.11)) has no `this` parameter but rather preserves the `this` of its enclosing context.
## 4.3 Identifiers
-When an expression is an *Identifier*, the expression refers to the most nested module, 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:
+When 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:
-* For a module, the object type associated with the module instance.
+* For a namespace, the object type associated with the namespace instance.
* For a class, the constructor type associated with the constructor function object.
* For an enum, the object type associated with the enum object.
* For a function, the function type associated with the function object.
@@ -2235,9 +2477,11 @@ Literals are typed as follows:
## 4.5 Object Literals
-Object literals are extended to support type annotations in get and set accessors.
+Object literals are extended to support type annotations in methods and get and set accessors.
- *PropertyAssignment:* *( Modified )*
+ *PropertyDefinition:* *( Modified )*
+ *IdentifierReference*
+ *CoverInitializedName*
*PropertyName* `:` *AssignmentExpression*
*PropertyName* *CallSignature* `{` *FunctionBody* `}`
*GetAccessor*
@@ -2247,17 +2491,29 @@ Object literals are extended to support type annotations in get and set accessor
`get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}`
*SetAccessor:*
- `set` *PropertyName* `(` *Identifier* *TypeAnnotationopt* `)` `{` *FunctionBody* `}`
+ `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}`
The 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.
-A property assignment of the form
+A shorthand property assignment of the form
+
+```TypeScript
+prop
+```
+
+is equivalent to
+
+```TypeScript
+prop : prop
+```
+
+Likewise, a property assignment of the form
```TypeScript
f ( ... ) { ... }
```
-is simply shorthand for
+is equivalent to
```TypeScript
f : function ( ... ) { ... }
@@ -2280,20 +2536,15 @@ A get accessor declaration is processed in the same manner as an ordinary functi
If 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.
-When 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.8.4](#3.8.4)) declared in the object literal, or the Undefined type if the object literal declares no numerically named properties.
+When 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.
-## 4.6 Array Literals
+If 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:
-Array literals are extended to support the spread (`...`) operator.
+* A dynamic property assignment does not introduce a property in the type of the object literal.
+* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type.
+* 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.
- *ElementList:* *( Modified )*
- *Elisionopt* *AssignmentExpression*
- *Elisionopt* *SpreadElement*
- *ElementList* `,` *Elisionopt* *AssignmentExpression*
- *ElementList* `,` *Elisionopt* *SpreadElement*
-
- *SpreadElement:*
- `...` *AssignmentExpression*
+## 4.6 Array Literals
An array literal
@@ -2305,7 +2556,7 @@ denotes a value of an array type (section [3.3.2](#3.3.2)) or a tuple type (sect
Each element expression in a non-empty array literal is processed as follows:
-* If the array literal contains no spread elements, and if the array literal is contextually typed (section [4.19](#4.19)) 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.
+* 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.
* 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.
* Otherwise, the element expression is not contextually typed.
@@ -2313,11 +2564,13 @@ The resulting type an array literal expression is determined as follows:
* If the array literal is empty, the resulting type is an array type with the element type Undefined.
* Otherwise, if the array literal 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.
-* Otherwise, if the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section [4.17.1](#4.17.1)), the resulting type is a tuple type constructed from the types of the element expressions.
+* 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.
* 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.
A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs.
+*TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*.
+
The 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
```TypeScript
@@ -2340,7 +2593,11 @@ var a = [2, 3, 4];
var b = [0, 1].concat(a, [5, 6]);
```
-## 4.7 Parentheses
+## 4.7 Template Literals
+
+*TODO: [Template literals](https://github.com/Microsoft/TypeScript/pull/960)*.
+
+## 4.8 Parentheses
A parenthesized expression
@@ -2350,72 +2607,78 @@ A parenthesized expression
has 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.
-## 4.8 The super Keyword
+## 4.9 The super Keyword
The `super` keyword can be used in expressions to reference base class properties and the base class constructor.
- *CallExpression:* *( Modified )*
- …
- `super` `(` *ArgumentListopt* `)`
- `super` `.` *IdentifierName*
-
-### 4.8.1 Super Calls
+### 4.9.1 Super Calls
Super 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).
-A 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.12](#4.12)) 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.
+A 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.
The type of a super call expression is Void.
The JavaScript code generated for a super call is specified in section [8.6.2](#8.6.2).
-### 4.8.2 Super Property Access
+### 4.9.2 Super Property Access
A 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:
* 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.
* 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.
-Super 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 standard function expressions nested in the above constructs because `this` is of type Any in such function expressions.
+Super 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.
Super 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).
The JavaScript code generated for a super property access is specified in section [8.6.2](#8.6.2).
-## 4.9 Function Expressions
+*TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*.
-Function expressions are extended from JavaScript to optionally include parameter and return type annotations, and a new compact form, called arrow function expressions, is introduced.
+## 4.10 Function Expressions
+
+Function expressions are extended from JavaScript to optionally include parameter and return type annotations.
*FunctionExpression:* *( Modified )*
- `function` *Identifieropt* *CallSignature* `{` *FunctionBody* `}`
+ `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}`
- *AssignmentExpression:* *( Modified )*
- …
- *ArrowFunctionExpression*
-
- *ArrowFunctionExpression:*
- *ArrowFormalParameters* `=>` *Block*
- *ArrowFormalParameters* `=>` *AssignmentExpression*
-
- *ArrowFormalParameters:*
- *CallSignature*
- *Identifier*
-
-The terms ***standard function expression*** and ***arrow function expression*** are used to refer to the *FunctionExpression* and *ArrowFunctionExpression* forms respectively. When referring to either, the generic term ***function expression*** is used.
+The descriptions of function declarations provided in chapter [6](#6) apply to function expressions as well, except that function expressions do not support overloading.
The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression's signature and body.
-The descriptions of function declarations provided in section [6.1](#6.1) apply to function expressions as well, except that function expressions do not support overloading.
+When 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.
-### 4.9.1 Standard Function Expressions
+Likewise, 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*.
-Standard function expressions are function expressions written with the `function` keyword. The type of `this` in a standard function expression is the Any type.
+A contextual signature *S* is extracted from a function type *T* as follows:
-Standard function expressions are transformed to JavaScript in the same manner as function declarations (see section [6.6](#6.6)).
+* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature.
+* 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.
+* Otherwise, no contextual signature can be extracted from *T*.
-### 4.9.2 Arrow Function Expressions
+In the example
-TypeScript supports ***arrow function expressions***, a new feature planned for ECMAScript 6. Arrow function expressions are a compact form of function expressions that omit the `function` keyword and have lexical scoping of `this`.
+```TypeScript
+var f: (s: string) => string = function (s) {
+ return s.toLowerCase();
+};
+```
+
+the 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.
+
+## 4.11 Arrow Functions
+
+Arrow functions are extended from JavaScript to optionally include parameter and return type annotations.
+
+ *ArrowFormalParameters:* *( Modified )*
+ *CallSignature*
+
+The descriptions of function declarations provided in chapter [6](#6) apply to arrow functions as well, except that arrow functions do not support overloading.
+
+The 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.
+
+When 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*.
An arrow function expression of the form
@@ -2452,7 +2715,7 @@ x => { return Math.sin(x); }
x => Math.sin(x)
```
-A function expression using the `function` keyword 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`.
+A 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`.
In the example
@@ -2497,27 +2760,11 @@ could be parsed as an arrow function expression with a type parameter or a type
< T > ( ( ... ) => { ... } )
```
-### 4.9.3 Contextually Typed Function Expressions
+## 4.12 Class Expressions
-When a function expression with no type parameters and no parameter type annotations is contextually typed (section [4.19](#4.19)) 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.
+*TODO: Document [class expressions](https://github.com/Microsoft/TypeScript/issues/497)*.
-Likewise, when a function expression with no return type annotation is contextually typed (section [4.19](#4.19)) by a function type *T* and a contextual signature *S* can be extracted from *T*, expressions in contained return statements (section [5.7](#5.7)) are contextually typed by the return type of *S*.
-
-A contextual signature *S* is extracted from a function type *T* as follows:
-
-* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature.
-* 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.
-* Otherwise, no contextual signature can be extracted from *T* and *S* is undefined.
-
-In the example
-
-```TypeScript
-var f: (s: string) => string = s => s.toLowerCase();
-```
-
-the 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.
-
-## 4.10 Property Access
+## 4.13 Property Access
A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference.
@@ -2530,7 +2777,7 @@ object . name
where *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:
* If *object* is of type Any, any *name* is permitted and the property access is of type Any.
-* Otherwise, if *name* denotes an accessible apparent property (section [3.10.1](#3.10.1)) in the type 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).
+* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the type 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).
* Otherwise, the property access is invalid and a compile-time error occurs.
A bracket notation property access of the form
@@ -2541,12 +2788,14 @@ object [ index ]
where *object* and *index* are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time:
-* If *index* is a string literal or a numeric literal and *object* has an apparent property (section [3.10.1](#3.10.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.
+* 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.
* 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.
* 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.
* Otherwise, if *index* is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.
* Otherwise, the property access is invalid and a compile-time error occurs.
+*TODO: Indexing with [symbols](https://github.com/Microsoft/TypeScript/pull/1978)*.
+
The rules above mean that properties are strongly typed when accessed using bracket notation with the literal representation of their name. For example:
```TypeScript
@@ -2567,7 +2816,7 @@ var s = data[0]; // string
var n = data[1]; // number
```
-## 4.11 The new Operator
+## 4.14 The new Operator
A `new` operation has one of the following forms:
@@ -2580,12 +2829,12 @@ new C < ... > ( ... )
where *C* is an expression. The first form is equivalent to supplying an empty argument list. *C* must be of type Any or of an object type with one or more construct or call signatures. The operation is processed as follows at compile-time:
* If *C* is of type Any, any argument list is permitted and the result of the operation is of type Any.
-* If *C* has one or more apparent construct signatures (section [3.10.1](#3.10.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.
+* 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.
* 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.
-## 4.12 Function Calls
+## 4.15 Function Calls
-Function calls are extended from JavaScript to optionally include type arguments.
+Function calls are extended from JavaScript to support optional type arguments.
*Arguments:* *( Modified )*
*TypeArgumentsopt* `(` *ArgumentListopt* `)`
@@ -2597,16 +2846,18 @@ func ( ... )
func < ... > ( ... )
```
-where *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.5.2](#3.5.2)) and an argument list.
+where *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.
If *func* is of type Any, or of an object type that has no call or construct signatures but is a subtype of the Function interface, the call is an ***untyped function call***. In an untyped function call no type arguments are permitted, argument expressions can be of any type and number, no contextual types are provided for the argument expressions, and the result is always of type Any.
-If *func* has apparent call signatures (section [3.10.1](#3.10.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.
+If *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.
-### 4.12.1 Overload Resolution
+### 4.15.1 Overload Resolution
The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn't support function overloading, all that matters at run-time is the name of the function.
+*TODO: Describe use of [wildcard function types](https://github.com/Microsoft/TypeScript/issues/3970) in overload resolution*.
+
The compile-time processing of a typed function call consists of the following steps:
* 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.
@@ -2614,7 +2865,7 @@ The compile-time processing of a typed function call consists of the following s
* the function call has no type arguments, and
* the signature is applicable with respect to the argument list of the function call.
* A generic signature is a candidate in a function call without type arguments when
- * type inference (section [4.12.2](#4.12.2)) succeeds for each type parameter,
+ * type inference (section [4.15.2](#4.15.2)) succeeds for each type parameter,
* 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.
* A generic signature is a candidate in a function call with type arguments when
* The signature has the same number of type parameters as were supplied in the type argument list,
@@ -2628,12 +2879,16 @@ A signature is said to be an ***applicable signature*** with respect to an argum
* the number of arguments is not less than the number of required parameters,
* the number of arguments is not greater than the number of parameters, and
-* for each argument expression *e* and its corresponding parameter *P,* when *e* is contextually typed (section [4.19](#4.19)) by the type of *P*, no errors ensue and the type of *e* is assignable to (section [3.10.4](#3.10.4)) the type of *P*.
+* 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*.
-### 4.12.2 Type Argument Inference
+*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*.
+
+### 4.15.2 Type Argument Inference
Given a signature < *T1* , *T2* , … , *Tn* > ( *p1* : *P1* , *p2* : *P2* , … , *pm* : *Pm* ), where each parameter type *P* references zero or more of the type parameters *T*, and an argument list ( *e1* , *e2* , … , *em* ), the task of type argument inference is to find a set of type arguments *A1*…*An* to substitute for *T1*…*Tn* such that the argument list becomes an applicable signature.
+*TODO: Update [type argument inference and overload resolution rules](https://github.com/Microsoft/TypeScript/issues/1186)*.
+
Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows:
* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint.
@@ -2643,13 +2898,13 @@ Type argument inference produces a set of candidate types for each type paramete
In order to compute candidate types, the argument list is processed as follows:
* Initially all inferred type arguments are considered ***unfixed*** with an empty set of candidate types.
-* 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.10.6](#3.10.6)) are made for unfixed inferred type arguments from the type computed for *e* to *P*.
+* 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*.
The 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:
* Where expressions contained within *e* would be contextually typed, they are instead inferentially typed.
-* When a function expression is inferentially typed (section [4.9.3](#4.9.3)) and a type assigned to a parameter in that expression references type parameters for which inferences are being made, the corresponding inferred type arguments to become ***fixed*** and no further candidate inferences are made for them.
-* If *e* is an expression of a function type that contains exactly one generic call signature and no other members, and *T* is a function type with exactly one non-generic call signature and no other members, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are ***fixed***, and *e*'s type is changed to a function type with *e*'s call signature instantiated in the context of *T*'s call signature (section [3.10.5](#3.10.5)).
+* 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.
+* 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)).
An example:
@@ -2715,9 +2970,9 @@ var pairs = zip(
and the resulting type of 'pairs' is therefore '{ name: string; age: number }[]'.
-### 4.12.3 Grammar Ambiguities
+### 4.15.3 Grammar Ambiguities
-The inclusion of type arguments in the *Arguments* production (section [4.12](#4.12)) gives rise to certain ambiguities in the grammar for expressions. For example, the statement
+The 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
```TypeScript
f(g(7));
@@ -2736,7 +2991,7 @@ f(g < A, B > +(7));
are both interpreted as calls to 'f' with two arguments.
-## 4.13 Type Assertions
+## 4.16 Type Assertions
TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression:
@@ -2746,7 +3001,7 @@ TypeScript extends the JavaScript expression grammar with the ability to assert
A type assertion expression consists of a type enclosed in `<` and `>` followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are *not* checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing `<` and `>` are simply removed from the generated code.
-In a type assertion expression of the form < *T* > *e*, *e* is contextually typed (section [4.19](#4.19)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*.
+In 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*.
Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren't *known* to be correct. In the example
@@ -2775,15 +3030,19 @@ if (shape instanceof Circle) {
}
```
-## 4.14 Unary Operators
+## 4.17 JSX Expressions
+
+*TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*.
+
+## 4.18 Unary Operators
The 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.
-### 4.14.1 The ++ and -- operators
+### 4.18.1 The ++ and -- operators
These operators, in prefix or postfix form, require their operand to be of type Any, the Number primitive type, or an enum type, and classified as a reference (section [4.1](#4.1)). They produce a result of the Number primitive type.
-### 4.14.2 The +, –, and ~ operators
+### 4.18.2 The +, –, and ~ operators
These operators permit their operand to be of any type and produce a result of the Number primitive type.
@@ -2797,7 +3056,7 @@ var n = +getValue();
The example above converts the result of 'getValue()' to a number if it isn't a number already. The type inferred for 'n' is the Number primitive type regardless of the return type of 'getValue'.
-### 4.14.3 The ! operator
+### 4.18.3 The ! operator
The ! operator permits its operand to be of any type and produces a result of the Boolean primitive type.
@@ -2811,17 +3070,17 @@ var b = !!getValue();
The example above converts the result of 'getValue()' to a Boolean if it isn't a Boolean already. The type inferred for 'b' is the Boolean primitive type regardless of the return type of 'getValue'.
-### 4.14.4 The delete Operator
+### 4.18.4 The delete Operator
The 'delete' operator takes an operand of any type and produces a result of the Boolean primitive type.
-### 4.14.5 The void Operator
+### 4.18.5 The void Operator
-The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.6](#3.2.6)).
+The 'void' operator takes an operand of any type and produces the value 'undefined'. The type of the result is the Undefined type ([3.2.7](#3.2.7)).
-### 4.14.6 The typeof Operator
+### 4.18.6 The typeof Operator
-The 'typeof' operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, 'typeof' can also be used in a type query (section [3.7.9](#3.7.9)) to produce the type of an expression.
+The 'typeof' operator takes an operand of any type and produces a value of the String primitive type. In positions where a type is expected, 'typeof' can also be used in a type query (section [3.8.10](#3.8.10)) to produce the type of an expression.
```TypeScript
var x = 5;
@@ -2831,11 +3090,11 @@ var z: typeof x; // Use in a type query
In the example above, 'x' is of type 'number', 'y' is of type 'string' because when used in an expression, 'typeof' produces a value of type string (in this case the string "number"), and 'z' is of type 'number' because when used in a type query, 'typeof' obtains the type of an expression.
-## 4.15 Binary Operators
+## 4.19 Binary Operators
The subsections that follow specify the compile-time processing rules of the binary operators. In general, if the operands of a binary operator do not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type any in further processing. Tables that summarize the compile-time processing rules for operands of the Any type, the Boolean, Number, and String primitive types, and all other types (the Other column in the tables) are provided.
-### 4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators
+### 4.19.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators
These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. The result is always of the Number primitive type.
@@ -2847,7 +3106,7 @@ These operators require their operands to be of type Any, the Number primitive t
|String||||||
|Other||||||
-### 4.15.2 The + operator
+### 4.19.2 The + operator
The 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.
@@ -2869,7 +3128,7 @@ var s = getValue() + "";
The example above converts the result of 'getValue()' to a string if it isn't a string already. The type inferred for 's' is the String primitive type regardless of the return type of 'getValue'.
-### 4.15.3 The <, >, <=, >=, ==, !=, ===, and !== operators
+### 4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators
These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type.
@@ -2881,17 +3140,17 @@ These operators require one or both of the operand types to be assignable to the
|String|Boolean|||Boolean||
|Other|Boolean||||Boolean|
-### 4.15.4 The instanceof operator
+### 4.19.4 The instanceof operator
The `instanceof` operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.
Note that object types containing one or more call or construct signatures are automatically subtypes of the 'Function' interface type, as described in section [3.3](#3.3).
-### 4.15.5 The in operator
+### 4.19.5 The in operator
The `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.
-### 4.15.6 The && operator
+### 4.19.6 The && operator
The && operator permits the operands to be of any type and produces a result of the same type as the second operand.
@@ -2903,11 +3162,11 @@ The && operator permits the operands to be of any type and produces a result of
|String|Any|Boolean|Number|String|Other|
|Other|Any|Boolean|Number|String|Other|
-### 4.15.7 The || operator
+### 4.19.7 The || operator
The || operator permits the operands to be of any type.
-If the || expression is contextually typed (section [4.19](#4.19)), 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.
+If 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.
The type of the result is the union type of the two operand types.
@@ -2919,7 +3178,7 @@ The type of the result is the union type of the two operand types.
|String|Any|S | B|S | N|String|S | O|
|Other|Any|B | O|N | O|S | O|Other|
-## 4.16 The Conditional Operator
+## 4.20 The Conditional Operator
In a conditional expression of the form
@@ -2929,11 +3188,11 @@ test ? expr1 : expr2
the *test* expression may be of any type.
-If the conditional expression is contextually typed (section [4.19](#4.19)), *expr1* and *expr2* are contextually typed by the same type. Otherwise, *expr1* and *expr2* are not contextually typed.
+If 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.
The type of the result is the union type of the types of *expr1* and *expr2*.
-## 4.17 Assignment Operators
+## 4.21 Assignment Operators
An assignment of the form
@@ -2941,7 +3200,7 @@ An assignment of the form
v = expr
```
-requires *v* to be classified as a reference (section [4.1](#4.1)) or as an assignment pattern (section [4.17.1](#4.17.1)). The *expr* expression is contextually typed (section [4.19](#4.19)) by the type of *v*, and the type of *expr* must be assignable to (section [3.10.4](#3.10.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*.
+requires *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*.
A compound assignment of the form
@@ -2957,42 +3216,9 @@ where ??= is one of the compound assignment operators
is 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.
-### 4.17.1 Destructuring Assignment
+### 4.21.1 Destructuring Assignment
-A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern.
-
- *AssignmentPattern:*
- *ObjectAssignmentPattern*
- *ArrayAssignmentPattern*
-
- *ObjectBindingPattern:*
- `{` `}`
- `{` *AssignmentPropertyList* `,`*opt* `}`
-
- *AssignmentPropertyList:*
- *AssignmentProperty*
- *AssignmentPropertyList* `,` *AssignmentProperty*
-
- *AssignmentProperty:*
- *Identifier* *Initialiseropt*
- *PropertyName* `:` *LeftHandSideExpression* *Initialiseropt*
- *PropertyName* `:` *AssignmentPattern* *Initialiseropt*
-
- *ArrayAssignmentPattern:*
- `[` *Elisionopt* *AssignmentRestElementopt* `]`
- `[` *AssignmentElementList* `]`
- `[` *AssignmentElementList* `,` *Elisionopt* *AssignmentRestElementopt* `]`
-
- *AssignmentElementList:*
- *Elisionopt* *AssignmentElement*
- *AssignmentElementList* `,` *Elisionopt* *AssignmentElement*
-
- *AssignmentElement:*
- *LeftHandSideExpression* *Initialiseropt*
- *AssignmentPattern* *Initialiseropt*
-
- *AssignmentRestElement:*
- `...` *LeftHandSideExpression*
+A ***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 6 specification.
In 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:
@@ -3009,9 +3235,7 @@ In a destructuring assignment expression, the type of the expression on the righ
In 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.
-When the output target is ECMAScript 6 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
+When the output target is ECMAScript 6 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
```TypeScript
var x = 1;
@@ -3028,18 +3252,18 @@ _a = [y, x], x = _a[0], y = _a[1];
var _a;
```
-## 4.18 The Comma Operator
+## 4.22 The Comma Operator
The comma operator permits the operands to be of any type and produces a result that is of the same type as the second operand.
-## 4.19 Contextually Typed Expressions
+## 4.23 Contextually Typed Expressions
Type 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:
* In a variable, parameter, binding property, binding element, or member declaration, an initializer expression is contextually typed by
* the type given in the declaration's type annotation, if any, or otherwise
- * for a parameter, the contextual type for the declaration (section [4.9.3](#4.9.3)), if any, or otherwise
- * the type implied by the binding pattern in the declaration (section [5.1.3](#5.1.3)), if any.
+ * for a parameter, the type provided by a contextual signature (section [4.10](#4.10)), if any, or otherwise
+ * the type implied by the binding pattern in the declaration (section [5.2.3](#5.2.3)), if any.
* 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.
* 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.
* In the body of a constructor declaration, return expressions are contextually typed by the containing class type.
@@ -3083,7 +3307,7 @@ setEventHandlers({
the object literal passed to 'setEventHandlers' is contextually typed to the 'EventHandlers' type. This causes the two property assignments to be contextually typed to the unnamed function type '(event: EventObject) => void', which in turn causes the 'e' parameters in the arrow function expressions to automatically be typed as 'EventObject'.
-## 4.20 Type Guards
+## 4.24 Type Guards
Type guards are particular expression patterns involving the 'typeof' and 'instanceof' operators that cause the types of variables or parameters to be ***narrowed*** to more specific types. For example, in the code below, knowledge of the static type of 'x' in combination with a 'typeof' check makes it safe to narrow the type of 'x' to string in the first branch of the 'if' statement and number in the second branch of the 'if' statement.
@@ -3100,12 +3324,12 @@ function foo(x: number | string) {
The type of a variable or parameter is narrowed in the following situations:
-* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided the true branch statement contains no assignments to the variable or parameter.
-* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided the false branch statement contains no assignments to the variable or parameter.
-* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when true*, provided the true expression contains no assignments to the variable or parameter.
-* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when false*, provided the false expression contains no assignments to the variable or parameter.
-* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when true*, provided the right operand contains no assignments to the variable or parameter.
-* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when false*, provided the right operand contains no assignments to the variable or parameter.
+* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided no part of the 'if' statement contains assignments to the variable or parameter.
+* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided no part of the 'if' statement contains assignments to the variable or parameter.
+* 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.
+* 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.
+* 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.
+* 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.
A type guard is simply an expression that follows a particular pattern. The process of narrowing the type of a variable *x* by a type guard *when true* or *when false* depends on the type guard as follows:
@@ -3198,17 +3422,29 @@ function getName(obj: Object) {
}
```
-the type of `obj` is narrowed to `NamedItem` in the first condtional expression, and the inferred type of the `getName` function is `string`.
+the type of `obj` is narrowed to `NamedItem` in the first conditional expression, and the inferred type of the `getName` function is `string`.
# 5 Statements
-This chapter describes the static type checking TypeScript provides for JavaScript statements. TypeScript itself does not introduce any new statement constructs.
+This 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.
-## 5.1 Variable Statements
+## 5.1 Blocks
-Variable statements are extended to include optional type annotations and ECMAScript 6 destructuring declarations.
+Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 6 grammar).
+
+ *Declaration:* *( Modified )*
+ …
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+
+Local class, interface, type alias, and enum declarations are block scoped, similar to let and const declarations.
+
+## 5.2 Variable Statements
+
+Variable statements are extended to include optional type annotations.
*VariableDeclaration:* *( Modified )*
*SimpleVariableDeclaration*
@@ -3216,23 +3452,20 @@ Variable statements are extended to include optional type annotations and ECMASc
A variable declaration is either a simple variable declaration or a destructuring variable declaration.
-### 5.1.1 Simple Variable Declarations
+### 5.2.1 Simple Variable Declarations
A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value.
*SimpleVariableDeclaration:*
- *Identifier* *TypeAnnotationopt* *Initialiseropt*
-
- *TypeAnnotation:*
- `:` *Type*
+ *BindingIdentifier* *TypeAnnotationopt* *Initializeropt*
The type *T* of a variable introduced by a simple variable declaration is determined as follows:
* If the declaration includes a type annotation, *T* is that type.
-* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.11](#3.11)) of the type of the initializer expression.
+* 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.
* Otherwise, *T* is the Any type.
-When 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.10.4](#3.10.4)) the type given in the type annotation.
+When 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.
Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable.
@@ -3270,47 +3503,16 @@ var d: { x: number; y: number; } = { x: 0, y: undefined };
var e = <{ x: number; y: number; }> { x: 0, y: undefined };
```
-### 5.1.2 Destructuring Variable Declarations
+### 5.2.2 Destructuring Variable Declarations
A ***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.
*DestructuringVariableDeclaration:*
- *BindingPattern* *TypeAnnotationopt* *Initialiser*
+ *BindingPattern* *TypeAnnotationopt* *Initializer*
- *BindingPattern:*
- *ObjectBindingPattern*
- *ArrayBindingPattern*
+Each 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.
- *ObjectBindingPattern:*
- `{` `}`
- `{` *BindingPropertyList* `,`*opt* `}`
-
- *BindingPropertyList:*
- *BindingProperty*
- *BindingPropertyList* `,` *BindingProperty*
-
- *BindingProperty:*
- *Identifier* *Initialiseropt*
- *PropertyName* `:` *Identifier* *Initialiseropt*
- *PropertyName* `:` *BindingPattern* *Initialiseropt*
-
- *ArrayBindingPattern:*
- `[` *Elisionopt* *BindingRestElementopt* `]`
- `[` *BindingElementList* `]`
- `[` *BindingElementList* `,` *Elisionopt* *BindingRestElementopt* `]`
-
- *BindingElementList:*
- *Elisionopt* *BindingElement*
- *BindingElementList* `,` *Elisionopt* *BindingElement*
-
- *BindingElement:*
- *Identifier* *Initialiseropt*
- *BindingPattern* *Initialiseropt*
-
- *BindingRestElement:*
- `...` *Identifier*
-
-Each 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.11](#3.11)) of the type associated with the binding property or element, as defined in the following.
+*TODO: Document destructuring an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array*.
The type *T* associated with a destructuring variable declaration is determined as follows:
@@ -3401,7 +3603,7 @@ var _a = getSomeObject(),
z = _d === void 0 ? 10 : _d;
```
-### 5.1.3 Implied Type
+### 5.2.3 Implied Type
A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows:
@@ -3431,15 +3633,31 @@ var [a, b, c] = [1, "hello", true];
the 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.
-## 5.2 If, Do, and While Statements
+## 5.3 Let and Const Declarations
+
+Let and const declarations are exended to include optional type annotations.
+
+ *LexicalBinding:* *( Modified )*
+ *SimpleLexicalBinding*
+ *DestructuringLexicalBinding*
+
+ *SimpleLexicalBinding:*
+ *BindingIdentifier* *TypeAnnotationopt* *Initializeropt*
+
+ *DestructuringLexicalBinding:*
+ *BindingPattern* *TypeAnnotationopt* *Initializeropt*
+
+*TODO: Document scoping and types of [let and const declarations](https://github.com/Microsoft/TypeScript/pull/904)*.
+
+## 5.4 If, Do, and While Statements
Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean).
-## 5.3 For Statements
+## 5.5 For Statements
-Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.1](#5.1)).
+Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [5.2](#5.2)).
-## 5.4 For-In Statements
+## 5.6 For-In Statements
In a 'for-in' statement of the form
@@ -3457,21 +3675,25 @@ for (var v in expr) statement
*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.
-## 5.5 Continue Statements
+## 5.7 For-Of Statements
+
+*TODO: Document [for-of statements](https://github.com/Microsoft/TypeScript/issues/7)*.
+
+## 5.8 Continue Statements
A 'continue' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') statement. When a 'continue' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement.
-## 5.6 Break Statements
+## 5.9 Break Statements
A 'break' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') or 'switch' statement. When a 'break' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement.
-## 5.7 Return Statements
+## 5.10 Return Statements
-It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in module bodies.
+It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in namespace bodies.
A 'return' statement without an expression returns the value 'undefined' and is permitted in the body of any function, regardless of the return type of the function.
-When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.19](#4.19)) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*'s return type.
+When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [4.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.
In a function implementation without a return type annotation, the return type is inferred from the 'return' statements in the function body, as described in section [6.3](#6.3).
@@ -3485,19 +3707,19 @@ function f(): (x: string) => number {
the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'.
-## 5.8 With Statements
+## 5.11 With Statements
Use of the 'with' statement in TypeScript is an error, as is the case in ECMAScript 5's strict mode. Furthermore, within the body of a 'with' statement, TypeScript considers every identifier occurring in an expression (section [4.3](#4.3)) to be of the Any type regardless of its declared type. Because the 'with' statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier.
-## 5.9 Switch Statements
+## 5.12 Switch Statements
-In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.10.4](#3.10.4)) the type of the 'switch' expression.
+In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [3.11.4](#3.11.4)) the type of the 'switch' expression.
-## 5.10 Throw Statements
+## 5.13 Throw Statements
The expression specified in a 'throw' statement can be of any type.
-## 5.11 Try Statements
+## 5.14 Try Statements
The variable introduced by a 'catch' clause of a 'try' statement is always of type Any. It is not possible to include a type annotation in a 'catch' clause.
@@ -3509,26 +3731,23 @@ TypeScript extends JavaScript functions to include type parameters, parameter an
## 6.1 Function Declarations
-Function declarations consist of an optional set of function overloads followed by an actual function implementation.
+Function declarations are extended to permit the function body to be omitted in overload declarations.
*FunctionDeclaration:* *( Modified )*
- *FunctionOverloadsopt* *FunctionImplementation*
+ `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}`
+ `function` *BindingIdentifieropt* *CallSignature* `;`
- *FunctionOverloads:*
- *FunctionOverload*
- *FunctionOverloads* *FunctionOverload*
+A *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)).
- *FunctionOverload:*
- `function` *Identifier* *CallSignature* `;`
+Function 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`).
- *FunctionImplementation:*
- `function` *Identifier* *CallSignature* `{` *FunctionBody* `}`
+When 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.
-A function declaration introduces a function with the given name in the containing declaration space. Function overloads, if present, must specify the same name as the function implementation. If a function declaration includes overloads, the overloads determine the call signatures of the type given to the function object and the function implementation signature must be assignable to that type. Otherwise, the function implementation itself determines the call signature. Function overloads have no other effect on a function declaration.
+When 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.
## 6.2 Function Overloads
-Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function's return type varies based on its arguments. Overload resolution in function calls is described further in section [4.12](#4.12).
+Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function's return type varies based on its arguments. Overload resolution in function calls is described further in section [4.15](#4.15).
Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost.
@@ -3568,8 +3787,8 @@ A function implementation without a return type annotation is said to be an ***i
* If there are no return statements with expressions in *f*'s function body, the inferred return type is Void.
* Otherwise, if *f*'s function body directly references *f* or references any implicitly typed functions that through this same analysis reference *f*, the inferred return type is Any.
-* Otherwise, if *f* is a contextually typed function expression (section [4.9.3](#4.9.3)), the inferred return type is the union type (section [3.4](#3.4)) of the types of the return statement expressions in the function body, ignoring return statements with no expressions.
-* Otherwise, the inferred return type is the first of the types of the return statement expressions in the function body that is a supertype (section [3.10.3](#3.10.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.
+* 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.
+* 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.
In the example
@@ -3590,11 +3809,11 @@ An explicitly typed function whose return type isn't the Void or the Any type mu
The type of 'this' in a function implementation is the Any type.
-In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [4.19](#4.19)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. When a parameter declaration has no type annotation but includes an initializer, the type of the parameter is the widened form (section [3.11](#3.11)) of the type of the initializer expression.
+In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [4.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.
Initializer 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.
-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
+When 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
```TypeScript
function strange(x: number, y = x * 2, z = x + y) {
@@ -3625,13 +3844,14 @@ the local variable 'x' is in scope in the parameter initializer (thus hiding the
## 6.4 Destructuring Parameter Declarations
-Parameter declarations can specify binding patterns (section [3.8.2.2](#3.8.2.2)) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [5.1.2](#5.1.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.
+Parameter 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.
The 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:
* If the declaration includes a type annotation, *T* is that type.
-* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.11](#3.11)) of the type of the initializer expression.
-* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.1.3](#5.1.3)).
+* 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.
+* 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.
+* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.2.3](#5.2.3)).
* Otherwise, if the parameter is a rest parameter, *T* is `any[]`.
* Otherwise, *T* is `any`.
@@ -3683,7 +3903,7 @@ function drawText({ text, location: [x, y], bold }: DrawTextInfo) {
## 6.5 Generic Functions
-A function implementation may include type parameters in its signature (section [3.8.2.1](#3.8.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct.
+A function implementation may include type parameters in its signature (section [3.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.
Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation.
@@ -3701,9 +3921,9 @@ function compare(x: T, y: T): number {
}
```
-Note that the 'x' and 'y' parameters are known to be subtypes of the constraint 'Comparable' and therefore have a 'compareTo' member. This is described further in section [3.5.1](#3.5.1).
+Note that the 'x' and 'y' parameters are known to be subtypes of the constraint 'Comparable' and therefore have a 'compareTo' member. This is described further in section [3.6.1](#3.6.1).
-The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section [4.12.2](#4.12.2)) from the types of the regular arguments in the call. In the example
+The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section [4.15.2](#4.15.2)) from the types of the regular arguments in the call. In the example
```TypeScript
class Person {
@@ -3741,6 +3961,14 @@ where *Parameter* is the parameter name and *Default* is the default value expre
*FunctionStatements* is the code generated for the statements specified in the function body.
+## 6.7 Generator Functions
+
+*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*.
+
+## 6.8 Type Guard Functions
+
+*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*.
+
# 7 Interfaces
@@ -3749,16 +3977,16 @@ Interfaces provide the ability to name and parameterize object types and to comp
Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.
-Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section [3.10.2](#3.10.2)).
+Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section [3.11.2](#3.11.2)).
Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces.
## 7.1 Interface Declarations
-An interface declaration declares a new named type (section [3.6](#3.6)) by introducing a type name in the containing module.
+An interface declaration declares an ***interface type***.
*InterfaceDeclaration:*
- `interface` *Identifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType*
+ `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType*
*InterfaceExtendsClause:*
`extends` *ClassOrInterfaceTypeList*
@@ -3770,9 +3998,9 @@ An interface declaration declares a new named type (section [3.6](#3.6)) by intr
*ClassOrInterfaceType:*
*TypeReference*
-The *Identifier* of an interface declaration may not be one of the predefined type names (section [3.7.1](#3.7.1)).
+An *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)).
-An interface may optionally have type parameters (section [3.5.1](#3.5.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.
+An 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.
An interface can inherit from zero or more ***base types*** which are specified in the *InterfaceExtendsClause*. The base types must be type references to class or interface types.
@@ -3786,9 +4014,9 @@ The following constraints must be satisfied by an interface declaration or other
* 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.
* An interface cannot declare a property with the same name as an inherited private or protected property.
-* Inherited properties with the same name must be identical (section [3.10.2](#3.10.2)).
-* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.8.4](#3.8.4).
-* The instance type (section [3.6.1](#3.6.1)) of the declared interface must be assignable (section [3.10.4](#3.10.4)) to each of the base type references.
+* Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)).
+* 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).
+* The instance type (section [3.7.1](#3.7.1)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references.
An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member.
@@ -3891,7 +4119,7 @@ class Location {
}
```
-In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.10](#3.10)).
+In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.11](#3.11)).
Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not.
@@ -3919,24 +4147,24 @@ function asMoverShaker(obj: any): MoverShaker {
# 8 Classes
-TypeScript supports classes that are closely aligned with those proposed for ECMAScript 6, and includes extensions for instance and static member declarations and properties declared and initialized from constructor parameters.
+TypeScript extends JavaScript classes to include type parameters, implements clauses, accessibility modifiers, member variable declarations, and parameter property declarations in constructors.
-*NOTE: TypeScript currently doesn't support class expressions or nested class declarations from the ECMAScript 6 proposal*.
+*TODO: Document [abstract classes](https://github.com/Microsoft/TypeScript/issues/3578)*.
## 8.1 Class Declarations
-Class declarations introduce named types and provide implementations of those types. Classes support inheritance, allowing derived classes to extend and specialize base classes.
+A class declaration declares a ***class type*** and a ***constructor function***.
- *ClassDeclaration:*
- `class` *Identifier* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}`
+ *ClassDeclaration:* *( Modified )*
+ `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}`
-A *ClassDeclaration* declares a ***class type*** and a ***constructor function***, both with the name given by *Identifier*, in the containing module. The class type is created from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is created 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.
+A *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.
-The *Identifier* of a class declaration may not be one of the predefined type names (section [3.7.1](#3.7.1)).
+The *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)).
-A class may optionally have type parameters (section [3.5.1](#3.5.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*.
+A 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*.
-The following example introduces both a named type called 'Point' (the class type) and a member called 'Point' (the constructor function) in the containing module.
+The following example introduces both a named type called 'Point' (the class type) and a named value called 'Point' (the constructor function) in the containing declaration space.
```TypeScript
class Point {
@@ -3946,7 +4174,7 @@ class Point {
}
```
-The 'Point' type is exactly equivalent to
+The named type 'Point' is exactly equivalent to
```TypeScript
interface Point {
@@ -3956,7 +4184,7 @@ interface Point {
}
```
-The 'Point' member is a constructor function whose type corresponds to the declaration
+The named value 'Point' is a constructor function whose type corresponds to the declaration
```TypeScript
var Point: {
@@ -3975,9 +4203,11 @@ the identifier 'Point' in the type annotation refers to the class instance type,
### 8.1.1 Class Heritage Specification
+*TODO: Update this section to reflect [expressions in class extends clauses](https://github.com/Microsoft/TypeScript/pull/3516)*.
+
The 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.
- *ClassHeritage:*
+ *ClassHeritage:* *( Modified )*
*ClassExtendsClauseopt* *ImplementsClauseopt*
*ClassExtendsClause:*
@@ -3995,7 +4225,7 @@ The following constraints must be satisfied by the class heritage specification
* 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.
* 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.
-* The instance type (section [3.6.1](#3.6.1)) of the declared class must be assignable (section [3.10.4](#3.10.4)) to the base type reference and each of the type references listed in the `implements` clause.
+* The instance type (section [3.7.1](#3.7.1)) 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.
* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures.
The following example illustrates a situation in which the first rule above would be violated:
@@ -4003,7 +4233,7 @@ The following example illustrates a situation in which the first rule above woul
```TypeScript
class A { a: number; }
-module Foo {
+namespace Foo {
var A = 1;
class B extends A { b: string; }
}
@@ -4019,14 +4249,7 @@ Note that because TypeScript has a structural type system, a class doesn't need
The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members.
- *ClassBody:*
- *ClassElementsopt*
-
- *ClassElements:*
- *ClassElement*
- *ClassElements* *ClassElement*
-
- *ClassElement:*
+ *ClassElement:* *( Modified )*
*ConstructorDeclaration*
*PropertyMemberDeclaration*
*IndexMemberDeclaration*
@@ -4043,7 +4266,7 @@ The members of a class consist of the members introduced through member declarat
Members are either ***instance members*** or ***static members***.
-Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated instance type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the instance type (section [3.6.1](#3.6.1)) of the class.
+Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated instance type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of the class.
Static 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.
@@ -4091,7 +4314,7 @@ In class 'A', the accesses to 'x' are permitted because 'x' is declared in 'A',
A derived class ***inherits*** all members from its base class it doesn't ***override***. Inheritance means that a derived class implicitly contains all non-overridden members of the base class. Only public and protected property members can be overridden.
-A property member in a derived class is said to override a property member in a base class when the derived class property member has the same name and kind (instance or static) as the base class property member. The type of an overriding property member must be assignable (section [3.10.4](#3.10.4)) to the type of the overridden property member, or otherwise a compile-time error occurs.
+A property member in a derived class is said to override a property member in a base class when the derived class property member has the same name and kind (instance or static) as the base class property member. The type of an overriding property member must be assignable (section [3.11.4](#3.11.4)) to the type of the overridden property member, or otherwise a compile-time error occurs.
Base class instance member functions can be overridden by derived class instance member functions, but not by other kinds of members.
@@ -4099,11 +4322,11 @@ Base class instance member variables and accessors can be overridden by derived
Base 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.
-An 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.10.4](#3.10.4)) to the type of the overridden index member, or otherwise a compile-time error occurs.
+An 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.
### 8.2.4 Class Types
-A class declaration declares a new named type (section [3.6](#3.6)) called a class type. Within the constructor and member functions of a class, the type of `this` is the instance type (section [3.6.1](#3.6.1)) of this class type. The class type has the following members:
+A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and member functions of a class, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of this class type. The class type has the following members:
* A property for each instance member variable declaration in the class body.
* A property of a function type for each instance member function declaration in the class body.
@@ -4112,7 +4335,7 @@ A class declaration declares a new named type (section [3.6](#3.6)) called a cla
* An index signature for each instance index member declaration in the class body.
* All base class instance type property or index members that are not overridden in the class.
-All 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.8.4](#3.8.4).
+All 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).
In the example
@@ -4212,23 +4435,16 @@ Note that the construct signatures in the constructor function types have the sa
A constructor declaration declares the constructor function of a class.
*ConstructorDeclaration:*
- *ConstructorOverloadsopt* *ConstructorImplementation*
-
- *ConstructorOverloads:*
- *ConstructorOverload*
- *ConstructorOverloads* *ConstructorOverload*
-
- *ConstructorOverload:*
+ *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}`
*AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;`
- *ConstructorImplementation:*
- *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}`
+Constructor 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.
-A class may contain at most one constructor declaration. If a class contains no constructor declaration, an automatic constructor is provided, as described in section [8.3.3](#8.3.3).
+In a class with no constructor declaration, an automatic constructor is provided, as described in section [8.3.3](#8.3.3).
-Overloads and the implementation of a constructor may include an accessibility modifier, but only public constructors are supported and private or protected constructors result in an error.
+When 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)).
-If a constructor declaration includes overloads, the overloads determine the construct signatures of the type given to the constructor function object, and the constructor implementation signature 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)).
+When 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.
The 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 instance type of the class.
@@ -4236,7 +4452,7 @@ The type parameters of a generic class are in scope and accessible in a construc
### 8.3.1 Constructor Parameters
-Similar 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`. 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.
+Similar 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.
A 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
@@ -4264,7 +4480,7 @@ class Point {
### 8.3.2 Super Calls
-Super calls (section [4.8.1](#4.8.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:
+Super 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:
```TypeScript
class ColoredPoint extends Point {
@@ -4358,13 +4574,13 @@ var Point: {
A member variable declaration declares an instance member variable or a static member variable.
*MemberVariableDeclaration:*
- *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initialiseropt* `;`
+ *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;`
-The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.1](#5.1)).
+The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)).
An instance member variable declaration introduces a member in the class instance 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 class instance type.
-A 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 program or module is loaded.
+A 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.
Initializer 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.
@@ -4402,27 +4618,18 @@ class Employee {
A member function declaration declares an instance member function or a static member function.
*MemberFunctionDeclaration:*
- *MemberFunctionOverloadsopt* *MemberFunctionImplementation*
-
- *MemberFunctionOverloads*:
- *MemberFunctionOverload*
- *MemberFunctionOverloads* *MemberFunctionOverload*
-
- *MemberFunctionOverload*:
+ *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
*AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;`
- *MemberFunctionImplementation:*
- *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
-
A 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.
-All overloads of a member function must have the same accessibility (public, private, or protected) and kind (instance or static).
+All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static).
An instance member function declaration declares a property in the class instance 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 class instance type.
A 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.
-A member function can access overridden base class members using a super property access (section [4.8.2](#4.8.2)). For example
+A member function can access overridden base class members using a super property access (section [4.9.2](#4.9.2)). For example
```TypeScript
class Point {
@@ -4490,16 +4697,24 @@ A static member accessor declaration declares a property in the constructor func
Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.6.1](#8.6.1).
+### 8.4.4 Dynamic Property Declarations
+
+If 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:
+
+* A dynamic property declaration does not introduce a property in the class instance type or constructor function type.
+* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type.
+* 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.
+
## 8.5 Index Member Declarations
-An index member declaration introduces an index signature (section [3.8.4](#3.8.4)) in the class instance type.
+An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class instance type.
*IndexMemberDeclaration:*
*IndexSignature* `;`
Index member declarations have no body and cannot specify an accessibility modifier.
-A 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.8.4](#3.8.4).
+A 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).
It is not possible to declare index members for the static side of a class.
@@ -4507,7 +4722,7 @@ Note that it is seldom meaningful to include a string index signature in a class
## 8.6 Code Generation
-This section describes the structure of the JavaScript code generated from TypeScript classes.
+When the output target is ECMAScript 6 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.
### 8.6.1 Classes Without Extends Clauses
@@ -4696,14 +4911,14 @@ An enum type is a distinct subtype of the Number primitive type with an associat
## 9.1 Enum Declarations
-An enum declaration declares an ***enum type*** and an ***enum object*** in the containing module.
+An enum declaration declares an ***enum type*** and an ***enum object***.
*EnumDeclaration:*
- `const`*opt* `enum` *Identifier* `{` *EnumBodyopt* `}`
+ `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}`
-The enum type and enum object declared by an *EnumDeclaration* both have the name given by the *Identifier* of the declaration. The enum type is a distinct subtype of the Number primitive type. The enum object is a variable of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'.
+An *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'.
-The *Identifier* of an enum declaration may not be one of the predefined type names (section [3.7.1](#3.7.1)).
+The *BindingIdentifier* of an enum declaration may not be one of the predefined type names (section [3.8.1](#3.8.1)).
When 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).
@@ -4749,6 +4964,8 @@ The body of an enum declaration defines zero or more enum members which are the
*EnumValue:*
*AssignmentExpression*
+The *PropertyName* of an enum member cannot be a computed property name ([2.2.3](#2.2.3)).
+
Enum 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.
An enum member is classified as follows:
@@ -4858,46 +5075,48 @@ var Color;
-# 10 Internal Modules
+# 10 Namespaces
-An internal module is a named container of statements and declarations. An internal module represents both a namespace and a singleton module instance. The namespace contains named types and other namespaces, and the singleton module instance contains properties for the module's exported members. The body of an internal module corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation.
+Namespaces 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.
-## 10.1 Module Declarations
+## 10.1 Namespace Declarations
-An internal module declaration declares a namespace name and, in the case of an instantiated module, a member name in the containing module.
+A 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.
- *ModuleDeclaration:*
- `module` *IdentifierPath* `{` *ModuleBody* `}`
+ *NamespaceDeclaration:*
+ `namespace` *IdentifierPath* `{` *NamespaceBody* `}`
*IdentifierPath:*
- *Identifier*
- *IdentifierPath* `.` *Identifier*
+ *BindingIdentifier*
+ *IdentifierPath* `.` *BindingIdentifier*
-Internal modules are either ***instantiated*** or ***non-instantiated***. A non-instantiated module is an internal module containing only interface types and other non-instantiated modules. An instantiated module is an internal module that doesn't meet this definition. In intuitive terms, an instantiated module is one for which a module object instance is created, whereas a non-instantiated module is one for which no code is generated.
+Namespaces are declared using the `namespace` keyword, but for backward compatibility of earlier versions of TypeScript a `module` keyword can also be used.
-When a module identifier is referenced as a *ModuleName* (section [3.7.2](#3.7.2)) it denotes a container of module and type names, and when a module identifier is referenced as a *PrimaryExpression* (section [4.3](#4.3)) it denotes the singleton module instance. For example:
+Namespaces 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.
+
+When 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:
```TypeScript
-module M {
+namespace M {
export interface P { x: number; y: number; }
export var a = 1;
}
-var p: M.P; // M used as ModuleName
+var p: M.P; // M used as NamespaceName
var m = M; // M used as PrimaryExpression
var x1 = M.a; // M used as PrimaryExpression
var x2 = m.a; // Same as M.a
var q: m.P; // Error
```
-Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *ModuleName* it denotes a container with a single type member 'P'. The final line in the example is an error because 'm' is a variable which cannot be referenced in a type name.
+Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *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.
-If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated module and it would be an error to reference 'M' as a *PrimaryExpression*.
+If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated namespace and it would be an error to reference 'M' as a *PrimaryExpression*.
-An internal module declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier internal module declarations where all but the outermost are automatically exported. For example:
+A 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:
```TypeScript
-module A.B.C {
+namespace A.B.C {
export var x = 1;
}
```
@@ -4905,106 +5124,128 @@ module A.B.C {
corresponds to
```TypeScript
-module A {
- export module B {
- export module C {
+namespace A {
+ export namespace B {
+ export namespace C {
export var x = 1;
}
}
}
```
-## 10.2 Module Body
+The hierarchy formed by namespace and named type names partially mirrors that formed by namespace instances and members. The example
-The body of an internal module corresponds to a function that is executed once to initialize the module instance.
+```TypeScript
+namespace A {
+ export namespace B {
+ export class C { }
+ }
+}
+```
- *ModuleBody:*
- *ModuleElementsopt*
+introduces a named type with the qualified name 'A.B.C' and also introduces a constructor function that can be accessed using the expression 'A.B.C'. Thus, in the example
- *ModuleElements:*
- *ModuleElement*
- *ModuleElements* *ModuleElement*
+```TypeScript
+var c: A.B.C = new A.B.C();
+```
- *ModuleElement:*
+the two occurrences of 'A.B.C' in fact refer to different entities. It is the context of the occurrences that determines whether 'A.B.C' is processed as a type name or an expression.
+
+## 10.2 Namespace Body
+
+The body of a namespace corresponds to a function that is executed once to initialize the namespace instance.
+
+ *NamespaceBody:*
+ *NamespaceElementsopt*
+
+ *NamespaceElements:*
+ *NamespaceElement*
+ *NamespaceElements* *NamespaceElement*
+
+ *NamespaceElement:*
*Statement*
- `export`*opt* *VariableDeclaration*
- `export`*opt* *FunctionDeclaration*
- `export`*opt* *ClassDeclaration*
- `export`*opt* *InterfaceDeclaration*
- `export`*opt* *TypeAliasDeclaration*
- `export`*opt* *EnumDeclaration*
- `export`*opt* *ModuleDeclaration*
- `export`*opt* *ImportDeclaration*
- `export`*opt* *AmbientDeclaration*
+ *LexicalDeclaration*
+ *FunctionDeclaration*
+ *GeneratorDeclaration*
+ *ClassDeclaration*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+ *NamespaceDeclaration
+ AmbientDeclaration
+ ImportAliasDeclaration
+ ExportNamespaceElement*
-Each module body has a declaration space for local variables (including functions, modules, class constructor functions, and enum objects), a declaration space for local named types (classes, interfaces, and enums), and a declaration space for local namespaces (containers of named types). Every declaration (whether local or exported) in a module contributes to one or more of these declaration spaces.
+ *ExportNamespaceElement:*
+ `export` *VariableStatement*
+ `export` *LexicalDeclaration*
+ `export` *FunctionDeclaration*
+ `export` *GeneratorDeclaration*
+ `export` *ClassDeclaration*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *EnumDeclaration*
+ `export` *NamespaceDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
-## 10.3 Import Declarations
+## 10.3 Import Alias Declarations
-Import declarations are used to create local aliases for entities in other modules.
+Import alias declarations are used to create local aliases for entities in other namespaces.
- *ImportDeclaration:*
- `import` *Identifier* `=` *EntityName* `;`
+ *ImportAliasDeclaration:*
+ `import` *BindingIdentifier* `=` *EntityName* `;`
*EntityName:*
- *ModuleName*
- *ModuleName* `.` *Identifier*
+ *NamespaceName*
+ *NamespaceName* `.` *IdentifierReference*
-An *EntityName* consisting of a single identifier is resolved as a *ModuleName* and is thus required to reference an internal module. The resulting local alias references the given internal module and is itself classified as an internal module.
+An *EntityName* consisting of 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.
-An *EntityName* consisting of more than one identifier is resolved as a *ModuleName* followed by an identifier that names one or more exported entities in the given module. The resulting local alias has all the meanings and classifications of the referenced entity or entities. (As many as three distinct meanings are possible for an entity name—namespace, type, and member.) In effect, it is as if the imported entity or entities were declared locally with the local alias name.
+An *EntityName* consisting of more than one identifier is resolved as a *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.
In the example
```TypeScript
-module A {
+namespace A {
export interface X { s: string }
export var X: X;
}
-module B {
+namespace B {
interface A { n: number }
- import Y = A; // Alias only for module A
- import Z = A.X; // Alias for both type and member A.X
+ import Y = A; // Alias for namespace A
+ import Z = A.X; // Alias for type and value A.X
var v: Z = Z;
}
```
-within 'B', 'Y' is an alias only for module 'A' and not the local interface 'A', whereas 'Z' is an alias for all exported meanings of 'A.X', thus denoting both an interface type and a variable.
+within 'B', 'Y' is an alias only for 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.
-If the *ModuleName* portion of an *EntityName* references an instantiated module, the *ModuleName* is required to reference the module instance when evaluated as an expression. In the example
+If 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
```TypeScript
-module A {
+namespace A {
export interface X { s: string }
}
-module B {
+namespace B {
var A = 1;
import Y = A;
}
```
-'Y' is a local alias for the non-instantiated module 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated module, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the module instance of module 'A'.
+'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'.
When an import statement includes an export modifier, all meanings of the local alias are exported.
## 10.4 Export Declarations
-An export declaration declares an externally accessible module member. An export declaration is simply a regular declaration prefixed with the keyword `export`.
+An export declaration declares an externally accessible namespace member. An export declaration is simply a regular declaration prefixed with the keyword `export`.
-Exported class, interface, and enum types can be accessed as a *TypeName* (section [3.7.2](#3.7.2)) of the form *M.T*, where *M* is a reference to the containing module and *T* is the exported type name. Likewise, as part of a *TypeName*, exported modules can be accessed as a *ModuleName* of the form *M.N*, where *M* is a reference to the containing module and *N* is the exported module.
+The 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.
-Exported variable, function, class, enum, module, and import alias declarations become properties on the module instance and together establish the module's ***instance type***. This unnamed type has the following members:
-
-* A property for each exported variable declaration.
-* A property of a function type for each exported function declaration.
-* A property of a constructor type for each exported class declaration.
-* A property of an object type for each exported enum declaration.
-* A property of an object type for each exported instantiated module declaration.
-* A property for each exported import alias that references a variable, function, class, enum, or instantiated module.
-
-An exported member depends on a (possibly empty) set of named types (section [3.6](#3.6)). Those named types must be at least as accessible as the exported member, or otherwise an error occurs.
+An 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.
The 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:
@@ -5012,40 +5253,40 @@ The named types upon which a member depends are the named types occurring in the
* A function directly depends on each *Type* specified in a parameter or return type annotation.
* 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.
* 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.
-* A module directly depends on its exported members.
+* A namespace directly depends on its exported members.
* A *Type* or *ObjectType* directly depends on every *TypeReference* that occurs within the type at any level of nesting.
* A *TypeReference* directly depends on the type it references and on each *Type* specified as a type argument.
-A named type *T* having a root module *R* (section [2.3](#2.3)) is said to be ***at least as accessible as*** a member *M* if
+A 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
-* *R* is the global module or an external module, or
-* *R* is an internal module in the parent module chain of *M*.
+* *R* is the global namespace or a module, or
+* *R* is a namespace in the parent namespace chain of *M*.
In the example
```TypeScript
interface A { x: string; }
-module M {
+namespace M {
export interface B { x: A; }
export interface C { x: B; }
export function foo(c: C) { … }
}
```
-the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because it is declared in a parent module of foo's module.
+the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because I t is declared in a parent namespace of foo's namespace.
## 10.5 Declaration Merging
-Internal modules are "open-ended" and internal module declarations with the same qualified name relative to a common root (as defined in section [2.3](#2.3)) contribute to a single module. For example, the following two declarations of a module outer might be located in separate source files.
+Namespaces 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.
File a.ts:
```TypeScript
-module outer {
+namespace outer {
var local = 1; // Non-exported local variable
export var a = local; // outer.a
- export module inner {
+ export namespace inner {
export var x = 10; // outer.inner.x
}
}
@@ -5054,16 +5295,16 @@ module outer {
File b.ts:
```TypeScript
-module outer {
+namespace outer {
var local = 2; // Non-exported local variable
export var b = local; // outer.b
- export module inner {
+ export namespace inner {
export var y = 20; // outer.inner.y
}
}
```
-Assuming the two source files are part of the same program, the two declarations will have the global module as their common root and will therefore contribute to the same module instance, the instance type of which will be:
+Assuming 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:
```TypeScript
{
@@ -5076,15 +5317,17 @@ Assuming the two source files are part of the same program, the two declarations
}
```
-Declaration merging does not apply to local aliases created by import declarations. In other words, it is not possible have an import declaration and a module declaration for the same name within the same module body.
+Declaration 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.
-Declaration merging also extends to internal module declarations with the same qualified name relative to a common root as a function, class, or enum declaration:
+*TODO: Clarify rules for [alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*.
-* When merging a function and an internal module, the type of the function object is merged with the instance type of the module. In effect, the overloads or implementation of the function provide the call signatures and the exported members of the module provide the properties of the combined type.
-* When merging a class and an internal module, the type of the constructor function object is merged with the instance type of the module. In effect, the overloads or implementation of the class constructor provide the construct signatures, and the static members of the class and exported members of the module provide the properties of the combined type. It is an error to have static class members and exported module members with the same name.
-* When merging an enum and an internal module, the type of the enum object is merged with the instance type of the module. In effect, the members of the enum and the exported members of the module provide the properties of the combined type. It is an error to have enum members and exported module members with the same name.
+Declaration merging also extends to namespace declarations with the same qualified name relative to a common root as a function, class, or enum declaration:
-When merging a non-ambient function or class declaration and a non-ambient internal module declaration, the function or class declaration must be located prior to the internal module declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object "callable" after the fact.)
+* When merging a 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.
+* 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.
+* 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.
+
+When 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.)
The example
@@ -5098,7 +5341,7 @@ function point(x: number, y: number): Point {
return { x: x, y: y };
}
-module point {
+namespace point {
export var origin = point(0, 0);
export function equals(p1: Point, p2: Point) {
return p1.x == p2.x && p1.y == p2.y;
@@ -5110,20 +5353,20 @@ var p2 = point.origin;
var b = point.equals(p1, p2);
```
-declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the module declaration for 'point' is located after the function declaration.
+declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the namespace declaration for 'point' is located after the function declaration.
## 10.6 Code Generation
-An internal module generates JavaScript code that is equivalent to the following:
+A namespace generates JavaScript code that is equivalent to the following:
```TypeScript
-var ;
-(function() {
-
-})(||(={}));
+var ;
+(function() {
+
+})(||(={}));
```
-where *ModuleName* is the name of the module and *ModuleStatements* is the code generated for the statements in the module body. The *ModuleName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire module is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn't create and return a module instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that internal modules can extend each other.
+where *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.
An import statement generates code of the form
@@ -5131,182 +5374,428 @@ An import statement generates code of the form
var = ;
```
-This code is emitted only if the imported entity is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported entity is referenced only as a *TypeName* or *ModuleName*, nothing is emitted. This ensures that types declared in one internal module can be referenced through an import alias in another internal module with no run-time overhead.
+This 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.
-When a variable is exported, all references to the variable in the body of the module are replaced with
+When a variable is exported, all references to the variable in the body of the namespace are replaced with
```TypeScript
-.
+.
```
-This effectively promotes the variable to be a property on the module instance and ensures that all references to the variable become references to the property.
+This 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.
-When a function, class, enum, or module is exported, the code generated for the entity is followed by an assignment statement of the form
+When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form
```TypeScript
-. = ;
+. = ;
```
-This copies a reference to the entity into a property on the module instance.
+This copies a reference to the entity into a property on the namespace instance.
-# 11 Source Files and External Modules
+# 11 Scripts and Modules
-TypeScript implements external modules that are closely aligned with those proposed for ECMAScript 6 and supports code generation targeting CommonJS and AMD module systems.
+TypeScript implements support for ECMAScript 6 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems.
-*NOTE: TypeScript currently doesn't support the full proposed capabilities of the ECMAScript 6 import and export syntax. We expect to align more closely on the syntax as the ECMAScript 6 specification evolves*.
+## 11.1 Programs and Source Files
-## 11.1 Source Files
-
-A TypeScript ***program*** consists of one or more source files that are either ***implementation source files*** or ***declaration source files***. Source files with extension '.ts' are *ImplementationSourceFiles* containing statements and declarations. Source files with extension '.d.ts' are *DeclarationSourceFiles* containing declarations only. Declaration source files are a strict subset of implementation source files.
+A TypeScript ***program*** consists of one or more source files.
*SourceFile:*
*ImplementationSourceFile*
*DeclarationSourceFile*
*ImplementationSourceFile:*
- *ImplementationElementsopt*
-
- *ImplementationElements:*
- *ImplementationElement*
- *ImplementationElements* *ImplementationElement*
-
- *ImplementationElement:*
- *ModuleElement*
- *ExportAssignment*
- *AmbientExternalModuleDeclaration*
- `export`*opt* *ExternalImportDeclaration*
+ *ImplementationScript*
+ *ImplementationModule*
*DeclarationSourceFile:*
- *DeclarationElementsopt*
+ *DeclarationScript*
+ *DeclarationModule*
- *DeclarationElements:*
- *DeclarationElement*
- *DeclarationElements* *DeclarationElement*
+Source 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.
- *DeclarationElement:*
- *ExportAssignment*
- *AmbientExternalModuleDeclaration*
- `export`*opt* *InterfaceDeclaration*
- `export`*opt* *TypeAliasDeclaration*
- `export`*opt* *ImportDeclaration*
- `export`*opt* *AmbientDeclaration*
- `export`*opt* *ExternalImportDeclaration*
+Declaration 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.
When a TypeScript program is compiled, all of the program's source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files.
-The source elements permitted in a TypeScript implementation source file are a superset of those supported by JavaScript. Specifically, TypeScript extends the JavaScript grammar's existing *VariableDeclaration* (section [5.1](#5.1)) and *FunctionDeclaration* (section [6.1](#6.1)) productions, and adds *TypeAliasDeclaration* (section [3.9](#3.9)), *InterfaceDeclaration* (section [7.1](#7.1)), *ClassDeclaration* (section [8.1](#8.1)), *EnumDeclaration* (section [9.1](#9.1)), *ModuleDeclaration* (section [10.1](#10.1)), *ImportDeclaration* (section [10.3](#10.3)), *ExternalImportDeclaration* (section [11.2.2](#11.2.2)), *ExportAssignment* (section [11.2.4](#11.2.4)), *AmbientDeclaration* (section [12.1](#12.1)), and *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) productions.
-
-Declaration source files are restricted to contain declarations only. Declaration source files can be used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application.
-
-Implementation and declaration source files that contain no import or export declarations form the single ***global module***. Entities declared in the global module are in scope everywhere in a program. Initialization order of the source files that make up the global module 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).
-
-Implementation and declaration source files that contain at least one external import declaration, export assignment, or top-level exported declaration are considered separate ***external modules***. Entities declared in an external module are in scope only in that module, but exported entities can be imported into other modules using import declarations. Initialization order of external modules is determined by the module loader being 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.
-
-External modules can additionally be declared using *AmbientExternalModuleDeclarations* in the global module that directly specify the external module names as string literals. This is described further in section [12.2](#12.2).
-
### 11.1.1 Source Files Dependencies
-The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and external import declarations as follows:
+The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows:
* A comment of the form /// <reference path="…"/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
-* An external import declaration that specifies a relative external module name (section [11.2.1](#11.2.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency.
-* An external import declaration that specifies a top-level external module name (section [11.2.1](#11.2.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency.
+* A 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.
+* 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.
Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined.
-## 11.2 External Modules
+## 11.2 Scripts
-External modules are separately loaded bodies of code referenced using external module names. External modules can be likened to functions that are loaded and executed once to initialize their associated module instance. Entities declared in an external module are private and inaccessible elsewhere unless they are exported.
+Source 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.
-External modules are written as separate source files that contain at least one external import declaration, export assignment, or top-level exported declaration. Specifically, if a source file contains at least one
+ *ImplementationScript:*
+ *ImplementationScriptElementsopt*
-* *ExternalImportDeclaration*,
-* *ExportAssignment*,
-* top-level exported *VariableDeclaration*,
-* top-level exported *FunctionDeclaration*,
-* top-level exported *ClassDeclaration*,
-* top-level exported *InterfaceDeclaration*,
-* top-level exported *TypeAliasDeclaration*,
-* top-level exported *EnumDeclaration*,
-* top-level exported *ModuleDeclaration*,
-* top-level exported *ImportDeclaration*, or
-* top-level exported *AmbientDeclaration*,
+ *ImplementationScriptElements:*
+ *ImplementationScriptElement*
+ *ImplementationScriptElements* *ImplementationScriptElement*
-that source file is considered an external module; otherwise, the source file is considered part of the global module.
+ *ImplementationScriptElement:*
+ *ImplementationElement*
+ *AmbientModuleDeclaration*
-Below is an example of two external modules written in separate source files.
+ *ImplementationElement:*
+ *Statement*
+ *LexicalDeclaration*
+ *FunctionDeclaration*
+ *GeneratorDeclaration*
+ *ClassDeclaration*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+ *NamespaceDeclaration*
+ *AmbientDeclaration*
+ *ImportAliasDeclaration*
-File main.ts:
+ *DeclarationScript:*
+ *DeclarationScriptElementsopt*
+
+ *DeclarationScriptElements:*
+ *DeclarationScriptElement*
+ *DeclarationScriptElements* *DeclarationScriptElement*
+
+ *DeclarationScriptElement:*
+ *DeclarationElement*
+ *AmbientModuleDeclaration*
+
+ *DeclarationElement:*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *NamespaceDeclaration*
+ *AmbientDeclaration*
+ *ImportAliasDeclaration*
+
+The 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).
+
+## 11.3 Modules
+
+Source 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.
+
+ *ImplementationModule:*
+ *ImplementationModuleElementsopt*
+
+ *ImplementationModuleElements:*
+ *ImplementationModuleElement*
+ *ImplementationModuleElements* *ImplementationModuleElement*
+
+ *ImplementationModuleElement:*
+ *ImplementationElement*
+ *ImportDeclaration*
+ *ImportAliasDeclaration*
+ *ImportRequireDeclaration*
+ *ExportImplementationElement*
+ *ExportDefaultImplementationElement*
+ *ExportListDeclaration*
+ *ExportAssignment*
+
+ *DeclarationModule:*
+ *DeclarationModuleElementsopt*
+
+ *DeclarationModuleElements:*
+ *DeclarationModuleElement*
+ *DeclarationModuleElements* *DeclarationModuleElement*
+
+ *DeclarationModuleElement:*
+ *DeclarationElement*
+ *ImportDeclaration*
+ *ImportAliasDeclaration*
+ *ExportDeclarationElement*
+ *ExportDefaultDeclarationElement*
+ *ExportListDeclaration*
+ *ExportAssignment*
+
+Initialization 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.
+
+Modules 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).
+
+Below is an example of two modules written in separate source files:
```TypeScript
-import log = require("./log");
-log.message("hello");
-```
+// -------- main.ts --------
+import { message } from "./log";
+message("hello");
-File log.ts:
-
-```TypeScript
+// -------- log.ts --------
export function message(s: string) {
console.log(s);
}
```
-The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program. At run-time, the import declaration loads the 'log' module and produces a reference to its module instance through which it is possible to reference the exported function.
+The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program.
-TypeScript supports two patterns of JavaScript code generation for external modules: The CommonJS Modules pattern (section [11.2.5](#11.2.5)), typically used by server frameworks such as node.js, and the Asynchronous Module Definition (AMD) pattern (section [11.2.6](#11.2.6)), an extension to CommonJS Modules that permits asynchronous module loading, as is typical in browsers. The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author external modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code.
+TypeScript supports multiple patterns of JavaScript code generation for modules:
-### 11.2.1 External Module Names
+* CommonJS. This format is used by server frameworks such as node.js.
+* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS.
+* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders.
+* System. This format is used to represent ECMAScript 6 semantics with high fidelity in down-level environments.
-External modules are identified and referenced using external module names. The following definition is aligned with that provided in the CommonJS Modules 1.0 specification.
+The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author 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.
-* An external module name is a string of terms delimited by forward slashes.
-* External module names may not have file-name extensions like ".js".
-* External module names may be relative or top-level. An external module name is relative if the first term is "." or "..".
+### 11.3.1 Module Names
+
+Modules 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.
+
+* A module name is a string of terms delimited by forward slashes.
+* Module names may not have file-name extensions like ".js".
+* Module names may be relative or top-level. A module name is relative if the first term is "." or "..".
* Top-level names are resolved off the conceptual module name space root.
* Relative names are resolved relative to the name of the module in which they occur.
-For purposes of resolving external module references, TypeScript associates a file path with every external module. The file path is simply the path of the module's source file without the file extension. For example, an external module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and an external module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'.
+For purposes of resolving 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'.
-An external module name in an import declaration is resolved as follows:
+A module name in an import declaration is resolved as follows:
-* If the import declaration specifies a relative external module name, the name is resolved relative to the directory of the referencing module's file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path 'C:/src/ui/main', the external module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'.
-* If the import declaration specifies a top-level external module name and the program contains an *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, then the import declaration references that ambient external module.
-* If the import declaration specifies a top-level external module name and the program contains no *AmbientExternalModuleDeclaration* (section [12.2](#12.2)) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs.
+* 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'.
+* 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.
+* 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.
-### 11.2.2 External Import Declarations
+### 11.3.2 Import Declarations
-External import declarations are used to import external modules and create local aliases by which they may be referenced.
+Import declarations are used to import entities from other modules and provide bindings for them in the current module.
- *ExternalImportDeclaration:*
- `import` *Identifier* `=` *ExternalModuleReference* `;`
+An import declaration of the form
- *ExternalModuleReference:*
- `require` `(` *StringLiteral* `)`
+```TypeScript
+import * as m from "mod";
+```
-The string literal specified in an *ExternalModuleReference* is interpreted as an external module name (section [11.2.1](#11.2.1)).
+imports 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).
-An external import declaration introduces a local identifier that references a given external module. The local identifier becomes an alias for, and is classified exactly like, the entity or entities exported from the referenced external module. Specifically, if the referenced external module contains no export assignment the identifier is classified as a module, and if the referenced external module contains an export assignment the identifier is classified exactly like the entity or entities named in the export assignment.
+An import declaration of the form
-### 11.2.3 Export Declarations
+```TypeScript
+import { x, y, z } from "mod";
+```
-An external module that contains no export assignment (section [11.2.4](#11.2.4)) exports an entity classified as a module. Similarly to an internal module, export declarations (section [10.4](#10.4)) in the external module are used to declare the members of this entity.
+imports 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:
-Unlike a non-instantiated internal module (section [10.1](#10.1)), an external module containing only interface types and non-instantiated internal modules still has a module instance associated with it, albeit one with no members.
+```TypeScript
+import { x as a, y as b } from "mod";
+```
-If an external module contains an export assignment it is an error for the external module to also contain export declarations. The two types of exports are mutually exclusive.
+An import declaration of the form
-### 11.2.4 Export Assignments
+```TypeScript
+import d from "mod";
+```
-An export assignment designates a module member as the entity to be exported in place of the external module itself.
+is exactly equivalent to the import declaration
+
+```TypeScript
+import { default as d } from "mod";
+```
+
+An import declaration of the form
+
+```TypeScript
+import "mod";
+```
+
+imports the given module without creating any local bindings (this is useful only if the imported module has side effects).
+
+### 11.3.3 Import Require Declarations
+
+Import require declarations exist for backward compatibility with earlier versions of TypeScript.
+
+ *ImportRequireDeclaration:*
+ `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;`
+
+An 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.
+
+An import require declaration of the form
+
+```TypeScript
+import m = require("mod");
+```
+
+is equivalent to the ECMAScript 6 import declaration
+
+```TypeScript
+import * as m from "mod";
+```
+
+provided the referenced module contains no export assignment.
+
+### 11.3.4 Export Declarations
+
+An 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)).
+
+#### 11.3.4.1 Export Modifiers
+
+In the body of a module, a declaration can export the declared entity by including an `export` modifier.
+
+ *ExportImplementationElement:*
+ `export` *VariableStatement*
+ `export` *LexicalDeclaration*
+ `export` *FunctionDeclaration*
+ `export` *GeneratorDeclaration*
+ `export` *ClassDeclaration*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *EnumDeclaration*
+ `export` *NamespaceDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
+
+ *ExportDeclarationElement:*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
+
+In 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
+
+```TypeScript
+export function point(x: number, y: number) {
+ return { x, y };
+}
+```
+
+introduces a local name `point` and an exported name `point` that both reference the function.
+
+#### 11.3.4.2 Export Default Declarations
+
+Export default declarations provide short-hand syntax for exporting an entity named `default`.
+
+ *ExportDefaultImplementationElement:*
+ `export` `default` *FunctionDeclaration*
+ `export` `default` *GeneratorDeclaration*
+ `export` `default` *ClassDeclaration*
+ `export` `default` *AssignmentExpression* `;`
+
+ *ExportDefaultDeclarationElement:*
+ `export` `default` *AmbientFunctionDeclaration*
+ `export` `default` *AmbientClassDeclaration*
+ `export` `default` *IdentifierReference* `;`
+
+An *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
+
+```TypeScript
+export default function point(x: number, y: number) {
+ return { x, y };
+}
+```
+
+introduces a local name `point` and an exported name `default` that both reference the function. The declaration is effectively equivalent to
+
+```TypeScript
+function point(x: number, y: number) {
+ return { x, y };
+}
+
+export default point;
+```
+
+which again is equivalent to
+
+```TypeScript
+function point(x: number, y: number) {
+ return { x, y };
+}
+
+export { point as default };
+```
+
+An *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
+
+```TypeScript
+interface Point {
+ x: number;
+ y: number;
+}
+
+function Point(x: number, y: number): Point {
+ return { x, y };
+}
+
+export default Point;
+```
+
+introduce a local name `Point` and an exported name `default`, both with a value and a type meaning.
+
+An *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
+
+```TypeScript
+export default "hello";
+```
+
+introduces an exported value named `default` of type string.
+
+#### 11.3.4.3 Export List Declarations
+
+An export list declaration exports one or more entities from the current module or a specified module.
+
+ *ExportListDeclaration:*
+ `export` `*` *FromClause* `;`
+ `export` *ExportClause* *FromClause* `;`
+ `export` *ExportClause* `;`
+
+An *ExportListDeclaration* without a *FromClause* exports entities from the current module. In a declaration of the form
+
+```TypeScript
+export { x };
+```
+
+the 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.
+
+An *ExportListDeclaration* with a *FromClause* re-exports entities from a specified module. In a declaration of the form
+
+```TypeScript
+export { x } from "mod";
+```
+
+the 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`.
+
+The *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
+
+```TypeScript
+export { x, y as b, z as c };
+```
+
+introduces 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.
+
+An *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.
+
+```TypeScript
+export * from "mod";
+```
+
+Explicitly exported members take precedence over members re-exported using export star declarations, as described in the following section.
+
+#### 11.3.4.4 Export Member Set
+
+The ***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:
+
+* Add *M* to *P*.
+* Add to *E* each member in the export declaration space of *M* with a name that isn't already in *E*.
+* For each export star declaration in *M*, in order of declaration, process the referenced module if it is not already in *P*.
+
+A 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.
+
+If 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.
+
+### 11.3.5 Export Assignments
+
+Export 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.
*ExportAssignment:*
- `export` `=` *Identifier* `;`
+ `export` `=` *IdentifierReference* `;`
-When an external module containing an export assignment is imported, the local alias introduced by the external import declaration takes on all meanings of the identifier named in the export assignment.
+A 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.
-It is an error for an external module to contain more than one export assignment.
+A 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.
Assume the following example resides in the file 'point.ts':
@@ -5319,7 +5808,7 @@ class Point {
}
```
-When 'point.ts' is imported in another external module, the import alias references the exported class and can be used both as a type and as a constructor function:
+When 'point.ts' is imported in another module, the import alias references the exported class and can be used both as a type and as a constructor function:
```TypeScript
import Pt = require("./point");
@@ -5330,11 +5819,11 @@ var p2 = Pt.origin;
Note that there is no requirement that the import alias use the same name as the exported entity.
-### 11.2.5 CommonJS Modules
+### 11.3.6 CommonJS Modules
-The CommonJS Modules definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a 'require' function that can be used to synchronously load other external modules to obtain their singleton module instance, as well as an 'exports' variable to which a module can add properties to define its external API.
+The [CommonJS Modules](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.
-The 'main' and 'log' example from section [11.2](#11.2) above generates the following JavaScript code when compiled for the CommonJS Modules pattern:
+The 'main' and 'log' example from section [11.3](#11.3) above generates the following JavaScript code when compiled for the CommonJS Modules pattern:
File main.js:
@@ -5351,7 +5840,7 @@ exports.message = function(s) {
}
```
-An external import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName* or *TypeQueryExpression*, nothing is emitted.
+A 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.
An example:
@@ -5392,9 +5881,9 @@ the emitted JavaScript would have no dependency on the 'geometry' module and wou
var p = { x: 10, y: 20 };
```
-### 11.2.6 AMD Modules
+### 11.3.7 AMD Modules
-The Asynchronous Module Definition (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global 'define' function taking an array of dependencies, specified as external module names, and a callback function containing the module body. The global 'define' function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module's dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array.
+The [Asynchronous Module Definition](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.
The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern.
@@ -5416,31 +5905,40 @@ define(["require", "exports"], function(require, exports) {
}
```
-The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported external modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *ModuleName*, no dependency is generated for that module.
+The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported 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.
# 12 Ambients
-Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or modules, ambient declarations provide type information for entities that exist "ambiently" and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag.
+Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or 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.
## 12.1 Ambient Declarations
-Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, internal modules, or external modules.
+Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, namespaces, or modules.
*AmbientDeclaration:*
`declare` *AmbientVariableDeclaration*
`declare` *AmbientFunctionDeclaration*
`declare` *AmbientClassDeclaration*
`declare` *AmbientEnumDeclaration*
- `declare` *AmbientModuleDeclaration*
+ `declare` *AmbientNamespaceDeclaration*
### 12.1.1 Ambient Variable Declarations
An ambient variable declaration introduces a variable in the containing declaration space.
*AmbientVariableDeclaration:*
- `var` *Identifier* *TypeAnnotationopt* `;`
+ `var` *AmbientBindingList* `;`
+ `let` *AmbientBindingList* `;`
+ `const` *AmbientBindingList* `;`
+
+ *AmbientBindingList:*
+ *AmbientBinding*
+ *AmbientBindingList* `,` *AmbientBinding*
+
+ *AmbientBinding:*
+ *BindingIdentifier* *TypeAnnotationopt*
An ambient variable declaration may optionally include a type annotation. If no type annotation is present, the variable is assumed to have type Any.
@@ -5451,18 +5949,18 @@ An ambient variable declaration does not permit an initializer expression to be
An ambient function declaration introduces a function in the containing declaration space.
*AmbientFunctionDeclaration:*
- `function` *Identifier* *CallSignature* `;`
+ `function` *BindingIdentifier* *CallSignature* `;`
-Ambient 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.10.2](#3.10.2)) or differ only in their return types.
+Ambient 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.
Ambient function declarations cannot specify a function bodies and do not permit default parameter values.
### 12.1.3 Ambient Class Declarations
-An ambient class declaration declares a class instance type and a constructor function in the containing module.
+An ambient class declaration declares a class instance type and a constructor function in the containing declaration space.
*AmbientClassDeclaration:*
- `class` *Identifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}`
+ `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}`
*AmbientClassBody:*
*AmbientClassBodyElementsopt*
@@ -5497,55 +5995,44 @@ Ambient enum declarations differ from non-ambient enum declarations in two ways:
Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations.
-### 12.1.5 Ambient Module Declarations
+### 12.1.5 Ambient Namespace Declarations
-An ambient module declaration declares an internal module.
+An ambient namespace declaration declares a namespace.
- *AmbientModuleDeclaration:*
- `module` *IdentifierPath* `{` *AmbientModuleBody* `}`
+ *AmbientNamespaceDeclaration:*
+ `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}`
- *AmbientModuleBody:*
- *AmbientModuleElementsopt*
+ *AmbientNamespaceBody:*
+ *AmbientNamespaceElementsopt*
- *AmbientModuleElements:*
- *AmbientModuleElement*
- *AmbientModuleElements* *AmbientModuleElement*
+ *AmbientNamespaceElements:*
+ *AmbientNamespaceElement*
+ *AmbientNamespaceElements* *AmbientNamespaceElement*
- *AmbientModuleElement:*
+ *AmbientNamespaceElement:*
`export`*opt* *AmbientVariableDeclaration*
+ `export`*opt* *AmbientLexicalDeclaration*
`export`*opt* *AmbientFunctionDeclaration*
`export`*opt* *AmbientClassDeclaration*
`export`*opt* *InterfaceDeclaration*
`export`*opt* *AmbientEnumDeclaration*
- `export`*opt* *AmbientModuleDeclaration*
- `export`*opt* *ImportDeclaration*
+ `export`*opt* *AmbientNamespaceDeclaration*
+ `export`*opt* *ImportAliasDeclaration*
-Except for *ImportDeclarations*, *AmbientModuleElements* always declare exported entities regardless of whether they include the optional `export` modifier.
+Except for *ImportAliasDeclarations*, *AmbientNamespaceElements* always declare exported entities regardless of whether they include the optional `export` modifier.
-## 12.2 Ambient External Module Declarations
+## 12.2 Ambient Module Declarations
-An *AmbientExternalModuleDeclaration* declares an external module. This type of declaration is permitted only at the top level in a source file that contributes to the global module (section [11.1](#11.1)). The *StringLiteral* must specify a top-level external module name. Relative external module names are not permitted.
+An *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.
- *AmbientExternalModuleDeclaration:*
- `declare` `module` *StringLiteral* `{` *AmbientExternalModuleBody* `}`
+ *AmbientModuleDeclaration:*
+ `declare` `module` *StringLiteral* `{` *DeclarationModule* `}`
- *AmbientExternalModuleBody:*
- *AmbientExternalModuleElementsopt*
+An *ImportRequireDeclaration* in an *AmbientModuleDeclaration* may reference other modules only through top-level module names. Relative module names are not permitted.
- *AmbientExternalModuleElements:*
- *AmbientExternalModuleElement*
- *AmbientExternalModuleElements* *AmbientExternalModuleElement*
+If 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.
- *AmbientExternalModuleElement:*
- *AmbientModuleElement*
- *ExportAssignment*
- `export`*opt* *ExternalImportDeclaration*
-
-An *ExternalImportDeclaration* in an *AmbientExternalModuleDeclaration* may reference other external modules only through top-level external module names. Relative external module names are not permitted.
-
-If an ambient external module declaration includes an export assignment, it is an error for any of the declarations within the module to specify an `export` modifier. If an ambient external module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier.
-
-Ambient external modules are "open-ended" and ambient external module declarations with the same string literal name contribute to a single external module. For example, the following two declarations of an external module 'io' might be located in separate source files.
+Ambient 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.
```TypeScript
declare module "io" {
@@ -5570,7 +6057,7 @@ declare module "io" {
# A Grammar
-This 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 Language Specification (specifically, the ECMA-262 Standard, 5th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar.
+This 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 Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar.
## A.1 Types
@@ -5582,7 +6069,7 @@ This appendix contains a summary of the grammar found in the main document. As d
*TypeParameterList* `,` *TypeParameter*
*TypeParameter:*
- *Identifier* *Constraintopt*
+ *BindingIdentifier* *Constraintopt*
*Constraint:*
`extends` *Type*
@@ -5598,13 +6085,17 @@ This appendix contains a summary of the grammar found in the main document. As d
*Type*
*Type:*
- *PrimaryOrUnionType*
+ *UnionOrIntersectionOrPrimaryType*
*FunctionType*
*ConstructorType*
- *PrimaryOrUnionType:*
- *PrimaryType*
- *UnionType*
+ *UnionOrIntersectionOrPrimaryType:*
+ *UnionType*
+ *IntersectionOrPrimaryType*
+
+ *IntersectionOrPrimaryType:*
+ *IntersectionType*
+ *PrimaryType*
*PrimaryType:*
*ParenthesizedType*
@@ -5623,28 +6114,31 @@ This appendix contains a summary of the grammar found in the main document. As d
`number`
`boolean`
`string`
+ `symbol`
`void`
*TypeReference:*
*TypeName* *[no LineTerminator here]* *TypeArgumentsopt*
*TypeName:*
- *Identifier*
- *ModuleName* `.` *Identifier*
+ *IdentifierReference*
+ *NamespaceName* `.` *IdentifierReference*
- *ModuleName:*
- *Identifier*
- *ModuleName* `.` *Identifier*
+ *NamespaceName:*
+ *IdentifierReference*
+ *NamespaceName* `.` *IdentifierReference*
*ObjectType:*
`{` *TypeBodyopt* `}`
*TypeBody:*
- *TypeMemberList* `;`*opt*
+ *TypeMemberList* `;`*opt*
+ *TypeMemberList* `,`*opt*
*TypeMemberList:*
*TypeMember*
- *TypeMemberList* `;` *TypeMember*
+ *TypeMemberList* `;` *TypeMember*
+ *TypeMemberList* `,` *TypeMember*
*TypeMember:*
*PropertySignature*
@@ -5667,7 +6161,10 @@ This appendix contains a summary of the grammar found in the main document. As d
*Type*
*UnionType:*
- *PrimaryOrUnionType* `|` *PrimaryType*
+ *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType*
+
+ *IntersectionType:*
+ *IntersectionOrPrimaryType* `&` *PrimaryType*
*FunctionType:*
*TypeParametersopt* `(` *ParameterListopt* `)` `=>` *Type*
@@ -5679,7 +6176,7 @@ This appendix contains a summary of the grammar found in the main document. As d
`typeof` *TypeQueryExpression*
*TypeQueryExpression:*
- *Identifier*
+ *IdentifierReference*
*TypeQueryExpression* `.` *IdentifierName*
*PropertySignature:*
@@ -5690,6 +6187,9 @@ This appendix contains a summary of the grammar found in the main document. As d
*StringLiteral*
*NumericLiteral*
+ *TypeAnnotation:*
+ `:` *Type*
+
*CallSignature:*
*TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt*
@@ -5707,42 +6207,48 @@ This appendix contains a summary of the grammar found in the main document. As d
*RequiredParameterList* `,` *RequiredParameter*
*RequiredParameter:*
- *AccessibilityModifieropt* *Identifier* *TypeAnnotationopt*
- *Identifier* `:` *StringLiteral*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt*
+ *BindingIdentifier* `:` *StringLiteral*
*AccessibilityModifier:*
`public`
`private`
`protected`
+ *BindingIdentifierOrPattern:*
+ *BindingIdentifier*
+ *BindingPattern*
+
*OptionalParameterList:*
*OptionalParameter*
*OptionalParameterList* `,` *OptionalParameter*
*OptionalParameter:*
- *AccessibilityModifieropt* *Identifier* `?` *TypeAnnotationopt*
- *AccessibilityModifieropt* *Identifier* *TypeAnnotationopt* *Initialiser*
- *Identifier* `?` `:` *StringLiteral*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* `?` *TypeAnnotationopt*
+ *AccessibilityModifieropt* *BindingIdentifierOrPattern* *TypeAnnotationopt* *Initializer*
+ *BindingIdentifier* `?` `:` *StringLiteral*
*RestParameter:*
- `...` *Identifier* *TypeAnnotationopt*
+ `...` *BindingIdentifier* *TypeAnnotationopt*
*ConstructSignature:*
`new` *TypeParametersopt* `(` *ParameterListopt* `)` *TypeAnnotationopt*
*IndexSignature:*
- `[` *Identifier* `:` `string` `]` *TypeAnnotation*
- `[` *Identifier* `:` `number` `]` *TypeAnnotation*
+ `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation*
+ `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation*
*MethodSignature:*
*PropertyName* `?`*opt* *CallSignature*
*TypeAliasDeclaration:*
- `type` *Identifier* `=` *Type* `;`
+ `type` *BindingIdentifier* *TypeParametersopt* `=` *Type* `;`
## A.2 Expressions
- *PropertyAssignment:* *( Modified )*
+ *PropertyDefinition:* *( Modified )*
+ *IdentifierReference*
+ *CoverInitializedName*
*PropertyName* `:` *AssignmentExpression*
*PropertyName* *CallSignature* `{` *FunctionBody* `}`
*GetAccessor*
@@ -5752,36 +6258,13 @@ This appendix contains a summary of the grammar found in the main document. As d
`get` *PropertyName* `(` `)` *TypeAnnotationopt* `{` *FunctionBody* `}`
*SetAccessor:*
- `set` *PropertyName* `(` *Identifier* *TypeAnnotationopt* `)` `{` *FunctionBody* `}`
-
- *ElementList:* *( Modified )*
- *Elisionopt* *AssignmentExpression*
- *Elisionopt* *SpreadElement*
- *ElementList* `,` *Elisionopt* *AssignmentExpression*
- *ElementList* `,` *Elisionopt* *SpreadElement*
-
- *SpreadElement:*
- `...` *AssignmentExpression*
-
- *CallExpression:* *( Modified )*
- …
- `super` `(` *ArgumentListopt* `)`
- `super` `.` *IdentifierName*
+ `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotationopt* `)` `{` *FunctionBody* `}`
*FunctionExpression:* *( Modified )*
- `function` *Identifieropt* *CallSignature* `{` *FunctionBody* `}`
+ `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}`
- *AssignmentExpression:* *( Modified )*
- …
- *ArrowFunctionExpression*
-
- *ArrowFunctionExpression:*
- *ArrowFormalParameters* `=>` *Block*
- *ArrowFormalParameters* `=>` *AssignmentExpression*
-
- *ArrowFormalParameters:*
- *CallSignature*
- *Identifier*
+ *ArrowFormalParameters:* *( Modified )*
+ *CallSignature*
*Arguments:* *( Modified )*
*TypeArgumentsopt* `(` *ArgumentListopt* `)`
@@ -5792,71 +6275,42 @@ This appendix contains a summary of the grammar found in the main document. As d
## A.3 Statements
+ *Declaration:* *( Modified )*
+ …
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+
*VariableDeclaration:* *( Modified )*
*SimpleVariableDeclaration*
*DestructuringVariableDeclaration*
*SimpleVariableDeclaration:*
- *Identifier* *TypeAnnotationopt* *Initialiseropt*
-
- *TypeAnnotation:*
- `:` *Type*
+ *BindingIdentifier* *TypeAnnotationopt* *Initializeropt*
*DestructuringVariableDeclaration:*
- *BindingPattern* *TypeAnnotationopt* *Initialiser*
+ *BindingPattern* *TypeAnnotationopt* *Initializer*
- *BindingPattern:*
- *ObjectBindingPattern*
- *ArrayBindingPattern*
+ *LexicalBinding:* *( Modified )*
+ *SimpleLexicalBinding*
+ *DestructuringLexicalBinding*
- *ObjectBindingPattern:*
- `{` `}`
- `{` *BindingPropertyList* `,`*opt* `}`
+ *SimpleLexicalBinding:*
+ *BindingIdentifier* *TypeAnnotationopt* *Initializeropt*
- *BindingPropertyList:*
- *BindingProperty*
- *BindingPropertyList* `,` *BindingProperty*
-
- *BindingProperty:*
- *Identifier* *Initialiseropt*
- *PropertyName* `:` *Identifier* *Initialiseropt*
- *PropertyName* `:` *BindingPattern* *Initialiseropt*
-
- *ArrayBindingPattern:*
- `[` *Elisionopt* *BindingRestElementopt* `]`
- `[` *BindingElementList* `]`
- `[` *BindingElementList* `,` *Elisionopt* *BindingRestElementopt* `]`
-
- *BindingElementList:*
- *Elisionopt* *BindingElement*
- *BindingElementList* `,` *Elisionopt* *BindingElement*
-
- *BindingElement:*
- *Identifier* *Initialiseropt*
- *BindingPattern* *Initialiseropt*
-
- *BindingRestElement:*
- `...` *Identifier*
+ *DestructuringLexicalBinding:*
+ *BindingPattern* *TypeAnnotationopt* *Initializeropt*
## A.4 Functions
*FunctionDeclaration:* *( Modified )*
- *FunctionOverloadsopt* *FunctionImplementation*
-
- *FunctionOverloads:*
- *FunctionOverload*
- *FunctionOverloads* *FunctionOverload*
-
- *FunctionOverload:*
- `function` *Identifier* *CallSignature* `;`
-
- *FunctionImplementation:*
- `function` *Identifier* *CallSignature* `{` *FunctionBody* `}`
+ `function` *BindingIdentifieropt* *CallSignature* `{` *FunctionBody* `}`
+ `function` *BindingIdentifieropt* *CallSignature* `;`
## A.5 Interfaces
*InterfaceDeclaration:*
- `interface` *Identifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType*
+ `interface` *BindingIdentifier* *TypeParametersopt* *InterfaceExtendsClauseopt* *ObjectType*
*InterfaceExtendsClause:*
`extends` *ClassOrInterfaceTypeList*
@@ -5870,10 +6324,10 @@ This appendix contains a summary of the grammar found in the main document. As d
## A.6 Classes
- *ClassDeclaration:*
- `class` *Identifier* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}`
+ *ClassDeclaration:* *( Modified )*
+ `class` *BindingIdentifieropt* *TypeParametersopt* *ClassHeritage* `{` *ClassBody* `}`
- *ClassHeritage:*
+ *ClassHeritage:* *( Modified )*
*ClassExtendsClauseopt* *ImplementsClauseopt*
*ClassExtendsClause:*
@@ -5885,52 +6339,27 @@ This appendix contains a summary of the grammar found in the main document. As d
*ImplementsClause:*
`implements` *ClassOrInterfaceTypeList*
- *ClassBody:*
- *ClassElementsopt*
-
- *ClassElements:*
- *ClassElement*
- *ClassElements* *ClassElement*
-
- *ClassElement:*
+ *ClassElement:* *( Modified )*
*ConstructorDeclaration*
*PropertyMemberDeclaration*
*IndexMemberDeclaration*
*ConstructorDeclaration:*
- *ConstructorOverloadsopt* *ConstructorImplementation*
-
- *ConstructorOverloads:*
- *ConstructorOverload*
- *ConstructorOverloads* *ConstructorOverload*
-
- *ConstructorOverload:*
+ *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}`
*AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `;`
- *ConstructorImplementation:*
- *AccessibilityModifieropt* `constructor` `(` *ParameterListopt* `)` `{` *FunctionBody* `}`
-
*PropertyMemberDeclaration:*
*MemberVariableDeclaration*
*MemberFunctionDeclaration*
*MemberAccessorDeclaration*
*MemberVariableDeclaration:*
- *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initialiseropt* `;`
+ *AccessibilityModifieropt* `static`*opt* *PropertyName* *TypeAnnotationopt* *Initializeropt* `;`
*MemberFunctionDeclaration:*
- *MemberFunctionOverloadsopt* *MemberFunctionImplementation*
-
- *MemberFunctionOverloads*:
- *MemberFunctionOverload*
- *MemberFunctionOverloads* *MemberFunctionOverload*
-
- *MemberFunctionOverload*:
+ *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
*AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;`
- *MemberFunctionImplementation:*
- *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
-
*MemberAccessorDeclaration:*
*AccessibilityModifieropt* `static`*opt* *GetAccessor*
*AccessibilityModifieropt* `static`*opt* *SetAccessor*
@@ -5941,7 +6370,7 @@ This appendix contains a summary of the grammar found in the main document. As d
## A.7 Enums
*EnumDeclaration:*
- `const`*opt* `enum` *Identifier* `{` *EnumBodyopt* `}`
+ `const`*opt* `enum` *BindingIdentifier* `{` *EnumBodyopt* `}`
*EnumBody:*
*EnumMemberList* `,`*opt*
@@ -5957,84 +6386,185 @@ This appendix contains a summary of the grammar found in the main document. As d
*EnumValue:*
*AssignmentExpression*
-## A.8 Internal Modules
+## A.8 Namespaces
- *ModuleDeclaration:*
- `module` *IdentifierPath* `{` *ModuleBody* `}`
+ *NamespaceDeclaration:*
+ `namespace` *IdentifierPath* `{` *NamespaceBody* `}`
*IdentifierPath:*
- *Identifier*
- *IdentifierPath* `.` *Identifier*
+ *BindingIdentifier*
+ *IdentifierPath* `.` *BindingIdentifier*
- *ModuleBody:*
- *ModuleElementsopt*
+ *NamespaceBody:*
+ *NamespaceElementsopt*
- *ModuleElements:*
- *ModuleElement*
- *ModuleElements* *ModuleElement*
+ *NamespaceElements:*
+ *NamespaceElement*
+ *NamespaceElements* *NamespaceElement*
- *ModuleElement:*
+ *NamespaceElement:*
*Statement*
- `export`*opt* *VariableDeclaration*
- `export`*opt* *FunctionDeclaration*
- `export`*opt* *ClassDeclaration*
- `export`*opt* *InterfaceDeclaration*
- `export`*opt* *TypeAliasDeclaration*
- `export`*opt* *EnumDeclaration*
- `export`*opt* *ModuleDeclaration*
- `export`*opt* *ImportDeclaration*
- `export`*opt* *AmbientDeclaration*
+ *LexicalDeclaration*
+ *FunctionDeclaration*
+ *GeneratorDeclaration*
+ *ClassDeclaration*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+ *NamespaceDeclaration
+ AmbientDeclaration
+ ImportAliasDeclaration
+ ExportNamespaceElement*
- *ImportDeclaration:*
- `import` *Identifier* `=` *EntityName* `;`
+ *ExportNamespaceElement:*
+ `export` *VariableStatement*
+ `export` *LexicalDeclaration*
+ `export` *FunctionDeclaration*
+ `export` *GeneratorDeclaration*
+ `export` *ClassDeclaration*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *EnumDeclaration*
+ `export` *NamespaceDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
+
+ *ImportAliasDeclaration:*
+ `import` *BindingIdentifier* `=` *EntityName* `;`
*EntityName:*
- *ModuleName*
- *ModuleName* `.` *Identifier*
+ *NamespaceName*
+ *NamespaceName* `.` *IdentifierReference*
-## A.9 Source Files and External Modules
+## A.9 Scripts and Modules
*SourceFile:*
*ImplementationSourceFile*
*DeclarationSourceFile*
*ImplementationSourceFile:*
- *ImplementationElementsopt*
-
- *ImplementationElements:*
- *ImplementationElement*
- *ImplementationElements* *ImplementationElement*
-
- *ImplementationElement:*
- *ModuleElement*
- *ExportAssignment*
- *AmbientExternalModuleDeclaration*
- `export`*opt* *ExternalImportDeclaration*
+ *ImplementationScript*
+ *ImplementationModule*
*DeclarationSourceFile:*
- *DeclarationElementsopt*
+ *DeclarationScript*
+ *DeclarationModule*
- *DeclarationElements:*
+ *ImplementationScript:*
+ *ImplementationScriptElementsopt*
+
+ *ImplementationScriptElements:*
+ *ImplementationScriptElement*
+ *ImplementationScriptElements* *ImplementationScriptElement*
+
+ *ImplementationScriptElement:*
+ *ImplementationElement*
+ *AmbientModuleDeclaration*
+
+ *ImplementationElement:*
+ *Statement*
+ *LexicalDeclaration*
+ *FunctionDeclaration*
+ *GeneratorDeclaration*
+ *ClassDeclaration*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *EnumDeclaration*
+ *NamespaceDeclaration*
+ *AmbientDeclaration*
+ *ImportAliasDeclaration*
+
+ *DeclarationScript:*
+ *DeclarationScriptElementsopt*
+
+ *DeclarationScriptElements:*
+ *DeclarationScriptElement*
+ *DeclarationScriptElements* *DeclarationScriptElement*
+
+ *DeclarationScriptElement:*
*DeclarationElement*
- *DeclarationElements* *DeclarationElement*
+ *AmbientModuleDeclaration*
*DeclarationElement:*
- *ExportAssignment*
- *AmbientExternalModuleDeclaration*
- `export`*opt* *InterfaceDeclaration*
- `export`*opt* *TypeAliasDeclaration*
- `export`*opt* *ImportDeclaration*
- `export`*opt* *AmbientDeclaration*
- `export`*opt* *ExternalImportDeclaration*
+ *InterfaceDeclaration*
+ *TypeAliasDeclaration*
+ *NamespaceDeclaration*
+ *AmbientDeclaration*
+ *ImportAliasDeclaration*
- *ExternalImportDeclaration:*
- `import` *Identifier* `=` *ExternalModuleReference* `;`
+ *ImplementationModule:*
+ *ImplementationModuleElementsopt*
- *ExternalModuleReference:*
- `require` `(` *StringLiteral* `)`
+ *ImplementationModuleElements:*
+ *ImplementationModuleElement*
+ *ImplementationModuleElements* *ImplementationModuleElement*
+
+ *ImplementationModuleElement:*
+ *ImplementationElement*
+ *ImportDeclaration*
+ *ImportAliasDeclaration*
+ *ImportRequireDeclaration*
+ *ExportImplementationElement*
+ *ExportDefaultImplementationElement*
+ *ExportListDeclaration*
+ *ExportAssignment*
+
+ *DeclarationModule:*
+ *DeclarationModuleElementsopt*
+
+ *DeclarationModuleElements:*
+ *DeclarationModuleElement*
+ *DeclarationModuleElements* *DeclarationModuleElement*
+
+ *DeclarationModuleElement:*
+ *DeclarationElement*
+ *ImportDeclaration*
+ *ImportAliasDeclaration*
+ *ExportDeclarationElement*
+ *ExportDefaultDeclarationElement*
+ *ExportListDeclaration*
+ *ExportAssignment*
+
+ *ImportRequireDeclaration:*
+ `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;`
+
+ *ExportImplementationElement:*
+ `export` *VariableStatement*
+ `export` *LexicalDeclaration*
+ `export` *FunctionDeclaration*
+ `export` *GeneratorDeclaration*
+ `export` *ClassDeclaration*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *EnumDeclaration*
+ `export` *NamespaceDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
+
+ *ExportDeclarationElement:*
+ `export` *InterfaceDeclaration*
+ `export` *TypeAliasDeclaration*
+ `export` *AmbientDeclaration*
+ `export` *ImportAliasDeclaration*
+
+ *ExportDefaultImplementationElement:*
+ `export` `default` *FunctionDeclaration*
+ `export` `default` *GeneratorDeclaration*
+ `export` `default` *ClassDeclaration*
+ `export` `default` *AssignmentExpression* `;`
+
+ *ExportDefaultDeclarationElement:*
+ `export` `default` *AmbientFunctionDeclaration*
+ `export` `default` *AmbientClassDeclaration*
+ `export` `default` *IdentifierReference* `;`
+
+ *ExportListDeclaration:*
+ `export` `*` *FromClause* `;`
+ `export` *ExportClause* *FromClause* `;`
+ `export` *ExportClause* `;`
*ExportAssignment:*
- `export` `=` *Identifier* `;`
+ `export` `=` *IdentifierReference* `;`
## A.10 Ambients
@@ -6043,16 +6573,25 @@ This appendix contains a summary of the grammar found in the main document. As d
`declare` *AmbientFunctionDeclaration*
`declare` *AmbientClassDeclaration*
`declare` *AmbientEnumDeclaration*
- `declare` *AmbientModuleDeclaration*
+ `declare` *AmbientNamespaceDeclaration*
*AmbientVariableDeclaration:*
- `var` *Identifier* *TypeAnnotationopt* `;`
+ `var` *AmbientBindingList* `;`
+ `let` *AmbientBindingList* `;`
+ `const` *AmbientBindingList* `;`
+
+ *AmbientBindingList:*
+ *AmbientBinding*
+ *AmbientBindingList* `,` *AmbientBinding*
+
+ *AmbientBinding:*
+ *BindingIdentifier* *TypeAnnotationopt*
*AmbientFunctionDeclaration:*
- `function` *Identifier* *CallSignature* `;`
+ `function` *BindingIdentifier* *CallSignature* `;`
*AmbientClassDeclaration:*
- `class` *Identifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}`
+ `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}`
*AmbientClassBody:*
*AmbientClassBodyElementsopt*
@@ -6076,37 +6615,26 @@ This appendix contains a summary of the grammar found in the main document. As d
*AmbientEnumDeclaration:*
*EnumDeclaration*
- *AmbientModuleDeclaration:*
- `module` *IdentifierPath* `{` *AmbientModuleBody* `}`
+ *AmbientNamespaceDeclaration:*
+ `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}`
- *AmbientModuleBody:*
- *AmbientModuleElementsopt*
+ *AmbientNamespaceBody:*
+ *AmbientNamespaceElementsopt*
- *AmbientModuleElements:*
- *AmbientModuleElement*
- *AmbientModuleElements* *AmbientModuleElement*
+ *AmbientNamespaceElements:*
+ *AmbientNamespaceElement*
+ *AmbientNamespaceElements* *AmbientNamespaceElement*
- *AmbientModuleElement:*
+ *AmbientNamespaceElement:*
`export`*opt* *AmbientVariableDeclaration*
+ `export`*opt* *AmbientLexicalDeclaration*
`export`*opt* *AmbientFunctionDeclaration*
`export`*opt* *AmbientClassDeclaration*
`export`*opt* *InterfaceDeclaration*
`export`*opt* *AmbientEnumDeclaration*
- `export`*opt* *AmbientModuleDeclaration*
- `export`*opt* *ImportDeclaration*
+ `export`*opt* *AmbientNamespaceDeclaration*
+ `export`*opt* *ImportAliasDeclaration*
- *AmbientExternalModuleDeclaration:*
- `declare` `module` *StringLiteral* `{` *AmbientExternalModuleBody* `}`
-
- *AmbientExternalModuleBody:*
- *AmbientExternalModuleElementsopt*
-
- *AmbientExternalModuleElements:*
- *AmbientExternalModuleElement*
- *AmbientExternalModuleElements* *AmbientExternalModuleElement*
-
- *AmbientExternalModuleElement:*
- *AmbientModuleElement*
- *ExportAssignment*
- `export`*opt* *ExternalImportDeclaration*
+ *AmbientModuleDeclaration:*
+ `declare` `module` *StringLiteral* `{` *DeclarationModule* `}`
diff --git a/bin/lib.core.d.ts b/lib/lib.core.d.ts
similarity index 100%
rename from bin/lib.core.d.ts
rename to lib/lib.core.d.ts
diff --git a/bin/lib.core.es6.d.ts b/lib/lib.core.es6.d.ts
similarity index 100%
rename from bin/lib.core.es6.d.ts
rename to lib/lib.core.es6.d.ts
diff --git a/bin/lib.d.ts b/lib/lib.d.ts
similarity index 100%
rename from bin/lib.d.ts
rename to lib/lib.d.ts
diff --git a/bin/lib.dom.d.ts b/lib/lib.dom.d.ts
similarity index 100%
rename from bin/lib.dom.d.ts
rename to lib/lib.dom.d.ts
diff --git a/bin/lib.es6.d.ts b/lib/lib.es6.d.ts
similarity index 100%
rename from bin/lib.es6.d.ts
rename to lib/lib.es6.d.ts
diff --git a/bin/lib.scriptHost.d.ts b/lib/lib.scriptHost.d.ts
similarity index 100%
rename from bin/lib.scriptHost.d.ts
rename to lib/lib.scriptHost.d.ts
diff --git a/bin/lib.webworker.d.ts b/lib/lib.webworker.d.ts
similarity index 100%
rename from bin/lib.webworker.d.ts
rename to lib/lib.webworker.d.ts
diff --git a/bin/tsc.js b/lib/tsc.js
similarity index 100%
rename from bin/tsc.js
rename to lib/tsc.js
diff --git a/bin/tsserver.js b/lib/tsserver.js
similarity index 100%
rename from bin/tsserver.js
rename to lib/tsserver.js
diff --git a/bin/typescript.d.ts b/lib/typescript.d.ts
similarity index 100%
rename from bin/typescript.d.ts
rename to lib/typescript.d.ts
diff --git a/bin/typescript.js b/lib/typescript.js
similarity index 100%
rename from bin/typescript.js
rename to lib/typescript.js
diff --git a/bin/typescriptServices.d.ts b/lib/typescriptServices.d.ts
similarity index 97%
rename from bin/typescriptServices.d.ts
rename to lib/typescriptServices.d.ts
index 9840a5e688f..7b4eaea9e16 100644
--- a/bin/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -1450,6 +1450,7 @@ declare namespace ts {
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
+ function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant: ts.LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
declare namespace ts {
function getDefaultLibFileName(options: CompilerOptions): string;
diff --git a/bin/typescriptServices.js b/lib/typescriptServices.js
similarity index 100%
rename from bin/typescriptServices.js
rename to lib/typescriptServices.js
diff --git a/package.json b/package.json
index c8b30f9de1c..52dabc79f6e 100644
--- a/package.json
+++ b/package.json
@@ -19,8 +19,7 @@
"type": "git",
"url": "https://github.com/Microsoft/TypeScript.git"
},
- "preferGlobal": true,
- "main": "./bin/typescript.js",
+ "main": "./lib/typescript.js",
"bin": {
"tsc": "./bin/tsc",
"tsserver": "./bin/tsserver"
@@ -38,6 +37,17 @@
"tslint": "latest"
},
"scripts": {
- "test": "jake runtests"
- }
+ "pretest": "jake tests",
+ "test": "jake runtests",
+ "build": "npm run build:compiler && npm run build:tests",
+ "build:compiler": "jake local",
+ "build:tests": "jake tests",
+ "clean": "jake clean"
+ },
+ "browser": {
+ "buffer": false,
+ "fs": false,
+ "os": false,
+ "path": false
+ }
}
diff --git a/scripts/word2md.js b/scripts/word2md.js
index 0645acbb143..e80275d5b2d 100644
--- a/scripts/word2md.js
+++ b/scripts/word2md.js
@@ -1,8 +1,16 @@
+// word2md - Word to Markdown conversion tool
+//
+// word2md converts a Microsoft Word document to Markdown formatted text. The tool uses the
+// Word Automation APIs to start an instance of Word and access the contents of the document
+// being converted. The tool must be run using the cscript.exe script host and requires Word
+// to be installed on the target machine. The name of the document to convert must be specified
+// as a command line argument and the resulting Markdown is written to standard output. The
+// tool recognizes the specific Word styles used in the TypeScript Language Specification.
var sys = (function () {
var fileStream = new ActiveXObject("ADODB.Stream");
- fileStream.Type = 2;
+ fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
- binaryStream.Type = 1;
+ binaryStream.Type = 1 /*binary*/;
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
@@ -17,11 +25,13 @@ var sys = (function () {
fileStream.Open();
binaryStream.Open();
try {
+ // Write characters in UTF-8 encoding
fileStream.Charset = "utf-8";
fileStream.WriteText(data);
+ // We don't want the BOM, skip it by setting the starting location to 3 (size of BOM).
fileStream.Position = 3;
fileStream.CopyTo(binaryStream);
- binaryStream.SaveToFile(fileName, 2);
+ binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
}
finally {
binaryStream.Close();
@@ -59,6 +69,17 @@ function convertDocumentToMarkdown(doc) {
setProperties(replace, replaceOptions);
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
+ function fixHyperlinks() {
+ var count = doc.hyperlinks.count;
+ for (var i = 0; i < count; i++) {
+ var hyperlink = doc.hyperlinks.item(i + 1);
+ var address = hyperlink.address;
+ if (address && address.length > 0) {
+ var textToDisplay = hyperlink.textToDisplay;
+ hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
+ }
+ }
+ }
function write(s) {
result += s;
}
@@ -184,14 +205,15 @@ function convertDocumentToMarkdown(doc) {
findReplace("<", { style: "Code Fragment" }, "<", {});
findReplace("<", { style: "Terminal" }, "<", {});
findReplace("", { font: { subscript: true } }, "^&", { font: { subscript: false } });
- findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 });
- findReplace("", { style: "Production" }, "*^&*", { style: -66 });
- findReplace("", { style: "Terminal" }, "`^&`", { style: -66 });
+ findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ });
+ findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ });
+ findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } });
findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } });
doc.fields.toggleShowCodes();
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
+ fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
result = result.replace(/\x96/g, "\u2013");
@@ -210,3 +232,4 @@ function main(args) {
app.quit();
}
main(sys.args);
+//# sourceMappingURL=file:///c:/ts/scripts/word2md.js.map
\ No newline at end of file
diff --git a/scripts/word2md.ts b/scripts/word2md.ts
index 65b39d6e4f6..ec9ed634b3c 100644
--- a/scripts/word2md.ts
+++ b/scripts/word2md.ts
@@ -100,9 +100,19 @@ module Word {
toggleShowCodes(): void;
}
+ export interface Hyperlink {
+ address: string;
+ textToDisplay: string;
+ range: Range;
+ }
+
+ export interface Hyperlinks extends Collection {
+ }
+
export interface Document {
fields: Fields;
paragraphs: Paragraphs;
+ hyperlinks: Hyperlinks;
builtInDocumentProperties: Collection;
close(saveChanges: boolean): void;
range(): Range;
@@ -195,6 +205,18 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
+ function fixHyperlinks() {
+ var count = doc.hyperlinks.count;
+ for (var i = 0; i < count; i++) {
+ var hyperlink = doc.hyperlinks.item(i + 1);
+ var address = hyperlink.address;
+ if (address && address.length > 0) {
+ var textToDisplay = hyperlink.textToDisplay;
+ hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
+ }
+ }
+ }
+
function write(s: string) {
result += s;
}
@@ -347,6 +369,8 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
+ fixHyperlinks();
+
writeDocument();
result = result.replace(/\x85/g, "\u2026");
diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts
index e842f9a4040..340bf478209 100644
--- a/src/compiler/binder.ts
+++ b/src/compiler/binder.ts
@@ -74,7 +74,7 @@ namespace ts {
// If the current node is a container that also container that also contains locals. Examples:
//
// Functions, Methods, Modules, Source-files.
- IsContainerWithLocals = IsContainer | HasLocals
+ IsContainerWithLocals = IsContainer | HasLocals
}
export function bindSourceFile(file: SourceFile) {
@@ -139,7 +139,7 @@ namespace ts {
function getDeclarationName(node: Declaration): string {
if (node.name) {
if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
- return '"' + (node.name).text + '"';
+ return `"${(node.name).text}"`;
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
let nameExpression = (node.name).expression;
@@ -830,7 +830,7 @@ namespace ts {
// Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
// string to contain unicode escapes (as per ES5).
- return nodeText === '"use strict"' || nodeText === "'use strict'";
+ return nodeText === "\"use strict\"" || nodeText === "'use strict'";
}
function bindWorker(node: Node) {
@@ -930,7 +930,7 @@ namespace ts {
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (isExternalModule(file)) {
- bindAnonymousDeclaration(file, SymbolFlags.ValueModule, '"' + removeFileExtension(file.fileName) + '"');
+ bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
}
}
@@ -1062,4 +1062,4 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
}
-}
+}
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts
index 3363987322a..562234a4305 100644
--- a/src/compiler/checker.ts
+++ b/src/compiler/checker.ts
@@ -91,7 +91,8 @@ namespace ts {
getExportsOfModule: getExportsOfModuleAsArray,
getJsxElementAttributesType,
- getJsxIntrinsicTagNames
+ getJsxIntrinsicTagNames,
+ isOptionalParameter
};
let unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown");
@@ -113,6 +114,10 @@ namespace ts {
emptyGenericType.instantiations = {};
let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
+ // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
+ // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
+ anyFunctionType.flags |= TypeFlags.ContainsAnyFunctionType;
+
let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
let anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false);
@@ -206,6 +211,9 @@ namespace ts {
let assignableRelation: Map = {};
let identityRelation: Map = {};
+ // This is for caching the result of getSymbolDisplayBuilder. Do not access directly.
+ let _displayBuilder: SymbolDisplayBuilder;
+
type TypeSystemEntity = Symbol | Type | Signature;
const enum TypeSystemPropertyName {
@@ -587,7 +595,19 @@ namespace ts {
declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg));
return undefined;
}
- if (result.flags & SymbolFlags.BlockScopedVariable) {
+
+ // Only check for block-scoped variable if we are looking for the
+ // name with variable meaning
+ // For example,
+ // declare module foo {
+ // interface bar {}
+ // }
+ // let foo/*1*/: foo/*2*/.bar;
+ // The foo at /*1*/ and /*2*/ will share same symbol with two meaning
+ // block - scope variable and namespace module. However, only when we
+ // try to resolve name in /*1*/ which is used in variable position,
+ // we want to check for block- scoped
+ if (meaning & SymbolFlags.BlockScopedVariable && result.flags & SymbolFlags.BlockScopedVariable) {
checkResolvedBlockScopedVariable(result, errorLocation);
}
}
@@ -945,28 +965,19 @@ namespace ts {
// Escape the name in the "require(...)" clause to ensure we find the right symbol.
let moduleName = escapeIdentifier(moduleReferenceLiteral.text);
- if (!moduleName) return;
+ if (!moduleName) {
+ return;
+ }
let isRelative = isExternalModuleNameRelative(moduleName);
if (!isRelative) {
- let symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule);
+ let symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule);
if (symbol) {
return symbol;
}
}
- let fileName: string;
- let sourceFile: SourceFile;
- while (true) {
- fileName = normalizePath(combinePaths(searchPath, moduleName));
- sourceFile = forEach(supportedExtensions, extension => host.getSourceFile(fileName + extension));
- if (sourceFile || isRelative) {
- break;
- }
- let parentPath = getDirectoryPath(searchPath);
- if (parentPath === searchPath) {
- break;
- }
- searchPath = parentPath;
- }
+
+ let fileName = getResolvedModuleFileName(getSourceFile(location), moduleReferenceLiteral.text);
+ let sourceFile = fileName && host.getSourceFile(fileName);
if (sourceFile) {
if (sourceFile.symbol) {
return sourceFile.symbol;
@@ -1473,8 +1484,6 @@ namespace ts {
return undefined;
}
- // This is for caching the result of getSymbolDisplayBuilder. Do not access directly.
- let _displayBuilder: SymbolDisplayBuilder;
function getSymbolDisplayBuilder(): SymbolDisplayBuilder {
function getNameOfSymbol(symbol: Symbol): string {
@@ -1994,15 +2003,15 @@ namespace ts {
}
return _displayBuilder || (_displayBuilder = {
- buildSymbolDisplay: buildSymbolDisplay,
- buildTypeDisplay: buildTypeDisplay,
- buildTypeParameterDisplay: buildTypeParameterDisplay,
- buildParameterDisplay: buildParameterDisplay,
- buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters,
- buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters,
- buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol,
- buildSignatureDisplay: buildSignatureDisplay,
- buildReturnTypeDisplay: buildReturnTypeDisplay
+ buildSymbolDisplay,
+ buildTypeDisplay,
+ buildTypeParameterDisplay,
+ buildParameterDisplay,
+ buildDisplayForParametersAndDelimiters,
+ buildDisplayForTypeParametersAndDelimiters,
+ buildTypeParameterDisplayFromSymbol,
+ buildSignatureDisplay,
+ buildReturnTypeDisplay
});
}
@@ -2157,10 +2166,13 @@ namespace ts {
function collectLinkedAliases(node: Identifier): Node[] {
let exportSymbol: Symbol;
if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) {
- exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, node);
+ exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, Diagnostics.Cannot_find_name_0, node);
}
else if (node.parent.kind === SyntaxKind.ExportSpecifier) {
- exportSymbol = getTargetOfExportSpecifier(node.parent);
+ let exportSpecifier = node.parent;
+ exportSymbol = (exportSpecifier.parent.parent).moduleSpecifier ?
+ getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) :
+ resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias);
}
let result: Node[] = [];
if (exportSymbol) {
@@ -3113,52 +3125,66 @@ namespace ts {
setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType);
}
- function findMatchingSignature(signature: Signature, signatureList: Signature[]): Signature {
- for (let s of signatureList) {
- // Only signatures with no type parameters may differ in return types
- if (compareSignatures(signature, s, /*compareReturnTypes*/ !!signature.typeParameters, compareTypes)) {
+ function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreReturnTypes: boolean): Signature {
+ for (let s of signatureList) {
+ if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) {
return s;
}
}
}
- function findMatchingSignatures(signature: Signature, signatureLists: Signature[][]): Signature[] {
+ function findMatchingSignatures(signatureLists: Signature[][], signature: Signature, listIndex: number): Signature[] {
+ if (signature.typeParameters) {
+ // We require an exact match for generic signatures, so we only return signatures from the first
+ // signature list and only if they have exact matches in the other signature lists.
+ if (listIndex > 0) {
+ return undefined;
+ }
+ for (let i = 1; i < signatureLists.length; i++) {
+ if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ false)) {
+ return undefined;
+ }
+ }
+ return [signature];
+ }
let result: Signature[] = undefined;
- for (let i = 1; i < signatureLists.length; i++) {
- let match = findMatchingSignature(signature, signatureLists[i]);
+ for (let i = 0; i < signatureLists.length; i++) {
+ // Allow matching non-generic signatures to have excess parameters and different return types
+ let match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true);
if (!match) {
return undefined;
}
- if (!result) {
- result = [signature];
- }
- if (match !== signature) {
- result.push(match);
+ if (!contains(result, match)) {
+ (result || (result = [])).push(match);
}
}
return result;
}
- // The signatures of a union type are those signatures that are present and identical in each of the
- // constituent types, except that non-generic signatures may differ in return types. When signatures
- // differ in return types, the resulting return type is the union of the constituent return types.
+ // The signatures of a union type are those signatures that are present in each of the constituent types.
+ // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
+ // parameters and may differ in return types. When signatures differ in return types, the resulting return
+ // type is the union of the constituent return types.
function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] {
let signatureLists = map(types, t => getSignaturesOfType(t, kind));
let result: Signature[] = undefined;
- for (let source of signatureLists[0]) {
- let unionSignatures = findMatchingSignatures(source, signatureLists);
- if (unionSignatures) {
- let signature: Signature = undefined;
- if (unionSignatures.length === 1 || source.typeParameters) {
- signature = source;
+ for (let i = 0; i < signatureLists.length; i++) {
+ for (let signature of signatureLists[i]) {
+ // Only process signatures with parameter lists that aren't already in the result list
+ if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) {
+ let unionSignatures = findMatchingSignatures(signatureLists, signature, i);
+ if (unionSignatures) {
+ let s = signature;
+ // Union the result types when more than one signature matches
+ if (unionSignatures.length > 1) {
+ s = cloneSignature(signature);
+ // Clear resolved return type we possibly got from cloneSignature
+ s.resolvedReturnType = undefined;
+ s.unionSignatures = unionSignatures;
+ }
+ (result || (result = [])).push(s);
+ }
}
- else {
- signature = cloneSignature(source);
- // Clear resolved return type we possibly got from cloneSignature
- signature.resolvedReturnType = undefined;
- signature.unionSignatures = unionSignatures;
- }
- (result || (result = [])).push(signature);
}
}
return result || emptyArray;
@@ -3431,7 +3457,7 @@ namespace ts {
// type, a property is considered known if it is known in any constituent type.
function isKnownProperty(type: Type, name: string): boolean {
if (type.flags & TypeFlags.ObjectType && type !== globalObjectType) {
- var resolved = resolveStructuredTypeMembers(type);
+ const resolved = resolveStructuredTypeMembers(type);
return !!(resolved.properties.length === 0 ||
resolved.stringIndexType ||
resolved.numberIndexType ||
@@ -3456,8 +3482,10 @@ namespace ts {
return emptyArray;
}
- // Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
- // maps primitive types and type parameters are to their apparent types.
+ /**
+ * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
+ * maps primitive types and type parameters are to their apparent types.
+ */
function getSignaturesOfType(type: Type, kind: SignatureKind): Signature[] {
return getSignaturesOfStructuredType(getApparentType(type), kind);
}
@@ -3517,7 +3545,19 @@ namespace ts {
}
function isOptionalParameter(node: ParameterDeclaration) {
- return hasQuestionToken(node) || !!node.initializer;
+ if (hasQuestionToken(node)) {
+ return true;
+ }
+
+ if (node.initializer) {
+ let signatureDeclaration = node.parent;
+ let signature = getSignatureFromDeclaration(signatureDeclaration);
+ let parameterIndex = signatureDeclaration.parameters.indexOf(node);
+ Debug.assert(parameterIndex >= 0);
+ return parameterIndex >= signature.minArgumentCount;
+ }
+
+ return false;
}
function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature {
@@ -3535,11 +3575,16 @@ namespace ts {
if (param.type && param.type.kind === SyntaxKind.StringLiteral) {
hasStringLiterals = true;
}
- if (minArgumentCount < 0) {
- if (param.initializer || param.questionToken || param.dotDotDotToken) {
+
+ if (param.initializer || param.questionToken || param.dotDotDotToken) {
+ if (minArgumentCount < 0) {
minArgumentCount = i;
}
}
+ else {
+ // If we see any required parameters, it means the prior ones were not in fact optional.
+ minArgumentCount = -1;
+ }
}
if (minArgumentCount < 0) {
@@ -3757,22 +3802,23 @@ namespace ts {
}
}
- // This function is used to propagate widening flags when creating new object types references and union types.
- // It is only necessary to do so if a constituent type might be the undefined type, the null type, or the type
- // of an object literal (since those types have widening related information we need to track).
- function getWideningFlagsOfTypes(types: Type[]): TypeFlags {
+ // This function is used to propagate certain flags when creating new object type references and union types.
+ // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
+ // of an object literal or the anyFunctionType. This is because there are operations in the type checker
+ // that care about the presence of such types at arbitrary depth in a containing type.
+ function getPropagatingFlagsOfTypes(types: Type[]): TypeFlags {
let result: TypeFlags = 0;
for (let type of types) {
result |= type.flags;
}
- return result & TypeFlags.RequiresWidening;
+ return result & TypeFlags.PropagatingFlags;
}
function createTypeReference(target: GenericType, typeArguments: Type[]): TypeReference {
let id = getTypeListId(typeArguments);
let type = target.instantiations[id];
if (!type) {
- let flags = TypeFlags.Reference | getWideningFlagsOfTypes(typeArguments);
+ let flags = TypeFlags.Reference | getPropagatingFlagsOfTypes(typeArguments);
type = target.instantiations[id] = createObjectType(flags, target.symbol);
type.target = target;
type.typeArguments = typeArguments;
@@ -4026,7 +4072,7 @@ namespace ts {
let id = getTypeListId(elementTypes);
let type = tupleTypes[id];
if (!type) {
- type = tupleTypes[id] = createObjectType(TypeFlags.Tuple | getWideningFlagsOfTypes(elementTypes));
+ type = tupleTypes[id] = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes));
type.elementTypes = elementTypes;
}
return type;
@@ -4175,7 +4221,7 @@ namespace ts {
let id = getTypeListId(typeSet);
let type = unionTypes[id];
if (!type) {
- type = unionTypes[id] = createObjectType(TypeFlags.Union | getWideningFlagsOfTypes(typeSet));
+ type = unionTypes[id] = createObjectType(TypeFlags.Union | getPropagatingFlagsOfTypes(typeSet));
type.types = typeSet;
}
return type;
@@ -4209,7 +4255,7 @@ namespace ts {
let id = getTypeListId(typeSet);
let type = intersectionTypes[id];
if (!type) {
- type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getWideningFlagsOfTypes(typeSet));
+ type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getPropagatingFlagsOfTypes(typeSet));
type.types = typeSet;
}
return type;
@@ -4364,11 +4410,11 @@ namespace ts {
return getInferredType(context, i);
}
}
- return t;
+ return t;
};
mapper.context = context;
- return mapper;
+ return mapper;
}
function identityMapper(type: Type): Type {
@@ -4633,19 +4679,21 @@ namespace ts {
let result: Ternary;
// both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
if (source === target) return Ternary.True;
- if (relation !== identityRelation) {
- if (isTypeAny(target)) return Ternary.True;
- if (source === undefinedType) return Ternary.True;
- if (source === nullType && target !== undefinedType) return Ternary.True;
- if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True;
- if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True;
- if (relation === assignableRelation) {
- if (isTypeAny(source)) return Ternary.True;
- if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True;
- }
+ if (relation === identityRelation) {
+ return isIdenticalTo(source, target);
}
- if (relation !== identityRelation && source.flags & TypeFlags.FreshObjectLiteral) {
+ if (isTypeAny(target)) return Ternary.True;
+ if (source === undefinedType) return Ternary.True;
+ if (source === nullType && target !== undefinedType) return Ternary.True;
+ if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True;
+ if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True;
+ if (relation === assignableRelation) {
+ if (isTypeAny(source)) return Ternary.True;
+ if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True;
+ }
+
+ if (source.flags & TypeFlags.FreshObjectLiteral) {
if (hasExcessProperties(source, target, reportErrors)) {
if (reportErrors) {
reportRelationError(headMessage, source, target);
@@ -4661,78 +4709,66 @@ namespace ts {
let saveErrorInfo = errorInfo;
- if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) {
- // We have type references to same target type, see if relationship holds for all type arguments
- if (result = typesRelatedTo((source).typeArguments, (target).typeArguments, reportErrors)) {
+ // Note that the "each" checks must precede the "some" checks to produce the correct results
+ if (source.flags & TypeFlags.Union) {
+ if (result = eachTypeRelatedToType(source, target, reportErrors)) {
return result;
}
}
- else if (source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.TypeParameter) {
- if (result = typeParameterRelatedTo(source, target, reportErrors)) {
+ else if (target.flags & TypeFlags.Intersection) {
+ if (result = typeRelatedToEachType(source, target, reportErrors)) {
return result;
}
}
- else if (relation !== identityRelation) {
- // Note that the "each" checks must precede the "some" checks to produce the correct results
- if (source.flags & TypeFlags.Union) {
- if (result = eachTypeRelatedToType(source, target, reportErrors)) {
- return result;
- }
- }
- else if (target.flags & TypeFlags.Intersection) {
- if (result = typeRelatedToEachType(source, target, reportErrors)) {
- return result;
- }
- }
- else {
- // It is necessary to try "each" checks on both sides because there may be nested "some" checks
- // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or
- // A & B = (A & B) | (C & D).
- if (source.flags & TypeFlags.Intersection) {
- // If target is a union type the following check will report errors so we suppress them here
- if (result = someTypeRelatedToType(source, target, reportErrors && !(target.flags & TypeFlags.Union))) {
- return result;
- }
- }
- if (target.flags & TypeFlags.Union) {
- if (result = typeRelatedToSomeType(source, target, reportErrors)) {
- return result;
- }
- }
- }
- }
else {
- if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
- source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
- if (result = eachTypeRelatedToSomeType(source, target)) {
- if (result &= eachTypeRelatedToSomeType(target, source)) {
- return result;
- }
+ // It is necessary to try "some" checks on both sides because there may be nested "each" checks
+ // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or
+ // A & B = (A & B) | (C & D).
+ if (source.flags & TypeFlags.Intersection) {
+ // If target is a union type the following check will report errors so we suppress them here
+ if (result = someTypeRelatedToType(source, target, reportErrors && !(target.flags & TypeFlags.Union))) {
+ return result;
+ }
+ }
+ if (target.flags & TypeFlags.Union) {
+ if (result = typeRelatedToSomeType(source, target, reportErrors)) {
+ return result;
}
}
}
- // Even if relationship doesn't hold for unions, type parameters, or generic type references,
- // it may hold in a structural comparison.
- // Report structural errors only if we haven't reported any errors yet
- let reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo;
- // Identity relation does not use apparent type
- let sourceOrApparentType = relation === identityRelation ? source : getApparentType(source);
- // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
- // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
- // relates to X. Thus, we include intersection types on the source side here.
- if (sourceOrApparentType.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) {
- if (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors)) {
+ if (source.flags & TypeFlags.TypeParameter) {
+ let constraint = getConstraintOfTypeParameter(source);
+ if (!constraint || constraint.flags & TypeFlags.Any) {
+ constraint = emptyObjectType;
+ }
+ // Report constraint errors only if the constraint is not the empty object type
+ let reportConstraintErrors = reportErrors && constraint !== emptyObjectType;
+ if (result = isRelatedTo(constraint, target, reportConstraintErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
- else if (source.flags & TypeFlags.TypeParameter && sourceOrApparentType.flags & TypeFlags.UnionOrIntersection) {
- // We clear the errors first because the following check often gives a better error than
- // the union or intersection comparison above if it is applicable.
- errorInfo = saveErrorInfo;
- if (result = isRelatedTo(sourceOrApparentType, target, reportErrors)) {
- return result;
+ else {
+ if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) {
+ // We have type references to same target type, see if relationship holds for all type arguments
+ if (result = typesRelatedTo((source).typeArguments, (target).typeArguments, reportErrors)) {
+ return result;
+ }
+ }
+ // Even if relationship doesn't hold for unions, intersections, or generic type references,
+ // it may hold in a structural comparison.
+ let apparentType = getApparentType(source);
+ // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
+ // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
+ // relates to X. Thus, we include intersection types on the source side here.
+ if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) {
+ // Report structural errors only if we haven't reported any errors yet
+ let reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo;
+ if (result = objectTypeRelatedTo(apparentType, target, reportStructuralErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
}
}
@@ -4742,6 +4778,31 @@ namespace ts {
return Ternary.False;
}
+ function isIdenticalTo(source: Type, target: Type): Ternary {
+ let result: Ternary;
+ if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType) {
+ if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) {
+ // We have type references to same target type, see if all type arguments are identical
+ if (result = typesRelatedTo((source).typeArguments, (target).typeArguments, /*reportErrors*/ false)) {
+ return result;
+ }
+ }
+ return objectTypeRelatedTo(source, target, /*reportErrors*/ false);
+ }
+ if (source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.TypeParameter) {
+ return typeParameterIdenticalTo(source, target);
+ }
+ if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
+ source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
+ if (result = eachTypeRelatedToSomeType(source, target)) {
+ if (result &= eachTypeRelatedToSomeType(target, source)) {
+ return result;
+ }
+ }
+ }
+ return Ternary.False;
+ }
+
function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean {
for (let prop of getPropertiesOfObjectType(source)) {
if (!isKnownProperty(target, prop.name)) {
@@ -4826,29 +4887,18 @@ namespace ts {
return result;
}
- function typeParameterRelatedTo(source: TypeParameter, target: TypeParameter, reportErrors: boolean): Ternary {
- if (relation === identityRelation) {
- if (source.symbol.name !== target.symbol.name) {
- return Ternary.False;
- }
- // covers case when both type parameters does not have constraint (both equal to noConstraintType)
- if (source.constraint === target.constraint) {
- return Ternary.True;
- }
- if (source.constraint === noConstraintType || target.constraint === noConstraintType) {
- return Ternary.False;
- }
- return isRelatedTo(source.constraint, target.constraint, reportErrors);
- }
- else {
- while (true) {
- let constraint = getConstraintOfTypeParameter(source);
- if (constraint === target) return Ternary.True;
- if (!(constraint && constraint.flags & TypeFlags.TypeParameter)) break;
- source = constraint;
- }
+ function typeParameterIdenticalTo(source: TypeParameter, target: TypeParameter): Ternary {
+ if (source.symbol.name !== target.symbol.name) {
return Ternary.False;
}
+ // covers case when both type parameters does not have constraint (both equal to noConstraintType)
+ if (source.constraint === target.constraint) {
+ return Ternary.True;
+ }
+ if (source.constraint === noConstraintType || target.constraint === noConstraintType) {
+ return Ternary.False;
+ }
+ return isIdenticalTo(source.constraint, target.constraint);
}
// Determine if two object types are related by structure. First, check if the result is already available in the global cache.
@@ -5050,30 +5100,24 @@ namespace ts {
let result = Ternary.True;
let saveErrorInfo = errorInfo;
- // Because the "abstractness" of a class is the same across all construct signatures
- // (internally we are checking the corresponding declaration), it is enough to perform
- // the check and report an error once over all pairs of source and target construct signatures.
- let sourceSig = sourceSignatures[0];
- // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds.
- let targetSig = targetSignatures[0];
- if (sourceSig && targetSig) {
- let sourceErasedSignature = getErasedSignature(sourceSig);
- let targetErasedSignature = getErasedSignature(targetSig);
- let sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature);
- let targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature);
+ if (kind === SignatureKind.Construct) {
+ // Only want to compare the construct signatures for abstractness guarantees.
+
+ // Because the "abstractness" of a class is the same across all construct signatures
+ // (internally we are checking the corresponding declaration), it is enough to perform
+ // the check and report an error once over all pairs of source and target construct signatures.
+ //
+ // sourceSig and targetSig are (possibly) undefined.
+ //
+ // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds.
+ let sourceSig = sourceSignatures[0];
+ let targetSig = targetSignatures[0];
- let sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getDeclarationOfKind(sourceReturnType.symbol, SyntaxKind.ClassDeclaration);
- let targetReturnDecl = targetReturnType && targetReturnType.symbol && getDeclarationOfKind(targetReturnType.symbol, SyntaxKind.ClassDeclaration);
- let sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract;
- let targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract;
-
- if (sourceIsAbstract && !targetIsAbstract) {
- if (reportErrors) {
- reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
- }
- return Ternary.False;
+ result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig);
+ if (result !== Ternary.True) {
+ return result;
}
}
@@ -5097,6 +5141,40 @@ namespace ts {
}
}
return result;
+
+ function abstractSignatureRelatedTo(source: Type, sourceSig: Signature, target: Type, targetSig: Signature) {
+ if (sourceSig && targetSig) {
+
+ let sourceDecl = source.symbol && getDeclarationOfKind(source.symbol, SyntaxKind.ClassDeclaration);
+ let targetDecl = target.symbol && getDeclarationOfKind(target.symbol, SyntaxKind.ClassDeclaration);
+
+ if (!sourceDecl) {
+ // If the source object isn't itself a class declaration, it can be freely assigned, regardless
+ // of whether the constructed object is abstract or not.
+ return Ternary.True;
+ }
+
+ let sourceErasedSignature = getErasedSignature(sourceSig);
+ let targetErasedSignature = getErasedSignature(targetSig);
+
+ let sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature);
+ let targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature);
+
+ let sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getDeclarationOfKind(sourceReturnType.symbol, SyntaxKind.ClassDeclaration);
+ let targetReturnDecl = targetReturnType && targetReturnType.symbol && getDeclarationOfKind(targetReturnType.symbol, SyntaxKind.ClassDeclaration);
+ let sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract;
+ let targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract;
+
+ if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) {
+ // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment.
+ if (reportErrors) {
+ reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
+ }
+ return Ternary.False;
+ }
+ }
+ return Ternary.True;
+ }
}
function signatureRelatedTo(source: Signature, target: Signature, reportErrors: boolean): Ternary {
@@ -5202,7 +5280,7 @@ namespace ts {
}
let result = Ternary.True;
for (let i = 0, len = sourceSignatures.length; i < len; ++i) {
- let related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*compareReturnTypes*/ true, isRelatedTo);
+ let related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
if (!related) {
return Ternary.False;
}
@@ -5216,7 +5294,7 @@ namespace ts {
return indexTypesIdenticalTo(IndexKind.String, source, target);
}
let targetType = getIndexTypeOfType(target, IndexKind.String);
- if (targetType) {
+ if (targetType && !(targetType.flags & TypeFlags.Any)) {
let sourceType = getIndexTypeOfType(source, IndexKind.String);
if (!sourceType) {
if (reportErrors) {
@@ -5241,7 +5319,7 @@ namespace ts {
return indexTypesIdenticalTo(IndexKind.Number, source, target);
}
let targetType = getIndexTypeOfType(target, IndexKind.Number);
- if (targetType) {
+ if (targetType && !(targetType.flags & TypeFlags.Any)) {
let sourceStringType = getIndexTypeOfType(source, IndexKind.String);
let sourceNumberType = getIndexTypeOfType(source, IndexKind.Number);
if (!(sourceStringType || sourceNumberType)) {
@@ -5332,14 +5410,18 @@ namespace ts {
return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
}
- function compareSignatures(source: Signature, target: Signature, compareReturnTypes: boolean, compareTypes: (s: Type, t: Type) => Ternary): Ternary {
+ function compareSignatures(source: Signature, target: Signature, partialMatch: boolean, ignoreReturnTypes: boolean, compareTypes: (s: Type, t: Type) => Ternary): Ternary {
if (source === target) {
return Ternary.True;
}
if (source.parameters.length !== target.parameters.length ||
source.minArgumentCount !== target.minArgumentCount ||
source.hasRestParameter !== target.hasRestParameter) {
- return Ternary.False;
+ if (!partialMatch ||
+ source.parameters.length < target.parameters.length && !source.hasRestParameter ||
+ source.minArgumentCount > target.minArgumentCount) {
+ return Ternary.False;
+ }
}
let result = Ternary.True;
if (source.typeParameters && target.typeParameters) {
@@ -5361,16 +5443,18 @@ namespace ts {
// M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N
source = getErasedSignature(source);
target = getErasedSignature(target);
- for (let i = 0, len = source.parameters.length; i < len; i++) {
- let s = source.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]);
- let t = target.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]);
+ let sourceLen = source.parameters.length;
+ let targetLen = target.parameters.length;
+ for (let i = 0; i < targetLen; i++) {
+ let s = source.hasRestParameter && i === sourceLen - 1 ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]);
+ let t = target.hasRestParameter && i === targetLen - 1 ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]);
let related = compareTypes(s, t);
if (!related) {
return Ternary.False;
}
result &= related;
}
- if (compareReturnTypes) {
+ if (!ignoreReturnTypes) {
result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
}
return result;
@@ -5656,11 +5740,17 @@ namespace ts {
}
function inferFromTypes(source: Type, target: Type) {
- if (source === anyFunctionType) {
- return;
- }
if (target.flags & TypeFlags.TypeParameter) {
- // If target is a type parameter, make an inference
+ // If target is a type parameter, make an inference, unless the source type contains
+ // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
+ // Because the anyFunctionType is internal, it should not be exposed to the user by adding
+ // it as an inference candidate. Hopefully, a better candidate will come along that does
+ // not contain anyFunctionType when we come back to this argument for its second round
+ // of inference.
+ if (source.flags & TypeFlags.ContainsAnyFunctionType) {
+ return;
+ }
+
let typeParameters = context.typeParameters;
for (let i = 0; i < typeParameters.length; i++) {
if (target === typeParameters[i]) {
@@ -5691,6 +5781,14 @@ namespace ts {
inferFromTypes(sourceTypes[i], targetTypes[i]);
}
}
+ else if (source.flags & TypeFlags.Tuple && target.flags & TypeFlags.Tuple && (source).elementTypes.length === (target).elementTypes.length) {
+ // If source and target are tuples of the same size, infer from element types
+ let sourceTypes = (source).elementTypes;
+ let targetTypes = (target).elementTypes;
+ for (let i = 0; i < sourceTypes.length; i++) {
+ inferFromTypes(sourceTypes[i], targetTypes[i]);
+ }
+ }
else if (target.flags & TypeFlags.UnionOrIntersection) {
let targetTypes = (target).types;
let typeParameterCount = 0;
@@ -6166,14 +6264,20 @@ namespace ts {
}
function getNarrowedType(originalType: Type, narrowedTypeCandidate: Type) {
- // Narrow to the target type if it's a subtype of the current type
- if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) {
+ // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces
+ // 0 candidates, fall back to the assignability check
+ if (originalType.flags & TypeFlags.Union) {
+ let assignableConstituents = filter((originalType).types, t => isTypeAssignableTo(t, narrowedTypeCandidate));
+ if (assignableConstituents.length) {
+ return getUnionType(assignableConstituents);
+ }
+ }
+
+ if (isTypeAssignableTo(narrowedTypeCandidate, originalType)) {
+ // Narrow to the target type if it's assignable to the current type
return narrowedTypeCandidate;
}
- // If the current type is a union type, remove all constituents that aren't subtypes of the target.
- if (originalType.flags & TypeFlags.Union) {
- return getUnionType(filter((originalType).types, t => isTypeSubtypeOf(t, narrowedTypeCandidate)));
- }
+
return originalType;
}
@@ -6395,22 +6499,79 @@ namespace ts {
let classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration));
let baseClassType = classType && getBaseTypes(classType)[0];
+ let container = getSuperContainer(node, /*includeFunctions*/ true);
+ let needToCaptureLexicalThis = false;
+
+ if (!isCallExpression) {
+ // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting
+ while (container && container.kind === SyntaxKind.ArrowFunction) {
+ container = getSuperContainer(container, /*includeFunctions*/ true);
+ needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6;
+ }
+ }
+
+ let canUseSuperExpression = isLegalUsageOfSuperExpression(container);
+ let nodeCheckFlag: NodeCheckFlags = 0;
+
+ // always set NodeCheckFlags for 'super' expression node
+ if (canUseSuperExpression) {
+ if ((container.flags & NodeFlags.Static) || isCallExpression) {
+ nodeCheckFlag = NodeCheckFlags.SuperStatic;
+ }
+ else {
+ nodeCheckFlag = NodeCheckFlags.SuperInstance;
+ }
+
+ getNodeLinks(node).flags |= nodeCheckFlag;
+
+ if (needToCaptureLexicalThis) {
+ // call expressions are allowed only in constructors so they should always capture correct 'this'
+ // super property access expressions can also appear in arrow functions -
+ // in this case they should also use correct lexical this
+ captureLexicalThis(node.parent, container);
+ }
+ }
+
if (!baseClassType) {
if (!classDeclaration || !getClassExtendsHeritageClauseElement(classDeclaration)) {
error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class);
}
+ return unknownType;
+ }
+
+ if (!canUseSuperExpression) {
+ if (container && container.kind === SyntaxKind.ComputedPropertyName) {
+ error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
+ }
+ else if (isCallExpression) {
+ error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
+ }
+ else {
+ error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
+ }
+
return unknownType;
}
+
+ if (container.kind === SyntaxKind.Constructor && isInConstructorArgumentInitializer(node, container)) {
+ // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
+ error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
+ return unknownType;
+ }
+
+ return nodeCheckFlag === NodeCheckFlags.SuperStatic
+ ? getBaseConstructorTypeOfClass(classType)
+ : baseClassType;
+
+ function isLegalUsageOfSuperExpression(container: Node): boolean {
+ if (!container) {
+ return false;
+ }
- let container = getSuperContainer(node, /*includeFunctions*/ true);
-
- if (container) {
- let canUseSuperExpression = false;
- let needToCaptureLexicalThis: boolean;
if (isCallExpression) {
// TS 1.0 SPEC (April 2014): 4.8.1
// Super calls are only permitted in constructors of derived classes
- canUseSuperExpression = container.kind === SyntaxKind.Constructor;
+ return container.kind === SyntaxKind.Constructor;
}
else {
// TS 1.0 SPEC (April 2014)
@@ -6418,75 +6579,28 @@ namespace ts {
// - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
// - In a static member function or static member accessor
- // super property access might appear in arrow functions with arbitrary deep nesting
- needToCaptureLexicalThis = false;
- while (container && container.kind === SyntaxKind.ArrowFunction) {
- container = getSuperContainer(container, /*includeFunctions*/ true);
- needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6;
- }
-
// topmost container must be something that is directly nested in the class declaration
if (container && isClassLike(container.parent)) {
if (container.flags & NodeFlags.Static) {
- canUseSuperExpression =
- container.kind === SyntaxKind.MethodDeclaration ||
- container.kind === SyntaxKind.MethodSignature ||
- container.kind === SyntaxKind.GetAccessor ||
- container.kind === SyntaxKind.SetAccessor;
+ return container.kind === SyntaxKind.MethodDeclaration ||
+ container.kind === SyntaxKind.MethodSignature ||
+ container.kind === SyntaxKind.GetAccessor ||
+ container.kind === SyntaxKind.SetAccessor;
}
else {
- canUseSuperExpression =
- container.kind === SyntaxKind.MethodDeclaration ||
- container.kind === SyntaxKind.MethodSignature ||
- container.kind === SyntaxKind.GetAccessor ||
- container.kind === SyntaxKind.SetAccessor ||
- container.kind === SyntaxKind.PropertyDeclaration ||
- container.kind === SyntaxKind.PropertySignature ||
- container.kind === SyntaxKind.Constructor;
+ return container.kind === SyntaxKind.MethodDeclaration ||
+ container.kind === SyntaxKind.MethodSignature ||
+ container.kind === SyntaxKind.GetAccessor ||
+ container.kind === SyntaxKind.SetAccessor ||
+ container.kind === SyntaxKind.PropertyDeclaration ||
+ container.kind === SyntaxKind.PropertySignature ||
+ container.kind === SyntaxKind.Constructor;
}
}
}
-
- if (canUseSuperExpression) {
- let returnType: Type;
-
- if ((container.flags & NodeFlags.Static) || isCallExpression) {
- getNodeLinks(node).flags |= NodeCheckFlags.SuperStatic;
- returnType = getBaseConstructorTypeOfClass(classType);
- }
- else {
- getNodeLinks(node).flags |= NodeCheckFlags.SuperInstance;
- returnType = baseClassType;
- }
-
- if (container.kind === SyntaxKind.Constructor && isInConstructorArgumentInitializer(node, container)) {
- // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
- error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
- returnType = unknownType;
- }
-
- if (!isCallExpression && needToCaptureLexicalThis) {
- // call expressions are allowed only in constructors so they should always capture correct 'this'
- // super property access expressions can also appear in arrow functions -
- // in this case they should also use correct lexical this
- captureLexicalThis(node.parent, container);
- }
-
- return returnType;
- }
- }
-
- if (container && container.kind === SyntaxKind.ComputedPropertyName) {
- error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
- }
- else if (isCallExpression) {
- error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
- }
- else {
- error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
- }
-
- return unknownType;
+
+ return false;
+ }
}
// Return contextual type of parameter or undefined if no contextual type is available
@@ -6854,20 +6968,13 @@ namespace ts {
let signatureList: Signature[];
let types = (type).types;
for (let current of types) {
- // The signature set of all constituent type with call signatures should match
- // So number of signatures allowed is either 0 or 1
- if (signatureList &&
- getSignaturesOfStructuredType(current, SignatureKind.Call).length > 1) {
- return undefined;
- }
-
let signature = getNonGenericSignature(current);
if (signature) {
if (!signatureList) {
// This signature will contribute to contextual union signature
signatureList = [signature];
}
- else if (!compareSignatures(signatureList[0], signature, /*compareReturnTypes*/ false, compareTypes)) {
+ else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) {
// Signatures aren't identical, do not use
return undefined;
}
@@ -7093,7 +7200,7 @@ namespace ts {
let stringIndexType = getIndexType(IndexKind.String);
let numberIndexType = getIndexType(IndexKind.Number);
let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
- result.flags |= TypeFlags.ObjectLiteral | TypeFlags.FreshObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.ContainsUndefinedOrNull);
+ result.flags |= TypeFlags.ObjectLiteral | TypeFlags.FreshObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.PropagatingFlags);
return result;
function getIndexType(kind: IndexKind) {
@@ -7139,13 +7246,17 @@ namespace ts {
}
function checkJsxElement(node: JsxElement) {
+ // Check attributes
+ checkJsxOpeningLikeElement(node.openingElement);
+
// Check that the closing tag matches
if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
error(node.closingElement, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNode(node.openingElement.tagName));
}
-
- // Check attributes
- checkJsxOpeningLikeElement(node.openingElement);
+ else {
+ // Perform resolution on the closing tag so that rename/go to definition/etc work
+ getJsxElementTagSymbol(node.closingElement);
+ }
// Check children
for (let child of node.children) {
@@ -7199,10 +7310,19 @@ namespace ts {
else if (elementAttributesType && !isTypeAny(elementAttributesType)) {
let correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text);
correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol);
- // If there's no corresponding property with this name, error
- if (!correspondingPropType && isUnhyphenatedJsxName(node.name.text)) {
- error(node.name, Diagnostics.Property_0_does_not_exist_on_type_1, node.name.text, typeToString(elementAttributesType));
- return unknownType;
+ if (isUnhyphenatedJsxName(node.name.text)) {
+ // Maybe there's a string indexer?
+ let indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String);
+ if (indexerType) {
+ correspondingPropType = indexerType
+ }
+ else {
+ // If there's no corresponding property with this name, error
+ if (!correspondingPropType) {
+ error(node.name, Diagnostics.Property_0_does_not_exist_on_type_1, node.name.text, typeToString(elementAttributesType));
+ return unknownType;
+ }
+ }
}
}
@@ -7256,7 +7376,7 @@ namespace ts {
/// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class
/// type or factory function.
/// Otherwise, returns unknownSymbol.
- function getJsxElementTagSymbol(node: JsxOpeningLikeElement): Symbol {
+ function getJsxElementTagSymbol(node: JsxOpeningLikeElement|JsxClosingElement): Symbol {
let flags: JsxFlags = JsxFlags.UnknownElement;
let links = getNodeLinks(node);
if (!links.resolvedSymbol) {
@@ -7268,7 +7388,7 @@ namespace ts {
}
return links.resolvedSymbol;
- function lookupIntrinsicTag(node: JsxOpeningLikeElement): Symbol {
+ function lookupIntrinsicTag(node: JsxOpeningLikeElement|JsxClosingElement): Symbol {
let intrinsicElementsType = getJsxIntrinsicElementsType();
if (intrinsicElementsType !== unknownType) {
// Property case
@@ -7286,7 +7406,7 @@ namespace ts {
}
// Wasn't found
- error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (node.tagName).text, 'JSX.' + JsxNames.IntrinsicElements);
+ error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (node.tagName).text, "JSX." + JsxNames.IntrinsicElements);
return unknownSymbol;
}
else {
@@ -7296,19 +7416,10 @@ namespace ts {
}
}
- function lookupClassTag(node: JsxOpeningLikeElement): Symbol {
- let valueSymbol: Symbol;
+ function lookupClassTag(node: JsxOpeningLikeElement|JsxClosingElement): Symbol {
+ let valueSymbol: Symbol = resolveJsxTagName(node);
// Look up the value in the current scope
- if (node.tagName.kind === SyntaxKind.Identifier) {
- let tag = node.tagName;
- let sym = getResolvedSymbol(tag);
- valueSymbol = sym.exportSymbol || sym;
- }
- else {
- valueSymbol = checkQualifiedName(node.tagName).symbol;
- }
-
if (valueSymbol && valueSymbol !== unknownSymbol) {
links.jsxFlags |= JsxFlags.ClassElement;
getSymbolLinks(valueSymbol).referenced = true;
@@ -7316,6 +7427,17 @@ namespace ts {
return valueSymbol || unknownSymbol;
}
+
+ function resolveJsxTagName(node: JsxOpeningLikeElement|JsxClosingElement): Symbol {
+ if (node.tagName.kind === SyntaxKind.Identifier) {
+ let tag = node.tagName;
+ let sym = getResolvedSymbol(tag);
+ return sym.exportSymbol || sym;
+ }
+ else {
+ return checkQualifiedName(node.tagName).symbol;
+ }
+ }
}
/**
@@ -7324,10 +7446,9 @@ namespace ts {
* For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`).
*/
function getJsxElementInstanceType(node: JsxOpeningLikeElement) {
- if (!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement)) {
- // There is no such thing as an instance type for a non-class element
- return undefined;
- }
+ // There is no such thing as an instance type for a non-class element. This
+ // line shouldn't be hit.
+ Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), "Should not call getJsxElementInstanceType on non-class Element");
let classSymbol = getJsxElementTagSymbol(node);
if (classSymbol === unknownSymbol) {
@@ -7350,16 +7471,11 @@ namespace ts {
if (signatures.length === 0) {
// We found no signatures at all, which is an error
error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName));
- return undefined;
+ return unknownType;
}
}
- // Check that the constructor/factory returns an object type
- let returnType = getUnionType(signatures.map(s => getReturnTypeOfSignature(s)));
- if (!isTypeAny(returnType) && !(returnType.flags & TypeFlags.ObjectType)) {
- error(node.tagName, Diagnostics.The_return_type_of_a_JSX_element_constructor_must_return_an_object_type);
- return undefined;
- }
+ let returnType = getUnionType(signatures.map(getReturnTypeOfSignature));
// Issue an error if this return type isn't assignable to JSX.ElementClass
let elemClassType = getJsxGlobalElementClassType();
@@ -7420,7 +7536,7 @@ namespace ts {
let elemInstanceType = getJsxElementInstanceType(node);
if (isTypeAny(elemInstanceType)) {
- return links.resolvedJsxType = anyType;
+ return links.resolvedJsxType = elemInstanceType;
}
let propsName = getJsxElementPropertiesName();
@@ -7512,7 +7628,7 @@ namespace ts {
// be marked as 'used' so we don't incorrectly elide its import. And if there
// is no 'React' symbol in scope, we should issue an error.
if (compilerOptions.jsx === JsxEmit.React) {
- let reactSym = resolveName(node.tagName, 'React', SymbolFlags.Value, Diagnostics.Cannot_find_name_0, 'React');
+ let reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React");
if (reactSym) {
getSymbolLinks(reactSym).referenced = true;
}
@@ -10406,17 +10522,21 @@ namespace ts {
return n.kind === SyntaxKind.CallExpression && (n).expression.kind === SyntaxKind.SuperKeyword;
}
+ function containsSuperCallAsComputedPropertyName(n: Declaration): boolean {
+ return n.name && containsSuperCall(n.name);
+ }
+
function containsSuperCall(n: Node): boolean {
if (isSuperCallExpression(n)) {
return true;
}
- switch (n.kind) {
- case SyntaxKind.FunctionExpression:
- case SyntaxKind.FunctionDeclaration:
- case SyntaxKind.ArrowFunction:
- case SyntaxKind.ObjectLiteralExpression: return false;
- default: return forEachChild(n, containsSuperCall);
+ else if (isFunctionLike(n)) {
+ return false;
}
+ else if (isClassLike(n)) {
+ return forEach((n).members, containsSuperCallAsComputedPropertyName);
+ }
+ return forEachChild(n, containsSuperCall);
}
function markThisReferencesAsErrors(n: Node): void {
@@ -10437,9 +10557,17 @@ namespace ts {
// TS 1.0 spec (April 2014): 8.3.2
// Constructors 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.
- if (getClassExtendsHeritageClauseElement(node.parent)) {
+ let containingClassDecl = node.parent;
+ if (getClassExtendsHeritageClauseElement(containingClassDecl)) {
+ let containingClassSymbol = getSymbolOfNode(containingClassDecl);
+ let containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol);
+ let baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType);
if (containsSuperCall(node.body)) {
+ if (baseConstructorType === nullType) {
+ error(node, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
+ }
+
// The first statement in the body of a constructor (excluding prologue directives) must be a super call
// if both of the following are true:
// - The containing class is a derived class.
@@ -10472,7 +10600,7 @@ namespace ts {
}
}
}
- else {
+ else if (baseConstructorType !== nullType) {
error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
}
}
@@ -10863,9 +10991,6 @@ namespace ts {
return;
}
- // Exports should be checked only if enclosing module contains both exported and non exported declarations.
- // In case if all declarations are non-exported check is unnecessary.
-
// if localSymbol is defined on node then node itself is exported - check is required
let symbol = node.localSymbol;
if (!symbol) {
@@ -10885,27 +11010,45 @@ namespace ts {
// we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace
// to denote disjoint declarationSpaces (without making new enum type).
- let exportedDeclarationSpaces: SymbolFlags = 0;
- let nonExportedDeclarationSpaces: SymbolFlags = 0;
- forEach(symbol.declarations, d => {
+ let exportedDeclarationSpaces = SymbolFlags.None;
+ let nonExportedDeclarationSpaces = SymbolFlags.None;
+ let defaultExportedDeclarationSpaces = SymbolFlags.None;
+ for (let d of symbol.declarations) {
let declarationSpaces = getDeclarationSpaces(d);
- if (getEffectiveDeclarationFlags(d, NodeFlags.Export)) {
- exportedDeclarationSpaces |= declarationSpaces;
+ let effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default);
+
+ if (effectiveDeclarationFlags & NodeFlags.Export) {
+ if (effectiveDeclarationFlags & NodeFlags.Default) {
+ defaultExportedDeclarationSpaces |= declarationSpaces;
+ }
+ else {
+ exportedDeclarationSpaces |= declarationSpaces;
+ }
}
else {
nonExportedDeclarationSpaces |= declarationSpaces;
}
- });
+ }
- let commonDeclarationSpace = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
+ // Spaces for anyting not declared a 'default export'.
+ let nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
+
+ let commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
+ let commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
- if (commonDeclarationSpace) {
+ if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
// declaration spaces for exported and non-exported declarations intersect
- forEach(symbol.declarations, d => {
- if (getDeclarationSpaces(d) & commonDeclarationSpace) {
+ for (let d of symbol.declarations) {
+ let declarationSpaces = getDeclarationSpaces(d);
+
+ // Only error on the declarations that conributed to the intersecting spaces.
+ if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
+ error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name));
+ }
+ else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name));
}
- });
+ }
}
function getDeclarationSpaces(d: Declaration): SymbolFlags {
@@ -12750,28 +12893,7 @@ namespace ts {
}
let initializer = member.initializer;
if (initializer) {
- autoValue = getConstantValueForEnumMemberInitializer(initializer);
- if (autoValue === undefined) {
- if (enumIsConst) {
- error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
- }
- else if (!ambient) {
- // Only here do we need to check that the initializer is assignable to the enum type.
- // If it is a constant value (not undefined), it is syntactically constrained to be a number.
- // Also, we do not need to check this for ambients because there is already
- // a syntax error if it is not a constant.
- checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined);
- }
- }
- else if (enumIsConst) {
- if (isNaN(autoValue)) {
- error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN);
- }
- else if (!isFinite(autoValue)) {
- error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
- }
- }
-
+ autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient);
}
else if (ambient && !enumIsConst) {
autoValue = undefined;
@@ -12785,8 +12907,36 @@ namespace ts {
nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed;
}
- function getConstantValueForEnumMemberInitializer(initializer: Expression): number {
- return evalConstant(initializer);
+ function computeConstantValueForEnumMemberInitializer(initializer: Expression, enumType: Type, enumIsConst: boolean, ambient: boolean): number {
+ // Controls if error should be reported after evaluation of constant value is completed
+ // Can be false if another more precise error was already reported during evaluation.
+ let reportError = true;
+ let value = evalConstant(initializer);
+
+ if (reportError) {
+ if (value === undefined) {
+ if (enumIsConst) {
+ error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
+ }
+ else if (!ambient) {
+ // Only here do we need to check that the initializer is assignable to the enum type.
+ // If it is a constant value (not undefined), it is syntactically constrained to be a number.
+ // Also, we do not need to check this for ambients because there is already
+ // a syntax error if it is not a constant.
+ checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined);
+ }
+ }
+ else if (enumIsConst) {
+ if (isNaN(value)) {
+ error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN);
+ }
+ else if (!isFinite(value)) {
+ error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
+ }
+ }
+ }
+
+ return value;
function evalConstant(e: Node): number {
switch (e.kind) {
@@ -12895,6 +13045,8 @@ namespace ts {
// illegal case: forward reference
if (!isDefinedBefore(propertyDecl, member)) {
+ reportError = false;
+ error(e, Diagnostics.A_member_initializer_in_a_const_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_const_enums);
return undefined;
}
@@ -13170,7 +13322,7 @@ namespace ts {
}
}
else {
- if (languageVersion >= ScriptTarget.ES6) {
+ if (languageVersion >= ScriptTarget.ES6 && !isInAmbientContext(node)) {
// Import equals declaration is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_or_import_d_from_mod_instead);
}
@@ -13812,7 +13964,9 @@ namespace ts {
meaning |= SymbolFlags.Alias;
return resolveEntityName(entityName, meaning);
}
- else if ((entityName.parent.kind === SyntaxKind.JsxOpeningElement) || (entityName.parent.kind === SyntaxKind.JsxSelfClosingElement)) {
+ else if ((entityName.parent.kind === SyntaxKind.JsxOpeningElement) ||
+ (entityName.parent.kind === SyntaxKind.JsxSelfClosingElement) ||
+ (entityName.parent.kind === SyntaxKind.JsxClosingElement)) {
return getJsxElementTagSymbol(entityName.parent);
}
else if (isExpression(entityName)) {
@@ -14234,15 +14388,17 @@ namespace ts {
return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Call).length > 0;
}
- function getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind {
+ function getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind {
// Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
- let symbol = resolveEntityName(node.typeName, SymbolFlags.Value, /*ignoreErrors*/ true);
- let constructorType = symbol ? getTypeOfSymbol(symbol) : undefined;
+ let valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true);
+ let constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined;
if (constructorType && isConstructorType(constructorType)) {
return TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
}
- let type = getTypeFromTypeNode(node);
+ // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
+ let typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true);
+ let type = getDeclaredTypeOfSymbol(typeSymbol);
if (type === unknownType) {
return TypeReferenceSerializationKind.Unknown;
}
@@ -14376,6 +14532,7 @@ namespace ts {
getBlockScopedVariableId,
getReferencedValueDeclaration,
getTypeReferenceSerializationKind,
+ isOptionalParameter
};
}
@@ -14771,17 +14928,15 @@ namespace ts {
return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer);
}
}
- else if (parameter.questionToken || parameter.initializer) {
+ else if (parameter.questionToken) {
seenOptionalParameter = true;
- if (parameter.questionToken && parameter.initializer) {
+ if (parameter.initializer) {
return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
}
}
- else {
- if (seenOptionalParameter) {
- return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
- }
+ else if (seenOptionalParameter && !parameter.initializer) {
+ return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
}
}
}
diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts
index ba7d8ca9ce3..9a984b9a2f1 100644
--- a/src/compiler/commandLineParser.ts
+++ b/src/compiler/commandLineParser.ts
@@ -335,7 +335,7 @@ namespace ts {
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } {
- let text = '';
+ let text = "";
try {
text = sys.readFile(fileName);
}
@@ -422,10 +422,13 @@ namespace ts {
if (json["files"] instanceof Array) {
fileNames = map(json["files"], s => combinePaths(basePath, s));
}
+ else {
+ errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
+ }
}
else {
let exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined;
- let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
+ let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
diff --git a/src/compiler/core.ts b/src/compiler/core.ts
index ec171d4aee2..5fc9335073c 100644
--- a/src/compiler/core.ts
+++ b/src/compiler/core.ts
@@ -24,6 +24,7 @@ namespace ts {
set,
contains,
remove,
+ clear,
forEachValue: forEachValueInMap
};
@@ -51,6 +52,10 @@ namespace ts {
function normalizeKey(key: string) {
return getCanonicalFileName(normalizeSlashes(key));
}
+
+ function clear() {
+ files = {};
+ }
}
export const enum Comparison {
@@ -193,6 +198,13 @@ namespace ts {
return array[array.length - 1];
}
+ /**
+ * Performs a binary search, finding the index at which 'value' occurs in 'array'.
+ * If no such index is found, returns the 2's-complement of first index at which
+ * number[index] exceeds number.
+ * @param array A sorted array whose first element must be no larger than number
+ * @param number The value to be searched for in the array.
+ */
export function binarySearch(array: number[], value: number): number {
let low = 0;
let high = array.length - 1;
@@ -219,10 +231,10 @@ namespace ts {
export function reduceLeft(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceLeft(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
- var count = array.length;
+ const count = array.length;
if (count > 0) {
- var pos = 0;
- var result = arguments.length <= 2 ? array[pos++] : initial;
+ let pos = 0;
+ let result = arguments.length <= 2 ? array[pos++] : initial;
while (pos < count) {
result = f(result, array[pos++]);
}
@@ -236,9 +248,9 @@ namespace ts {
export function reduceRight(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceRight(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
- var pos = array.length - 1;
+ let pos = array.length - 1;
if (pos >= 0) {
- var result = arguments.length <= 2 ? array[pos--] : initial;
+ let result = arguments.length <= 2 ? array[pos--] : initial;
while (pos >= 0) {
result = f(result, array[pos--]);
}
@@ -523,7 +535,7 @@ namespace ts {
if (path.lastIndexOf("file:///", 0) === 0) {
return "file:///".length;
}
- let idx = path.indexOf('://');
+ let idx = path.indexOf("://");
if (idx !== -1) {
return idx + "://".length;
}
@@ -709,7 +721,7 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
- export const supportedExtensions = [".tsx", ".ts", ".d.ts"];
+ export const supportedExtensions = [".ts", ".tsx", ".d.ts"];
const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
export function removeFileExtension(path: string): string {
@@ -805,4 +817,4 @@ namespace ts {
Debug.assert(false, message);
}
}
-}
+}
diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts
index 6c0803f8761..a490ba39a46 100644
--- a/src/compiler/declarationEmitter.ts
+++ b/src/compiler/declarationEmitter.ts
@@ -750,14 +750,18 @@ namespace ts {
}
function writeTypeAliasDeclaration(node: TypeAliasDeclaration) {
+ let prevEnclosingDeclaration = enclosingDeclaration;
+ enclosingDeclaration = node;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
writeTextOfNode(currentSourceFile, node.name);
+ emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
write(";");
writeLine();
+ enclosingDeclaration = prevEnclosingDeclaration;
function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
return {
@@ -1371,7 +1375,7 @@ namespace ts {
else {
writeTextOfNode(currentSourceFile, node.name);
}
- if (node.initializer || hasQuestionToken(node)) {
+ if (resolver.isOptionalParameter(node)) {
write("?");
}
decreaseIndent();
@@ -1497,11 +1501,8 @@ namespace ts {
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
writeTextOfNode(currentSourceFile, bindingElement.propertyName);
write(": ");
-
- // If bindingElement has propertyName property, then its name must be another bindingPattern of SyntaxKind.ObjectBindingPattern
- emitBindingPattern(bindingElement.name);
}
- else if (bindingElement.name) {
+ if (bindingElement.name) {
if (isBindingPattern(bindingElement.name)) {
// If it is a nested binding pattern, we will recursively descend into each element and emit each one separately.
// In the case of rest element, we will omit rest element.
diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts
index ecea3a76673..5ccc0a0db9b 100644
--- a/src/compiler/diagnosticInformationMap.generated.ts
+++ b/src/compiler/diagnosticInformationMap.generated.ts
@@ -294,7 +294,7 @@ namespace ts {
Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." },
Duplicate_function_implementation: { code: 2393, category: DiagnosticCategory.Error, key: "Duplicate function implementation." },
Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." },
- Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration {0} must be all exported or all local." },
+ Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration '{0}' must be all exported or all local." },
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." },
Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." },
Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." },
@@ -425,6 +425,8 @@ namespace ts {
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
+ A_member_initializer_in_a_const_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_const_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums." },
+ Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -613,5 +615,6 @@ namespace ts {
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
+ A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" },
};
}
\ No newline at end of file
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json
index 2765d04f400..e138e2ddac4 100644
--- a/src/compiler/diagnosticMessages.json
+++ b/src/compiler/diagnosticMessages.json
@@ -1,4 +1,4 @@
-{
+ {
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -1165,7 +1165,7 @@
"category": "Error",
"code": 2394
},
- "Individual declarations in merged declaration {0} must be all exported or all local.": {
+ "Individual declarations in merged declaration '{0}' must be all exported or all local.": {
"category": "Error",
"code": 2395
},
@@ -1689,6 +1689,14 @@
"category": "Error",
"code": 2650
},
+ "A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums.": {
+ "category": "Error",
+ "code": 2651
+ },
+ "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead.": {
+ "category": "Error",
+ "code": 2652
+ },
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2445,5 +2453,9 @@
"Cannot use JSX unless the '--jsx' flag is provided.": {
"category": "Error",
"code": 17004
+ },
+ "A constructor cannot contain a 'super' call when its class extends 'null'": {
+ "category": "Error",
+ "code": 17005
}
}
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts
index e97ece5bf00..a6e9b22ddee 100644
--- a/src/compiler/emitter.ts
+++ b/src/compiler/emitter.ts
@@ -163,7 +163,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let writeComment = writeCommentRange;
/** Emit a node */
- let emit = emitNodeWithoutSourceMap;
+ let emit = emitNodeWithCommentsAndWithoutSourcemap;
/** Called just before starting emit of a node */
let emitStart = function (node: Node) { };
@@ -380,7 +380,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function base64VLQFormatEncode(inValue: number) {
function base64FormatEncode(inValue: number) {
if (inValue < 64) {
- return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue);
+ return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue);
}
throw TypeError(inValue + ": not a 64 based value");
}
@@ -687,9 +687,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
+
+ function emitNodeWithCommentsAndWithSourcemap(node: Node) {
+ emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);
+ }
writeEmittedFiles = writeJavaScriptAndSourceMapFile;
- emit = emitNodeWithSourceMap;
+ emit = emitNodeWithCommentsAndWithSourcemap;
emitStart = recordEmitNodeStartSpan;
emitEnd = recordEmitNodeEndSpan;
emitToken = writeTextWithSpanRecord;
@@ -832,7 +836,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(", ");
}
}
- emitNode(nodes[start + i]);
+ let node = nodes[start + i];
+ // This emitting is to make sure we emit following comment properly
+ // ...(x, /*comment1*/ y)...
+ // ^ => node.pos
+ // "comment1" is not considered leading comment for "y" but rather
+ // considered as trailing comment of the previous node.
+ emitTrailingCommentsOfPosition(node.pos);
+ emitNode(node);
leadingComma = true;
}
if (trailingComma) {
@@ -895,7 +906,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
- return getQuotedEscapedLiteralText('"', node.text, '"');
+ return getQuotedEscapedLiteralText("\"", node.text, "\"");
}
// If we don't need to downlevel and we can reach the original source text using
@@ -908,15 +919,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// or an escaped quoted form of the original text if it's string-like.
switch (node.kind) {
case SyntaxKind.StringLiteral:
- return getQuotedEscapedLiteralText('"', node.text, '"');
+ return getQuotedEscapedLiteralText("\"", node.text, "\"");
case SyntaxKind.NoSubstitutionTemplateLiteral:
- return getQuotedEscapedLiteralText('`', node.text, '`');
+ return getQuotedEscapedLiteralText("`", node.text, "`");
case SyntaxKind.TemplateHead:
- return getQuotedEscapedLiteralText('`', node.text, '${');
+ return getQuotedEscapedLiteralText("`", node.text, "${");
case SyntaxKind.TemplateMiddle:
- return getQuotedEscapedLiteralText('}', node.text, '${');
+ return getQuotedEscapedLiteralText("}", node.text, "${");
case SyntaxKind.TemplateTail:
- return getQuotedEscapedLiteralText('}', node.text, '`');
+ return getQuotedEscapedLiteralText("}", node.text, "`");
case SyntaxKind.NumericLiteral:
return node.text;
}
@@ -947,7 +958,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
text = text.replace(/\r\n?/g, "\n");
text = escapeString(text);
- write('"' + text + '"');
+ write(`"${text}"`);
}
function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression) => void) {
@@ -1134,9 +1145,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/// 'Div' for upper-cased or dotted names
function emitTagName(name: Identifier|QualifiedName) {
if (name.kind === SyntaxKind.Identifier && isIntrinsicJsxName((name).text)) {
- write('"');
+ write("\"");
emit(name);
- write('"');
+ write("\"");
}
else {
emit(name);
@@ -1148,9 +1159,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/// about keywords, just non-identifier characters
function emitAttributeName(name: Identifier) {
if (/[A-Za-z_]+[\w*]/.test(name.text)) {
- write('"');
+ write("\"");
emit(name);
- write('"');
+ write("\"");
}
else {
emit(name);
@@ -1248,10 +1259,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Don't emit empty strings
if (children[i].kind === SyntaxKind.JsxText) {
let text = getTextToEmit(children[i]);
- if(text !== undefined) {
- write(', "');
+ if (text !== undefined) {
+ write(", \"");
write(text);
- write('"');
+ write("\"");
}
}
else {
@@ -1425,6 +1436,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.IfStatement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
+ case SyntaxKind.JsxSpreadAttribute:
case SyntaxKind.JsxExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ParenthesizedExpression:
@@ -1490,7 +1502,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (declaration.kind === SyntaxKind.ImportClause) {
// Identifier references default import
write(getGeneratedNameForNode(declaration.parent));
- write(languageVersion === ScriptTarget.ES3 ? '["default"]' : ".default");
+ write(languageVersion === ScriptTarget.ES3 ? "[\"default\"]" : ".default");
return;
}
else if (declaration.kind === SyntaxKind.ImportSpecifier) {
@@ -1975,6 +1987,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitPropertyAssignment(node: PropertyDeclaration) {
emit(node.name);
write(": ");
+ // This is to ensure that we emit comment in the following case:
+ // For example:
+ // obj = {
+ // id: /*comment1*/ ()=>void
+ // }
+ // "comment1" is not considered to be leading comment for node.initializer
+ // but rather a trailing comment on the previous node.
+ emitTrailingCommentsOfPosition(node.initializer.pos);
emit(node.initializer);
}
@@ -2005,12 +2025,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean {
- if (compilerOptions.isolatedModules) {
- // do not inline enum values in separate compilation mode
- return false;
- }
-
- let constantValue = resolver.getConstantValue(node);
+ let constantValue = tryGetConstEnumValue(node);
if (constantValue !== undefined) {
write(constantValue.toString());
if (!compilerOptions.removeComments) {
@@ -2021,6 +2036,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
return false;
}
+
+ function tryGetConstEnumValue(node: Node): number {
+ if (compilerOptions.isolatedModules) {
+ return undefined;
+ }
+
+ return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression
+ ? resolver.getConstantValue(node)
+ : undefined
+ }
// Returns 'true' if the code was actually indented, false otherwise.
// If the code is not indented, an optional valueToWriteWhenNotIndenting will be
@@ -2053,10 +2078,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
// 1 .toString is a valid property access, emit a space after the literal
+ // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal
let shouldEmitSpace: boolean;
- if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) {
- let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
- shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
+ if (!indentedBeforeDot) {
+ if (node.expression.kind === SyntaxKind.NumericLiteral) {
+ // check if numeric literal was originally written with a dot
+ let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
+ shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
+ }
+ else {
+ // check if constant enum value is integer
+ let constantValue = tryGetConstEnumValue(node.expression);
+ // isFinite handles cases when constantValue is undefined
+ shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue;
+ }
}
if (shouldEmitSpace) {
@@ -2095,7 +2130,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
write(".");
- emitNodeWithoutSourceMap(node.right);
+ emit(node.right);
}
function emitEntityNameAsExpression(node: EntityName, useFallback: boolean) {
@@ -2787,7 +2822,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitNodeWithoutSourceMap(counter);
write(" < ");
- emitNodeWithoutSourceMap(rhsReference);
+ emitNodeWithCommentsAndWithoutSourcemap(rhsReference);
write(".length");
emitEnd(node.initializer);
@@ -2822,7 +2857,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
// The following call does not include the initializer, so we have
// to emit it separately.
- emitNodeWithoutSourceMap(declaration);
+ emitNodeWithCommentsAndWithoutSourcemap(declaration);
write(" = ");
emitNodeWithoutSourceMap(rhsIterationValue);
}
@@ -2845,7 +2880,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined);
}
else {
- emitNodeWithoutSourceMap(assignmentExpression);
+ emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression);
}
}
emitEnd(node.initializer);
@@ -3001,7 +3036,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("exports.");
}
}
- emitNodeWithoutSourceMap(node.name);
+ emitNodeWithCommentsAndWithoutSourcemap(node.name);
emitEnd(node.name);
}
@@ -3047,7 +3082,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("default");
}
else {
- emitNodeWithoutSourceMap(node.name);
+ emitNodeWithCommentsAndWithoutSourcemap(node.name);
}
write(`", `);
emitDeclarationName(node);
@@ -3075,31 +3110,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitExportMemberAssignments(name: Identifier) {
+ if (compilerOptions.module === ModuleKind.System) {
+ return;
+ }
+
if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) {
for (let specifier of exportSpecifiers[name.text]) {
writeLine();
- if (compilerOptions.module === ModuleKind.System) {
- emitStart(specifier.name);
- write(`${exportFunctionForFile}("`);
- emitNodeWithoutSourceMap(specifier.name);
- write(`", `);
- emitExpressionIdentifier(name);
- write(")");
- emitEnd(specifier.name);
- }
- else {
- emitStart(specifier.name);
- emitContainingModuleName(specifier);
- write(".");
- emitNodeWithoutSourceMap(specifier.name);
- emitEnd(specifier.name);
- write(" = ");
- emitExpressionIdentifier(name);
- }
+ emitStart(specifier.name);
+ emitContainingModuleName(specifier);
+ write(".");
+ emitNodeWithCommentsAndWithoutSourcemap(specifier.name);
+ emitEnd(specifier.name);
+ write(" = ");
+ emitExpressionIdentifier(name);
write(";");
}
}
}
+
+ function emitExportSpecifierInSystemModule(specifier: ExportSpecifier): void {
+ Debug.assert(compilerOptions.module === ModuleKind.System);
+
+ writeLine();
+ emitStart(specifier.name);
+ write(`${exportFunctionForFile}("`);
+ emitNodeWithCommentsAndWithoutSourcemap(specifier.name);
+ write(`", `);
+ emitExpressionIdentifier(specifier.propertyName || specifier.name);
+ write(")");
+ emitEnd(specifier.name);
+ write(";");
+ }
function emitDestructuring(root: BinaryExpression | VariableDeclaration | ParameterDeclaration, isAssignmentExpressionStatement: boolean, value?: Expression) {
let emitCount = 0;
@@ -3138,7 +3180,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (exportChanged) {
write(`${exportFunctionForFile}("`);
- emitNodeWithoutSourceMap(name);
+ emitNodeWithCommentsAndWithoutSourcemap(name);
write(`", `);
}
@@ -3370,7 +3412,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (exportChanged) {
write(`${exportFunctionForFile}("`);
- emitNodeWithoutSourceMap(node.name);
+ emitNodeWithCommentsAndWithoutSourcemap(node.name);
write(`", `);
}
@@ -3526,9 +3568,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitEnd(parameter);
write(" { ");
emitStart(parameter);
- emitNodeWithoutSourceMap(paramName);
+ emitNodeWithCommentsAndWithoutSourcemap(paramName);
write(" = ");
- emitNodeWithoutSourceMap(initializer);
+ emitNodeWithCommentsAndWithoutSourcemap(initializer);
emitEnd(parameter);
write("; }");
}
@@ -3551,7 +3593,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitLeadingComments(restParam);
emitStart(restParam);
write("var ");
- emitNodeWithoutSourceMap(restParam.name);
+ emitNodeWithCommentsAndWithoutSourcemap(restParam.name);
write(" = [];");
emitEnd(restParam);
emitTrailingComments(restParam);
@@ -3572,7 +3614,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
increaseIndent();
writeLine();
emitStart(restParam);
- emitNodeWithoutSourceMap(restParam.name);
+ emitNodeWithCommentsAndWithoutSourcemap(restParam.name);
write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];");
emitEnd(restParam);
decreaseIndent();
@@ -3593,7 +3635,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitDeclarationName(node: Declaration) {
if (node.name) {
- emitNodeWithoutSourceMap(node.name);
+ emitNodeWithCommentsAndWithoutSourcemap(node.name);
}
else {
write(getGeneratedNameForNode(node));
@@ -3616,11 +3658,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return emitOnlyPinnedOrTripleSlashComments(node);
}
- if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) {
- // Methods will emit the comments as part of emitting method declaration
+ // TODO (yuisu) : we should not have special cases to condition emitting comments
+ // but have one place to fix check for these conditions.
+ if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature &&
+ node.parent && node.parent.kind !== SyntaxKind.PropertyAssignment &&
+ node.parent.kind !== SyntaxKind.CallExpression) {
+ // 1. Methods will emit the comments as part of emitting method declaration
+
+ // 2. If the function is a property of object literal, emitting leading-comments
+ // is done by emitNodeWithoutSourceMap which then call this function.
+ // In particular, we would like to avoid emit comments twice in following case:
+ // For example:
+ // var obj = {
+ // id:
+ // /*comment*/ () => void
+ // }
+
+ // 3. If the function is an argument in call expression, emitting of comments will be
+ // taken care of in emit list of arguments inside of emitCallexpression
emitLeadingComments(node);
}
+ emitStart(node);
// For targeting below es6, emit functions-like declaration including arrow function using function keyword.
// When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead
if (!shouldEmitAsArrowFunction(node)) {
@@ -3646,6 +3705,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (languageVersion < ScriptTarget.ES6 && node.kind === SyntaxKind.FunctionDeclaration && node.parent === currentSourceFile && node.name) {
emitExportMemberAssignments((node).name);
}
+
+ emitEnd(node);
if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) {
emitTrailingComments(node);
}
@@ -4001,10 +4062,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitMemberAccessForPropertyName(memberName: DeclarationName) {
- // TODO: (jfreeman,drosen): comment on why this is emitNodeWithoutSourceMap instead of emit here.
+ // This does not emit source map because it is emitted by caller as caller
+ // is aware how the property name changes to the property access
+ // eg. public x = 10; becomes this.x and static x = 10 becomes className.x
if (memberName.kind === SyntaxKind.StringLiteral || memberName.kind === SyntaxKind.NumericLiteral) {
write("[");
- emitNodeWithoutSourceMap(memberName);
+ emitNodeWithCommentsAndWithoutSourcemap(memberName);
write("]");
}
else if (memberName.kind === SyntaxKind.ComputedPropertyName) {
@@ -4012,7 +4075,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else {
write(".");
- emitNodeWithoutSourceMap(memberName);
+ emitNodeWithCommentsAndWithoutSourcemap(memberName);
}
}
@@ -4080,10 +4143,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitMemberAccessForPropertyName((member).name);
emitEnd((member).name);
write(" = ");
- emitStart(member);
emitFunctionDeclaration(member);
emitEnd(member);
- emitEnd(member);
write(";");
emitTrailingComments(member);
}
@@ -4254,11 +4315,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDetachedComments(ctor.body.statements);
}
emitCaptureThisForNodeIfNecessary(node);
+ let superCall: ExpressionStatement;
if (ctor) {
emitDefaultValueAssignments(ctor);
emitRestParameter(ctor);
if (baseTypeElement) {
- var superCall = findInitialSuperCall(ctor);
+ superCall = findInitialSuperCall(ctor);
if (superCall) {
writeLine();
emit(superCall);
@@ -4866,6 +4928,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitSerializedTypeNode(node: TypeNode) {
+ if (!node) {
+ return;
+ }
+
switch (node.kind) {
case SyntaxKind.VoidKeyword:
write("void 0");
@@ -4924,14 +4990,22 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */
function emitSerializedTypeReferenceNode(node: TypeReferenceNode) {
- let typeName = node.typeName;
- let result = resolver.getTypeReferenceSerializationKind(node);
+ let location: Node = node.parent;
+ while (isDeclaration(location) || isTypeNode(location)) {
+ location = location.parent;
+ }
+
+ // Clone the type name and parent it to a location outside of the current declaration.
+ let typeName = cloneEntityName(node.typeName);
+ typeName.parent = location;
+
+ let result = resolver.getTypeReferenceSerializationKind(typeName);
switch (result) {
case TypeReferenceSerializationKind.Unknown:
let temp = createAndRecordTempVariable(TempFlags.Auto);
write("(typeof (");
emitNodeWithoutSourceMap(temp);
- write(" = ")
+ write(" = ");
emitEntityNameAsExpression(typeName, /*useFallback*/ true);
write(") === 'function' && ");
emitNodeWithoutSourceMap(temp);
@@ -4990,7 +5064,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
//
// For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.
if (node) {
- var valueDeclaration: FunctionLikeDeclaration;
+ let valueDeclaration: FunctionLikeDeclaration;
if (node.kind === SyntaxKind.ClassDeclaration) {
valueDeclaration = getFirstConstructorWithBody(node);
}
@@ -4999,8 +5073,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (valueDeclaration) {
- var parameters = valueDeclaration.parameters;
- var parameterCount = parameters.length;
+ const parameters = valueDeclaration.parameters;
+ const parameterCount = parameters.length;
if (parameterCount > 0) {
for (var i = 0; i < parameterCount; i++) {
if (i > 0) {
@@ -5008,7 +5082,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (parameters[i].dotDotDotToken) {
- var parameterType = parameters[i].type;
+ let parameterType = parameters[i].type;
if (parameterType.kind === SyntaxKind.ArrayType) {
parameterType = (parameterType).elementType;
}
@@ -5032,7 +5106,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Serializes the return type of function. Used by the __metadata decorator for a method. */
function emitSerializedReturnTypeOfNode(node: Node): string | string[] {
- if (node && isFunctionLike(node)) {
+ if (node && isFunctionLike(node) && (node).type) {
emitSerializedTypeNode((node).type);
return;
}
@@ -5057,6 +5131,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
argumentsWritten++;
}
if (shouldEmitParamTypesMetadata(node)) {
+ debugger;
if (writeComma || argumentsWritten) {
write(", ");
}
@@ -5275,13 +5350,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitExportMemberAssignments(node.name);
}
}
+
+ /*
+ * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
+ * Here we check if alternative name was provided for a given moduleName and return it if possible.
+ */
+ function tryRenameExternalModule(moduleName: LiteralExpression): string {
+ if (currentSourceFile.renamedDependencies && hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
+ return `"${currentSourceFile.renamedDependencies[moduleName.text]}"`
+ }
+ return undefined;
+ }
function emitRequire(moduleName: Expression) {
if (moduleName.kind === SyntaxKind.StringLiteral) {
write("require(");
- emitStart(moduleName);
- emitLiteral(moduleName);
- emitEnd(moduleName);
+ let text = tryRenameExternalModule(moduleName);
+ if (text) {
+ write(text);
+ }
+ else {
+ emitStart(moduleName);
+ emitLiteral(moduleName);
+ emitEnd(moduleName);
+ }
emitToken(SyntaxKind.CloseParenToken, moduleName.end);
}
else {
@@ -5495,11 +5587,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitStart(specifier);
emitContainingModuleName(specifier);
write(".");
- emitNodeWithoutSourceMap(specifier.name);
+ emitNodeWithCommentsAndWithoutSourcemap(specifier.name);
write(" = ");
write(generatedName);
write(".");
- emitNodeWithoutSourceMap(specifier.propertyName || specifier.name);
+ emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name);
write(";");
emitEnd(specifier);
}
@@ -5522,7 +5614,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else {
if (!node.exportClause || resolver.isValueAliasDeclaration(node)) {
- emitStart(node);
write("export ");
if (node.exportClause) {
// export { x, y, ... }
@@ -5535,10 +5626,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (node.moduleSpecifier) {
write(" from ");
- emitNodeWithoutSourceMap(node.moduleSpecifier);
+ emit(node.moduleSpecifier);
}
write(";");
- emitEnd(node);
}
}
}
@@ -5552,13 +5642,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (needsComma) {
write(", ");
}
- emitStart(specifier);
if (specifier.propertyName) {
- emitNodeWithoutSourceMap(specifier.propertyName);
+ emit(specifier.propertyName);
write(" as ");
}
- emitNodeWithoutSourceMap(specifier.name);
- emitEnd(specifier);
+ emit(specifier.name);
needsComma = true;
}
}
@@ -5684,7 +5772,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
let moduleName = getExternalModuleName(importNode);
if (moduleName.kind === SyntaxKind.StringLiteral) {
- return getLiteralText(moduleName);
+ return tryRenameExternalModule(moduleName) || getLiteralText(moduleName);
}
return undefined;
@@ -5820,7 +5908,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
write("}");
writeLine();
- write(`${exportFunctionForFile}(exports);`)
+ write(`${exportFunctionForFile}(exports);`);
decreaseIndent();
writeLine();
write("}");
@@ -5845,7 +5933,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
write("'");
if (node.kind === SyntaxKind.Identifier) {
- emitNodeWithoutSourceMap(node);
+ emitNodeWithCommentsAndWithoutSourcemap(node);
}
else {
emitDeclarationName(node);
@@ -6030,7 +6118,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return compilerOptions.module === ModuleKind.System && isExternalModule(currentSourceFile);
}
- function emitSystemModuleBody(node: SourceFile, startIndex: number): void {
+ function emitSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[], startIndex: number): void {
// shape of the body in system modules:
// function (exports) {
//
@@ -6075,7 +6163,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("return {");
increaseIndent();
writeLine();
- emitSetters(exportStarFunction);
+ emitSetters(exportStarFunction, dependencyGroups);
writeLine();
emitExecute(node, startIndex);
decreaseIndent();
@@ -6084,115 +6172,90 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitTempDeclarations(/*newLine*/ true);
}
- function emitSetters(exportStarFunction: string) {
+ function emitSetters(exportStarFunction: string, dependencyGroups: DependencyGroup[]) {
write("setters:[");
- for (let i = 0; i < externalImports.length; ++i) {
+
+ for (let i = 0; i < dependencyGroups.length; ++i) {
if (i !== 0) {
write(",");
}
writeLine();
increaseIndent();
- let importNode = externalImports[i];
- let importVariableName = getLocalNameForExternalImport(importNode) || "";
- let parameterName = "_" + importVariableName;
+
+ let group = dependencyGroups[i];
+
+ // derive a unique name for parameter from the first named entry in the group
+ let parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || "");
write(`function (${parameterName}) {`);
+ increaseIndent();
+
+ for(let entry of group) {
+ let importVariableName = getLocalNameForExternalImport(entry) || "";
+
+ switch (entry.kind) {
+ case SyntaxKind.ImportDeclaration:
+ if (!(entry).importClause) {
+ // 'import "..."' case
+ // module is imported only for side-effects, no emit required
+ break;
+ }
+ // fall-through
+ case SyntaxKind.ImportEqualsDeclaration:
+ Debug.assert(importVariableName !== "");
- switch (importNode.kind) {
- case SyntaxKind.ImportDeclaration:
- if (!(importNode).importClause) {
- // 'import "..."' case
- // module is imported only for side-effects, setter body will be empty
- break;
- }
- // fall-through
- case SyntaxKind.ImportEqualsDeclaration:
- Debug.assert(importVariableName !== "");
-
- increaseIndent();
- writeLine();
- // save import into the local
- write(`${importVariableName} = ${parameterName};`);
- writeLine();
-
- let defaultName =
- importNode.kind === SyntaxKind.ImportDeclaration
- ? (importNode).importClause.name
- : (importNode).name;
-
- if (defaultName) {
- // emit re-export for imported default name
- // import n1 from 'foo1'
- // import n2 = require('foo2')
- // export {n1}
- // export {n2}
- emitExportMemberAssignments(defaultName);
writeLine();
- }
+ // save import into the local
+ write(`${importVariableName} = ${parameterName};`);
+ writeLine();
+ break;
+ case SyntaxKind.ExportDeclaration:
+ Debug.assert(importVariableName !== "");
- if (importNode.kind === SyntaxKind.ImportDeclaration &&
- (importNode).importClause.namedBindings) {
-
- let namedBindings = (importNode).importClause.namedBindings;
- if (namedBindings.kind === SyntaxKind.NamespaceImport) {
- // emit re-export for namespace
- // import * as n from 'foo'
- // export {n}
- emitExportMemberAssignments((namedBindings).name);
+ if ((entry).exportClause) {
+ // export {a, b as c} from 'foo'
+ // emit as:
+ // exports_({
+ // "a": _["a"],
+ // "c": _["b"]
+ // });
writeLine();
+ write(`${exportFunctionForFile}({`);
+ writeLine();
+ increaseIndent();
+ for (let i = 0, len = (entry).exportClause.elements.length; i < len; ++i) {
+ if (i !== 0) {
+ write(",");
+ writeLine();
+ }
+
+ let e = (entry).exportClause.elements[i];
+ write(`"`);
+ emitNodeWithCommentsAndWithoutSourcemap(e.name);
+ write(`": ${parameterName}["`);
+ emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name);
+ write(`"]`);
+ }
+ decreaseIndent();
+ writeLine();
+ write("});")
}
else {
- // emit re-exports for named imports
- // import {a, b} from 'foo'
- // export {a, b as c}
- for (let element of (namedBindings).elements) {
- emitExportMemberAssignments(element.name || element.propertyName);
- writeLine();
- }
- }
- }
-
- decreaseIndent();
- break;
- case SyntaxKind.ExportDeclaration:
- Debug.assert(importVariableName !== "");
-
- increaseIndent();
-
- if ((importNode).exportClause) {
- // export {a, b as c} from 'foo'
- // emit as:
- // var reexports = {}
- // reexports['a'] = _foo["a"];
- // reexports['c'] = _foo["b"];
- // exports_(reexports);
- let reexportsVariableName = makeUniqueName("reexports");
- writeLine();
- write(`var ${reexportsVariableName} = {};`)
- writeLine();
- for (let e of (importNode).exportClause.elements) {
- write(`${reexportsVariableName}["`);
- emitNodeWithoutSourceMap(e.name);
- write(`"] = ${parameterName}["`);
- emitNodeWithoutSourceMap(e.propertyName || e.name);
- write(`"];`);
writeLine();
+ // export * from 'foo'
+ // emit as:
+ // exportStar(_foo);
+ write(`${exportStarFunction}(${parameterName});`);
}
- write(`${exportFunctionForFile}(${reexportsVariableName});`);
- }
- else {
- writeLine();
- // export * from 'foo'
- // emit as:
- // exportStar(_foo);
- write(`${exportStarFunction}(${parameterName});`);
- }
- writeLine();
- decreaseIndent();
- break;
+ writeLine();
+ break;
+ }
+
}
+ decreaseIndent();
+
write("}");
decreaseIndent();
}
@@ -6205,26 +6268,40 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
for (let i = startIndex; i < node.statements.length; ++i) {
let statement = node.statements[i];
- // - external module related imports/exports are not emitted for system modules
- // - function declarations are not emitted because they were already hoisted
switch (statement.kind) {
- case SyntaxKind.ExportDeclaration:
+ // - function declarations are not emitted because they were already hoisted
+ // - import declarations are not emitted since they are already handled in setters
+ // - export declarations with module specifiers are not emitted since they were already written in setters
+ // - export declarations without module specifiers are emitted preserving the order
+ case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ImportDeclaration:
- case SyntaxKind.FunctionDeclaration:
+ continue;
+ case SyntaxKind.ExportDeclaration:
+ if (!(statement).moduleSpecifier) {
+ for (let element of (statement).exportClause.elements) {
+ // write call to exporter function for every export specifier in exports list
+ emitExportSpecifierInSystemModule(element);
+ }
+ }
continue;
case SyntaxKind.ImportEqualsDeclaration:
if (!isInternalModuleImportEqualsDeclaration(statement)) {
+ // - import equals declarations that import external modules are not emitted
continue;
}
- }
- writeLine();
- emit(statement);
+ // fall-though for import declarations that import internal modules
+ default:
+ writeLine();
+ emit(statement);
+ }
}
decreaseIndent();
writeLine();
write("}"); // execute
}
-
+
+ type DependencyGroup = Array;
+
function emitSystemModule(node: SourceFile, startIndex: number): void {
collectExternalModuleInfo(node);
// System modules has the following shape
@@ -6244,18 +6321,35 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`"${node.moduleName}", `);
}
write("[");
+
+ let groupIndices: Map = {};
+ let dependencyGroups: DependencyGroup[] = [];
+
for (let i = 0; i < externalImports.length; ++i) {
let text = getExternalModuleNameText(externalImports[i]);
+ if (hasProperty(groupIndices, text)) {
+ // deduplicate/group entries in dependency list by the dependency name
+ let groupIndex = groupIndices[text];
+ dependencyGroups[groupIndex].push(externalImports[i]);
+ continue;
+ }
+ else {
+ groupIndices[text] = dependencyGroups.length;
+ dependencyGroups.push([externalImports[i]]);
+ }
+
if (i !== 0) {
write(", ");
}
+
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
writeLine();
increaseIndent();
+ emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
- emitSystemModuleBody(node, startIndex);
+ emitSystemModuleBody(node, dependencyGroups, startIndex);
decreaseIndent();
writeLine();
write("});");
@@ -6325,6 +6419,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitAMDModule(node: SourceFile, startIndex: number) {
+ emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
@@ -6346,6 +6441,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitCommonJSModule(node: SourceFile, startIndex: number) {
+ emitEmitHelpers(node);
collectExternalModuleInfo(node);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
@@ -6355,6 +6451,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitUMDModule(node: SourceFile, startIndex: number) {
+ emitEmitHelpers(node);
collectExternalModuleInfo(node);
// Module is detected first to support Browserify users that load into a browser with an AMD loader
@@ -6384,6 +6481,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = false;
+ emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
@@ -6429,7 +6527,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (isLineBreak(c)) {
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
- result = (result ? result + '" + \' \' + "' : '') + part;
+ result = (result ? result + "\" + ' ' + \"" : "") + part;
}
firstNonWhitespace = -1;
}
@@ -6442,7 +6540,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
if (firstNonWhitespace !== -1) {
let part = text.substr(firstNonWhitespace);
- result = (result ? result + '" + \' \' + "' : '') + part;
+ result = (result ? result + "\" + ' ' + \"" : "") + part;
}
return result;
@@ -6467,14 +6565,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitJsxText(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
- write('"');
+ write("\"");
write(trimReactWhitespace(node));
- write('"');
+ write("\"");
break;
case JsxEmit.Preserve:
default: // Emit JSX-preserve as default when no --jsx flag is specified
- write(getTextOfNode(node, true));
+ writer.writeLiteral(getTextOfNode(node, true));
break;
}
}
@@ -6484,9 +6582,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
switch (compilerOptions.jsx) {
case JsxEmit.Preserve:
default:
- write('{');
+ write("{");
emit(node.expression);
- write('}');
+ write("}");
break;
case JsxEmit.React:
emit(node.expression);
@@ -6522,14 +6620,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
- function emitSourceFileNode(node: SourceFile) {
- // Start new file on new line
- writeLine();
- emitDetachedComments(node);
-
- // emit prologue directives prior to __extends
- let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
-
+ function emitEmitHelpers(node: SourceFile): void {
// Only emit helpers if the user did not say otherwise.
if (!compilerOptions.noEmitHelpers) {
// Only Emit __extends function when target ES5.
@@ -6557,6 +6648,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
awaiterEmitted = true;
}
}
+ }
+
+ function emitSourceFileNode(node: SourceFile) {
+ // Start new file on new line
+ writeLine();
+ emitShebang();
+ emitDetachedComments(node);
+
+ // emit prologue directives prior to __extends
+ let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
if (isExternalModule(node) || compilerOptions.isolatedModules) {
if (languageVersion >= ScriptTarget.ES6) {
@@ -6580,6 +6681,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = false;
+ emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
emitTempDeclarations(/*newLine*/ true);
@@ -6588,28 +6690,41 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitLeadingComments(node.endOfFileToken);
}
- function emitNodeWithoutSourceMap(node: Node): void {
- if (!node) {
- return;
- }
+ function emitNodeWithCommentsAndWithoutSourcemap(node: Node): void {
+ emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap);
+ }
- if (node.flags & NodeFlags.Ambient) {
- return emitOnlyPinnedOrTripleSlashComments(node);
- }
+ function emitNodeConsideringCommentsOption(node: Node, emitNodeConsideringSourcemap: (node: Node) => void): void {
+ if (node) {
+ if (node.flags & NodeFlags.Ambient) {
+ return emitOnlyPinnedOrTripleSlashComments(node);
+ }
- let emitComments = shouldEmitLeadingAndTrailingComments(node);
- if (emitComments) {
- emitLeadingComments(node);
- }
+ if (isSpecializedCommentHandling(node)) {
+ // This is the node that will handle its own comments and sourcemap
+ return emitNodeWithoutSourceMap(node);
+ }
- emitJavaScriptWorker(node);
+ let emitComments = shouldEmitLeadingAndTrailingComments(node);
+ if (emitComments) {
+ emitLeadingComments(node);
+ }
- if (emitComments) {
- emitTrailingComments(node);
+ emitNodeConsideringSourcemap(node);
+
+ if (emitComments) {
+ emitTrailingComments(node);
+ }
}
}
- function shouldEmitLeadingAndTrailingComments(node: Node) {
+ function emitNodeWithoutSourceMap(node: Node): void {
+ if (node) {
+ emitJavaScriptWorker(node);
+ }
+ }
+
+ function isSpecializedCommentHandling(node: Node): boolean {
switch (node.kind) {
// All of these entities are emitted in a specialized fashion. As such, we allow
// the specialized methods for each to handle the comments on the nodes.
@@ -6619,8 +6734,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ExportAssignment:
- return false;
+ return true;
+ }
+ }
+ function shouldEmitLeadingAndTrailingComments(node: Node) {
+ switch (node.kind) {
case SyntaxKind.VariableStatement:
return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node);
@@ -6635,6 +6754,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return shouldEmitEnumDeclaration(node);
}
+ // If the node is emitted in specialized fashion, dont emit comments as this node will handle
+ // emitting comments when emitting itself
+ Debug.assert(!isSpecializedCommentHandling(node));
+
// If this is the expression body of an arrow function that we're down-leveling,
// then we don't want to emit comments when we emit the body. It will have already
// been taken care of when we emitted the 'return' statement for the function
@@ -6841,6 +6964,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return leadingComments;
}
+ /**
+ * Removes all but the pinned or triple slash comments.
+ * @param ranges The array to be filtered
+ * @param onlyPinnedOrTripleSlashComments whether the filtering should be performed.
+ */
function filterComments(ranges: CommentRange[], onlyPinnedOrTripleSlashComments: boolean): CommentRange[] {
// If we're removing comments, then we want to strip out all but the pinned or
// triple slash comments.
@@ -6906,6 +7034,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
}
+ /**
+ * Emit trailing comments at the position. The term trailing comment is used here to describe following comment:
+ * x, /comment1/ y
+ * ^ => pos; the function will emit "comment1" in the emitJS
+ */
+ function emitTrailingCommentsOfPosition(pos: number) {
+ let trailingComments = filterComments(getTrailingCommentRanges(currentSourceFile.text, pos), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
+
+ // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
+ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
+ }
+
function emitLeadingCommentsOfPosition(pos: number) {
let leadingComments: CommentRange[];
if (hasDetachedComments(pos)) {
@@ -6968,6 +7108,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
}
+
+ function emitShebang() {
+ let shebang = getShebang(currentSourceFile.text);
+ if (shebang) {
+ write(shebang);
+ }
+ }
function isPinnedOrTripleSlashComment(comment: CommentRange) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts
index 127d1b58ee4..def08e81758 100644
--- a/src/compiler/parser.ts
+++ b/src/compiler/parser.ts
@@ -844,6 +844,10 @@ namespace ts {
return token = scanner.scanJsxIdentifier();
}
+ function scanJsxText(): SyntaxKind {
+ return token = scanner.scanJsxToken();
+ }
+
function speculationHelper(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
@@ -913,9 +917,11 @@ namespace ts {
return token > SyntaxKind.LastReservedWord;
}
- function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean {
+ function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage, shouldAdvance = true): boolean {
if (token === kind) {
- nextToken();
+ if (shouldAdvance) {
+ nextToken();
+ }
return true;
}
@@ -3148,7 +3154,7 @@ namespace ts {
}
function parseAwaitExpression() {
- var node = createNode(SyntaxKind.AwaitExpression);
+ const node = createNode(SyntaxKind.AwaitExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
@@ -3178,7 +3184,7 @@ namespace ts {
return parseTypeAssertion();
}
if (lookAhead(nextTokenIsIdentifierOrKeyword)) {
- return parseJsxElementOrSelfClosingElement();
+ return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true);
}
// Fall through
default:
@@ -3308,14 +3314,14 @@ namespace ts {
return finishNode(node);
}
- function parseJsxElementOrSelfClosingElement(): JsxElement|JsxSelfClosingElement {
- let opening = parseJsxOpeningOrSelfClosingElement();
+ function parseJsxElementOrSelfClosingElement(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement {
+ let opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext);
if (opening.kind === SyntaxKind.JsxOpeningElement) {
let node = createNode(SyntaxKind.JsxElement, opening.pos);
node.openingElement = opening;
node.children = parseJsxChildren(node.openingElement.tagName);
- node.closingElement = parseJsxClosingElement();
+ node.closingElement = parseJsxClosingElement(inExpressionContext);
return finishNode(node);
}
else {
@@ -3336,11 +3342,11 @@ namespace ts {
case SyntaxKind.JsxText:
return parseJsxText();
case SyntaxKind.OpenBraceToken:
- return parseJsxExpression();
+ return parseJsxExpression(/*inExpressionContext*/ false);
case SyntaxKind.LessThanToken:
- return parseJsxElementOrSelfClosingElement();
+ return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false);
}
- Debug.fail('Unknown JSX child kind ' + token);
+ Debug.fail("Unknown JSX child kind " + token);
}
function parseJsxChildren(openingTagName: EntityName): NodeArray {
@@ -3368,7 +3374,7 @@ namespace ts {
return result;
}
- function parseJsxOpeningOrSelfClosingElement(): JsxOpeningElement|JsxSelfClosingElement {
+ function parseJsxOpeningOrSelfClosingElement(inExpressionContext: boolean): JsxOpeningElement|JsxSelfClosingElement {
let fullStart = scanner.getStartPos();
parseExpected(SyntaxKind.LessThanToken);
@@ -3378,12 +3384,22 @@ namespace ts {
let attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute);
let node: JsxOpeningLikeElement;
- if (parseOptional(SyntaxKind.GreaterThanToken)) {
+ if (token === SyntaxKind.GreaterThanToken) {
+ // Closing tag, so scan the immediately-following text with the JSX scanning instead
+ // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
+ // scanning errors
node = createNode(SyntaxKind.JsxOpeningElement, fullStart);
+ scanJsxText();
}
else {
parseExpected(SyntaxKind.SlashToken);
- parseExpected(SyntaxKind.GreaterThanToken);
+ if (inExpressionContext) {
+ parseExpected(SyntaxKind.GreaterThanToken);
+ }
+ else {
+ parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
+ scanJsxText();
+ }
node = createNode(SyntaxKind.JsxSelfClosingElement, fullStart);
}
@@ -3406,14 +3422,20 @@ namespace ts {
return elementName;
}
- function parseJsxExpression(): JsxExpression {
+ function parseJsxExpression(inExpressionContext: boolean): JsxExpression {
let node = createNode(SyntaxKind.JsxExpression);
parseExpected(SyntaxKind.OpenBraceToken);
if (token !== SyntaxKind.CloseBraceToken) {
node.expression = parseExpression();
}
- parseExpected(SyntaxKind.CloseBraceToken);
+ if (inExpressionContext) {
+ parseExpected(SyntaxKind.CloseBraceToken);
+ }
+ else {
+ parseExpected(SyntaxKind.CloseBraceToken, /*message*/ undefined, /*advance*/ false);
+ scanJsxText();
+ }
return finishNode(node);
}
@@ -3432,7 +3454,7 @@ namespace ts {
node.initializer = parseLiteralNode();
break;
default:
- node.initializer = parseJsxExpression();
+ node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
break;
}
}
@@ -3448,11 +3470,17 @@ namespace ts {
return finishNode(node);
}
- function parseJsxClosingElement(): JsxClosingElement {
+ function parseJsxClosingElement(inExpressionContext: boolean): JsxClosingElement {
let node = createNode(SyntaxKind.JsxClosingElement);
parseExpected(SyntaxKind.LessThanSlashToken);
node.tagName = parseJsxElementName();
- parseExpected(SyntaxKind.GreaterThanToken);
+ if (inExpressionContext) {
+ parseExpected(SyntaxKind.GreaterThanToken);
+ }
+ else {
+ parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
+ scanJsxText();
+ }
return finishNode(node);
}
@@ -5140,7 +5168,7 @@ namespace ts {
// the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
// If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
if (token === SyntaxKind.FromKeyword || (token === SyntaxKind.StringLiteral && !scanner.hasPrecedingLineBreak())) {
- parseExpected(SyntaxKind.FromKeyword)
+ parseExpected(SyntaxKind.FromKeyword);
node.moduleSpecifier = parseModuleSpecifier();
}
}
@@ -6011,7 +6039,7 @@ namespace ts {
return;
function visitNode(node: IncrementalNode) {
- let text = '';
+ let text = "";
if (aggressiveChecks && shouldCheckNode(node)) {
text = oldText.substring(node.pos, node.end);
}
diff --git a/src/compiler/program.ts b/src/compiler/program.ts
index 4b1f10eb649..ceb4e5fb033 100644
--- a/src/compiler/program.ts
+++ b/src/compiler/program.ts
@@ -8,6 +8,9 @@ namespace ts {
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
+
+ let emptyArray: any[] = [];
+
export const version = "1.6.0";
export function findConfigFile(searchPath: string): string {
@@ -25,6 +28,62 @@ namespace ts {
}
return undefined;
}
+
+ export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
+ let basePath = getDirectoryPath(containingFile);
+ let referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
+ return normalizePath(referencedFileName);
+ }
+
+ export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
+ // TODO: use different resolution strategy based on compiler options
+ return legacyNameResolver(moduleName, containingFile, compilerOptions, host);
+ }
+
+ function legacyNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
+
+ // module names that contain '!' are used to reference resources and are not resolved to actual files on disk
+ if (moduleName.indexOf('!') != -1) {
+ return { resolvedFileName: undefined, failedLookupLocations: [] };
+ }
+
+ let searchPath = getDirectoryPath(containingFile);
+ let searchName: string;
+
+ let failedLookupLocations: string[] = [];
+
+ let referencedSourceFile: string;
+ while (true) {
+ searchName = normalizePath(combinePaths(searchPath, moduleName));
+ referencedSourceFile = forEach(supportedExtensions, extension => {
+ if (extension === ".tsx" && !compilerOptions.jsx) {
+ // resolve .tsx files only if jsx support is enabled
+ // 'logical not' handles both undefined and None cases
+ return undefined;
+ }
+
+ let candidate = searchName + extension;
+ if (host.fileExists(candidate)) {
+ return candidate;
+ }
+ else {
+ failedLookupLocations.push(candidate);
+ }
+ });
+
+ if (referencedSourceFile) {
+ break;
+ }
+
+ let parentPath = getDirectoryPath(searchPath);
+ if (parentPath === searchPath) {
+ break;
+ }
+ searchPath = parentPath;
+ }
+
+ return { resolvedFileName: referencedSourceFile, failedLookupLocations };
+ }
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
let currentDirectory: string;
@@ -92,7 +151,8 @@ namespace ts {
}
const newLine = getNewLineCharacter(options);
-
+
+
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
@@ -100,7 +160,9 @@ namespace ts {
getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
- getNewLine: () => newLine
+ getNewLine: () => newLine,
+ fileExists: fileName => sys.fileExists(fileName),
+ readFile: fileName => sys.readFile(fileName)
};
}
@@ -143,7 +205,7 @@ namespace ts {
}
}
- export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program {
+ export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let diagnostics = createDiagnosticCollection();
@@ -158,24 +220,56 @@ namespace ts {
let start = new Date().getTime();
host = host || createCompilerHost(options);
+
+ // initialize resolveModuleNameWorker only if noResolve is false
+ let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => string[];
+ if (!options.noResolve) {
+ resolveModuleNamesWorker = host.resolveModuleNames;
+ if (!resolveModuleNamesWorker) {
+ resolveModuleNamesWorker = (moduleNames, containingFile) => {
+ return map(moduleNames, moduleName => {
+ let moduleResolution = resolveModuleName(moduleName, containingFile, options, host);
+ return moduleResolution.resolvedFileName;
+ });
+ }
+ }
+ }
let filesByName = createFileMap(fileName => host.getCanonicalFileName(fileName));
-
- forEach(rootNames, name => processRootFile(name, /*isDefaultLib:*/ false));
-
- // Do not process the default library if:
- // - The '--noLib' flag is used.
- // - A 'no-default-lib' reference comment is encountered in
- // processing the root files.
- if (!skipDefaultLib) {
- processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib:*/ true);
+
+ if (oldProgram) {
+ // check properties that can affect structure of the program or module resolution strategy
+ // if any of these properties has changed - structure cannot be reused
+ let oldOptions = oldProgram.getCompilerOptions();
+ if ((oldOptions.module !== options.module) ||
+ (oldOptions.noResolve !== options.noResolve) ||
+ (oldOptions.target !== options.target) ||
+ (oldOptions.noLib !== options.noLib) ||
+ (oldOptions.jsx !== options.jsx)) {
+ oldProgram = undefined;
+ }
+ }
+
+ if (!tryReuseStructureFromOldProgram()) {
+ forEach(rootNames, name => processRootFile(name, false));
+ // Do not process the default library if:
+ // - The '--noLib' flag is used.
+ // - A 'no-default-lib' reference comment is encountered in
+ // processing the root files.
+ if (!skipDefaultLib) {
+ processRootFile(host.getDefaultLibFileName(options), true);
+ }
}
verifyCompilerOptions();
+ // unconditionally set oldProgram to undefined to prevent it from being captured in closure
+ oldProgram = undefined;
+
programTime += new Date().getTime() - start;
program = {
+ getRootFileNames: () => rootNames,
getSourceFile: getSourceFile,
getSourceFiles: () => files,
getCompilerOptions: () => options,
@@ -211,6 +305,82 @@ namespace ts {
return classifiableNames;
}
+ function tryReuseStructureFromOldProgram(): boolean {
+ if (!oldProgram) {
+ return false;
+ }
+
+ Debug.assert(!oldProgram.structureIsReused);
+
+ // there is an old program, check if we can reuse its structure
+ let oldRootNames = oldProgram.getRootFileNames();
+ if (!arrayIsEqualTo(oldRootNames, rootNames)) {
+ return false;
+ }
+
+ // check if program source files has changed in the way that can affect structure of the program
+ let newSourceFiles: SourceFile[] = [];
+ for (let oldSourceFile of oldProgram.getSourceFiles()) {
+ let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
+ if (!newSourceFile) {
+ return false;
+ }
+
+ if (oldSourceFile !== newSourceFile) {
+ if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
+ // value of no-default-lib has changed
+ // this will affect if default library is injected into the list of files
+ return false;
+ }
+
+ // check tripleslash references
+ if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
+ // tripleslash references has changed
+ return false;
+ }
+
+ // check imports
+ collectExternalModuleReferences(newSourceFile);
+ if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
+ // imports has changed
+ return false;
+ }
+
+ if (resolveModuleNamesWorker) {
+ let moduleNames = map(newSourceFile.imports, name => name.text);
+ let resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName);
+ // ensure that module resolution results are still correct
+ for (let i = 0; i < moduleNames.length; ++i) {
+ let oldResolution = getResolvedModuleFileName(oldSourceFile, moduleNames[i]);
+ if (oldResolution !== resolutions[i]) {
+ return false;
+ }
+ }
+ }
+ // pass the cache of module resolutions from the old source file
+ newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
+ }
+ else {
+ // file has no changes - use it as is
+ newSourceFile = oldSourceFile;
+ }
+
+ // if file has passed all checks it should be safe to reuse it
+ newSourceFiles.push(newSourceFile);
+ }
+
+ // update fileName -> file mapping
+ for (let file of newSourceFiles) {
+ filesByName.set(file.fileName, file);
+ }
+
+ files = newSourceFiles;
+
+ oldProgram.structureIsReused = true;
+
+ return true;
+ }
+
function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost {
return {
getCanonicalFileName: fileName => host.getCanonicalFileName(fileName),
@@ -370,16 +540,66 @@ namespace ts {
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
+ }
+
+ function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean {
+ return a.fileName === b.fileName;
+ }
+
+ function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean {
+ return a.text === b.text;
+ }
+
+ function collectExternalModuleReferences(file: SourceFile): void {
+ if (file.imports) {
+ return;
+ }
+
+ let imports: LiteralExpression[];
+ for (let node of file.statements) {
+ switch (node.kind) {
+ case SyntaxKind.ImportDeclaration:
+ case SyntaxKind.ImportEqualsDeclaration:
+ case SyntaxKind.ExportDeclaration:
+ let moduleNameExpr = getExternalModuleName(node);
+ if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) {
+ break;
+ }
+ if (!(moduleNameExpr).text) {
+ break;
+ }
+
+ (imports || (imports = [])).push(moduleNameExpr);
+ break;
+ case SyntaxKind.ModuleDeclaration:
+ if ((node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
+ // TypeScript 1.0 spec (April 2014): 12.1.6
+ // An AmbientExternalModuleDeclaration declares an external module.
+ // This type of declaration is permitted only in the global module.
+ // The StringLiteral must specify a top - level external module name.
+ // Relative external module names are not permitted
+ forEachChild((node).body, node => {
+ if (isExternalModuleImportEqualsDeclaration(node) &&
+ getExternalModuleImportEqualsDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
+ let moduleName = getExternalModuleImportEqualsDeclarationExpression(node);
+ // TypeScript 1.0 spec (April 2014): 12.1.6
+ // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
+ // only through top - level external module names. Relative external module names are not permitted.
+ if (moduleName) {
+ (imports || (imports = [])).push(moduleName);
+ }
+ }
+ });
+ }
+ break;
+ }
+ }
+
+ file.imports = imports || emptyArray;
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
- let start: number;
- let length: number;
let diagnosticArgument: string[];
- if (refEnd !== undefined && refPos !== undefined) {
- start = refPos;
- length = refEnd - refPos;
- }
let diagnostic: DiagnosticMessage;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) {
@@ -411,8 +631,8 @@ namespace ts {
}
if (diagnostic) {
- if (refFile) {
- diagnostics.add(createFileDiagnostic(refFile, start, length, diagnostic, ...diagnosticArgument));
+ if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
+ diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
else {
diagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
@@ -421,7 +641,7 @@ namespace ts {
}
// Get source file from normalized fileName
- function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile {
+ function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
let canonicalName = host.getCanonicalFileName(normalizeSlashes(fileName));
if (filesByName.contains(canonicalName)) {
// We've already looked for this file, use cached result
@@ -436,8 +656,8 @@ namespace ts {
// We haven't looked for this file, do so now and cache result
let file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
- if (refFile) {
- diagnostics.add(createFileDiagnostic(refFile, refStart, refLength,
+ if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
+ diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
@@ -473,8 +693,13 @@ namespace ts {
if (file && host.useCaseSensitiveFileNames()) {
let sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;
if (canonicalName !== sourceFileName) {
- diagnostics.add(createFileDiagnostic(refFile, refStart, refLength,
- Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
+ if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
+ diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
+ Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
+ }
+ else {
+ diagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
+ }
}
}
return file;
@@ -483,60 +708,35 @@ namespace ts {
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
- let referencedFileName = isRootedDiskPath(ref.fileName) ? ref.fileName : combinePaths(basePath, ref.fileName);
- processSourceFile(normalizePath(referencedFileName), /* isDefaultLib */ false, file, ref.pos, ref.end);
+ let referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
+ processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
-
- function processImportedModules(file: SourceFile, basePath: string) {
- forEach(file.statements, node => {
- if (node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.ExportDeclaration) {
- let moduleNameExpr = getExternalModuleName(node);
- if (moduleNameExpr && moduleNameExpr.kind === SyntaxKind.StringLiteral) {
- let moduleNameText = (moduleNameExpr).text;
- if (moduleNameText) {
- let searchPath = basePath;
- let searchName: string;
- while (true) {
- searchName = normalizePath(combinePaths(searchPath, moduleNameText));
- if (forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, moduleNameExpr))) {
- break;
- }
- let parentPath = getDirectoryPath(searchPath);
- if (parentPath === searchPath) {
- break;
- }
- searchPath = parentPath;
- }
- }
+
+ function processImportedModules(file: SourceFile, basePath: string) {
+ collectExternalModuleReferences(file);
+ if (file.imports.length) {
+ file.resolvedModules = {};
+ let oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
+
+ let moduleNames = map(file.imports, name => name.text);
+ let resolutions = resolveModuleNamesWorker(moduleNames, file.fileName);
+ for (let i = 0; i < file.imports.length; ++i) {
+ let resolution = resolutions[i];
+ setResolvedModuleName(file, moduleNames[i], resolution);
+ if (resolution) {
+ findModuleSourceFile(resolution, file.imports[i]);
}
- }
- else if (node.kind === SyntaxKind.ModuleDeclaration && (node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
- // TypeScript 1.0 spec (April 2014): 12.1.6
- // An AmbientExternalModuleDeclaration declares an external module.
- // This type of declaration is permitted only in the global module.
- // The StringLiteral must specify a top - level external module name.
- // Relative external module names are not permitted
- forEachChild((node).body, node => {
- if (isExternalModuleImportEqualsDeclaration(node) &&
- getExternalModuleImportEqualsDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
-
- let nameLiteral = getExternalModuleImportEqualsDeclarationExpression(node);
- let moduleName = nameLiteral.text;
- if (moduleName) {
- // TypeScript 1.0 spec (April 2014): 12.1.6
- // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
- // only through top - level external module names. Relative external module names are not permitted.
- let searchName = normalizePath(combinePaths(basePath, moduleName));
- forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, nameLiteral));
- }
- }
- });
- }
- });
+ }
+ }
+ else {
+ // no imports - drop cached module resolutions
+ file.resolvedModules = undefined;
+ }
+ return;
function findModuleSourceFile(fileName: string, nameLiteral: Expression) {
- return findSourceFile(fileName, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos);
+ return findSourceFile(fileName, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end);
}
}
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts
index d52f96c912b..2f73c9c8820 100644
--- a/src/compiler/scanner.ts
+++ b/src/compiler/scanner.ts
@@ -319,14 +319,21 @@ namespace ts {
}
/* @internal */
+ /**
+ * We assume the first line starts at position 0 and 'position' is non-negative.
+ */
export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) {
let lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
// If the actual position was not found,
- // the binary search returns the negative value of the next line start
+ // the binary search returns the 2's-complement of the next line start
// e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
- // then the search will return -2
+ // then the search will return -2.
+ //
+ // We want the index of the previous line start, so we subtract 1.
+ // Review 2's-complement if this is confusing.
lineNumber = ~lineNumber - 1;
+ Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
}
return {
line: lineNumber,
@@ -401,6 +408,9 @@ namespace ts {
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
+ case CharacterCodes.hash:
+ // Only if its the beginning can we have #! trivia
+ return pos === 0;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
@@ -461,6 +471,13 @@ namespace ts {
}
break;
+ case CharacterCodes.hash:
+ if (isShebangTrivia(text, pos)) {
+ pos = scanShebangTrivia(text, pos);
+ continue;
+ }
+ break;
+
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
@@ -528,13 +545,31 @@ namespace ts {
return pos;
}
- // Extract comments from the given source text starting at the given position. If trailing is
- // false, whitespace is skipped until the first line break and comments between that location
- // and the next token are returned.If trailing is true, comments occurring between the given
- // position and the next line break are returned.The return value is an array containing a
- // TextRange for each comment. Single-line comment ranges include the beginning '//' characters
- // but not the ending line break. Multi - line comment ranges include the beginning '/* and
- // ending '*/' characters.The return value is undefined if no comments were found.
+ const shebangTriviaRegex = /^#!.*/;
+
+ function isShebangTrivia(text: string, pos: number) {
+ // Shebangs check must only be done at the start of the file
+ Debug.assert(pos === 0);
+ return shebangTriviaRegex.test(text);
+ }
+
+ function scanShebangTrivia(text: string, pos: number) {
+ let shebang = shebangTriviaRegex.exec(text)[0];
+ pos = pos + shebang.length;
+ return pos;
+ }
+
+ /**
+ * Extract comments from text prefixing the token closest following `pos`.
+ * The return value is an array containing a TextRange for each comment.
+ * Single-line comment ranges include the beginning '//' characters but not the ending line break.
+ * Multi - line comment ranges include the beginning '/* and ending '/' characters.
+ * The return value is undefined if no comments were found.
+ * @param trailing
+ * If false, whitespace is skipped until the first line break and comments between that location
+ * and the next token are returned.
+ * If true, comments occurring between the given position and the next line break are returned.
+ */
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
let collecting = trailing || pos === 0;
@@ -617,6 +652,13 @@ namespace ts {
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}
+
+ /** Optionally, get the shebang */
+ export function getShebang(text: string): string {
+ return shebangTriviaRegex.test(text)
+ ? shebangTriviaRegex.exec(text)[0]
+ : undefined;
+ }
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
@@ -629,9 +671,8 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
-
- /* @internal */
- // Creates a scanner over a (possibly unspecified) range of a piece of text.
+
+ // Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
@@ -1087,6 +1128,18 @@ namespace ts {
return token = SyntaxKind.EndOfFileToken;
}
let ch = text.charCodeAt(pos);
+
+ // Special handling for shebang
+ if (ch === CharacterCodes.hash && pos === 0 && isShebangTrivia(text, pos)) {
+ pos = scanShebangTrivia(text, pos);
+ if (skipTrivia) {
+ continue;
+ }
+ else {
+ return token = SyntaxKind.ShebangTrivia;
+ }
+ }
+
switch (ch) {
case CharacterCodes.lineFeed:
case CharacterCodes.carriageReturn:
diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts
index 228b9516de1..5b46324601b 100644
--- a/src/compiler/sys.ts
+++ b/src/compiler/sys.ts
@@ -30,8 +30,8 @@ namespace ts {
declare var global: any;
declare var __filename: string;
declare var Buffer: {
- new (str: string, encoding ?: string): any;
- }
+ new (str: string, encoding?: string): any;
+ };
declare class Enumerator {
public atEnd(): boolean;
@@ -188,13 +188,13 @@ namespace ts {
};
}
function getNodeSystem(): System {
- var _fs = require("fs");
- var _path = require("path");
- var _os = require('os');
+ const _fs = require("fs");
+ const _path = require("path");
+ const _os = require("os");
- var platform: string = _os.platform();
+ const platform: string = _os.platform();
// win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
- var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
+ const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
@@ -228,7 +228,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void {
// If a BOM is required, emit one
if (writeByteOrderMark) {
- data = '\uFEFF' + data;
+ data = "\uFEFF" + data;
}
_fs.writeFileSync(fileName, data, "utf8");
@@ -271,10 +271,10 @@ namespace ts {
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
write(s: string): void {
- var buffer = new Buffer(s, 'utf8');
- var offset: number = 0;
- var toWrite: number = buffer.length;
- var written = 0;
+ const buffer = new Buffer(s, "utf8");
+ let offset: number = 0;
+ let toWrite: number = buffer.length;
+ let written = 0;
// 1 is a standard descriptor for stdout
while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) {
offset += written;
@@ -297,7 +297,7 @@ namespace ts {
}
callback(fileName);
- };
+ }
},
resolvePath: function (path: string): string {
return _path.resolve(path);
@@ -334,7 +334,9 @@ namespace ts {
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
- else if (typeof module !== "undefined" && module.exports) {
+ else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
+ // process and process.nextTick checks if current environment is node-like
+ // process.browser check excludes webpack and browserify
return getNodeSystem();
}
else {
diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts
index a657cc8c314..c322187fa14 100644
--- a/src/compiler/tsc.ts
+++ b/src/compiler/tsc.ts
@@ -3,7 +3,7 @@
namespace ts {
export interface SourceFile {
- fileWatcher: FileWatcher;
+ fileWatcher?: FileWatcher;
}
/**
@@ -14,7 +14,7 @@ namespace ts {
let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
- errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
+ errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
return false;
}
@@ -49,7 +49,7 @@ namespace ts {
}
// TODO: Add codePage support for readFile?
- let fileContents = '';
+ let fileContents = "";
try {
fileContents = sys.readFile(filePath);
}
@@ -245,7 +245,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
}
- function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
+ function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
let sourceFile = cachedProgram.getSourceFile(fileName);
@@ -355,22 +355,23 @@ namespace ts {
return { program, exitStatus };
function compileProgram(): ExitStatus {
- // First get any syntactic errors.
- let diagnostics = program.getSyntacticDiagnostics();
- reportDiagnostics(diagnostics);
+ let diagnostics: Diagnostic[];
+
+ // First get and report any syntactic errors.
+ diagnostics = program.getSyntacticDiagnostics();
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === 0) {
- let diagnostics = program.getGlobalDiagnostics();
- reportDiagnostics(diagnostics);
+ diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics());
if (diagnostics.length === 0) {
- let diagnostics = program.getSemanticDiagnostics();
- reportDiagnostics(diagnostics);
+ diagnostics = program.getSemanticDiagnostics();
}
}
+ reportDiagnostics(diagnostics);
+
// If the user doesn't want us to emit, then we're done at this point.
if (compilerOptions.noEmit) {
return diagnostics.length
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index 21eed30c244..1338d19e1a7 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -9,6 +9,7 @@ namespace ts {
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
+ clear(): void;
}
export interface TextRange {
@@ -17,6 +18,7 @@ namespace ts {
}
// token > SyntaxKind.Identifer => token is a keyword
+ // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
export const enum SyntaxKind {
Unknown,
EndOfFileToken,
@@ -24,6 +26,8 @@ namespace ts {
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
+ // We detect and preserve #! on the first line
+ ShebangTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
@@ -583,9 +587,9 @@ namespace ts {
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
* Examples:
- * FunctionDeclaration
- * MethodDeclaration
- * AccessorDeclaration
+ * - FunctionDeclaration
+ * - MethodDeclaration
+ * - AccessorDeclaration
*/
export interface FunctionLikeDeclaration extends SignatureDeclaration {
_functionLikeDeclarationBrand: any;
@@ -1240,6 +1244,10 @@ namespace ts {
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
+
+ // this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
+ /* @internal */
+ renamedDependencies?: Map;
/**
* lib.d.ts should have a reference comment like
@@ -1272,8 +1280,12 @@ namespace ts {
// Stores a line map for the file.
// This field should never be used directly to obtain line map, use getLineMap function instead.
/* @internal */ lineMap: number[];
-
/* @internal */ classifiableNames?: Map;
+ // Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
+ // It is used to resolve module names in the checker.
+ // Content of this fiels should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
+ /* @internal */ resolvedModules: Map;
+ /* @internal */ imports: LiteralExpression[];
}
export interface ScriptReferenceHost {
@@ -1282,7 +1294,7 @@ namespace ts {
getCurrentDirectory(): string;
}
- export interface ParseConfigHost {
+ export interface ParseConfigHost extends ModuleResolutionHost {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
@@ -1300,6 +1312,12 @@ namespace ts {
}
export interface Program extends ScriptReferenceHost {
+
+ /**
+ * Get a list of root file names that were passed to a 'createProgram'
+ */
+ getRootFileNames(): string[]
+
/**
* Get a list of files in the program
*/
@@ -1340,6 +1358,9 @@ namespace ts {
/* @internal */ getIdentifierCount(): number;
/* @internal */ getSymbolCount(): number;
/* @internal */ getTypeCount(): number;
+
+ // For testing purposes only.
+ /* @internal */ structureIsReused?: boolean;
}
export interface SourceMapSpan {
@@ -1431,6 +1452,7 @@ namespace ts {
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
+ isOptionalParameter(node: ParameterDeclaration): boolean;
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1574,7 +1596,8 @@ namespace ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getBlockScopedVariableId(node: Identifier): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
- getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind;
+ getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
+ isOptionalParameter(node: ParameterDeclaration): boolean;
}
export const enum SymbolFlags {
@@ -1768,7 +1791,9 @@ namespace ts {
ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
- ESSymbol = 0x00800000, // Type of symbol primitive introduced in ES6
+ /* @internal */
+ ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
+ ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -1777,10 +1802,12 @@ namespace ts {
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
- UnionOrIntersection = Union | Intersection,
+ UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
- RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
+ RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
+ /* @internal */
+ PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
// Properties common to all types
@@ -2220,9 +2247,23 @@ namespace ts {
byteOrderMark = 0xFEFF,
tab = 0x09, // \t
verticalTab = 0x0B, // \v
+ }
+
+ export interface ModuleResolutionHost {
+ fileExists(fileName: string): boolean;
+ // readFile function is used to read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json'
+ // to determine location of bundled typings for node module
+ readFile(fileName: string): string;
}
+
+ export interface ResolvedModule {
+ resolvedFileName: string;
+ failedLookupLocations: string[];
+ }
+
+ export type ModuleNameResolver = (moduleName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => ResolvedModule;
- export interface CompilerHost {
+ export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
@@ -2231,6 +2272,15 @@ namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
+
+ /*
+ * CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
+ * module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
+ * will appply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
+ * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
+ * 'throw new Error("NotImplemented")'
+ */
+ resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
export interface TextSpan {
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts
index 56eb2415cf9..a33419ae810 100644
--- a/src/compiler/utilities.ts
+++ b/src/compiler/utilities.ts
@@ -80,6 +80,41 @@ namespace ts {
return node.end - node.pos;
}
+ export function arrayIsEqualTo(arr1: T[], arr2: T[], comparer?: (a: T, b: T) => boolean): boolean {
+ if (!arr1 || !arr2) {
+ return arr1 === arr2;
+ }
+
+ if (arr1.length !== arr2.length) {
+ return false;
+ }
+
+ for (let i = 0; i < arr1.length; ++i) {
+ let equals = comparer ? comparer(arr1[i], arr2[i]) : arr1[i] === arr2[i];
+ if (!equals) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ export function hasResolvedModuleName(sourceFile: SourceFile, moduleNameText: string): boolean {
+ return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
+ }
+
+ export function getResolvedModuleFileName(sourceFile: SourceFile, moduleNameText: string): string {
+ return hasResolvedModuleName(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
+ }
+
+ export function setResolvedModuleName(sourceFile: SourceFile, moduleNameText: string, resolvedFileName: string): void {
+ if (!sourceFile.resolvedModules) {
+ sourceFile.resolvedModules = {};
+ }
+
+ sourceFile.resolvedModules[moduleNameText] = resolvedFileName;
+ }
+
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
@@ -381,24 +416,12 @@ namespace ts {
}
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile) {
- // If parameter/type parameter, the prev token trailing comments are part of this node too
- if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
- // e.g. (/** blah */ a, /** blah */ b);
-
- // e.g.: (
- // /** blah */ a,
- // /** blah */ b);
- return concatenate(
- getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
- getLeadingCommentRanges(sourceFileOfNode.text, node.pos));
- }
- else {
- return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
- }
+ return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) {
- return filter(getLeadingCommentRangesOfNode(node, sourceFileOfNode), isJsDocComment);
+ let commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ?
concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
getLeadingCommentRangesOfNode(node, sourceFileOfNode);
+ return filter(commentRanges, isJsDocComment);
function isJsDocComment(comment: CommentRange) {
// True if the comment starts with '/**' but not if it is '/**/'
@@ -988,15 +1011,13 @@ namespace ts {
if (node) {
switch (node.kind) {
case SyntaxKind.Parameter:
- return (node).questionToken !== undefined;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
- return (node).questionToken !== undefined;
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
- return (node).questionToken !== undefined;
+ return (node).questionToken !== undefined;
}
}
@@ -1424,6 +1445,22 @@ namespace ts {
return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile;
}
+ export function cloneEntityName(node: EntityName): EntityName {
+ if (node.kind === SyntaxKind.Identifier) {
+ let clone = createSynthesizedNode(SyntaxKind.Identifier);
+ clone.text = (node).text;
+ return clone;
+ }
+ else {
+ let clone = createSynthesizedNode(SyntaxKind.QualifiedName);
+ clone.left = cloneEntityName((node).left);
+ clone.left.parent = clone;
+ clone.right = cloneEntityName((node).right);
+ clone.right.parent = clone;
+ return clone;
+ }
+ }
+
export function nodeIsSynthesized(node: Node): boolean {
return node.pos === -1;
}
@@ -1868,7 +1905,7 @@ namespace ts {
function writeTrimmedCurrentLine(pos: number, nextLineStart: number) {
let end = Math.min(comment.end, nextLineStart - 1);
- let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, '');
+ let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts
index b1d43302372..87e22e08cfa 100644
--- a/src/harness/compilerRunner.ts
+++ b/src/harness/compilerRunner.ts
@@ -1,6 +1,6 @@
-///
-///
-///
+///
+///
+///
const enum CompilerTestType {
Conformance,
@@ -9,7 +9,7 @@ const enum CompilerTestType {
}
class CompilerBaselineRunner extends RunnerBase {
- private basePath = 'tests/cases';
+ private basePath = "tests/cases";
private testSuiteName: string;
private errors: boolean;
private emit: boolean;
@@ -25,21 +25,21 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = true;
this.output = true;
if (testType === CompilerTestType.Conformance) {
- this.testSuiteName = 'conformance';
+ this.testSuiteName = "conformance";
}
else if (testType === CompilerTestType.Regressions) {
- this.testSuiteName = 'compiler';
+ this.testSuiteName = "compiler";
}
else if (testType === CompilerTestType.Test262) {
- this.testSuiteName = 'test262';
+ this.testSuiteName = "test262";
} else {
- this.testSuiteName = 'compiler'; // default to this for historical reasons
+ this.testSuiteName = "compiler"; // default to this for historical reasons
}
- this.basePath += '/' + this.testSuiteName;
+ this.basePath += "/" + this.testSuiteName;
}
public checkTestCodeOutput(fileName: string) {
- describe('compiler tests for ' + fileName, () => {
+ describe("compiler tests for " + fileName, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let justName: string;
@@ -64,14 +64,14 @@ class CompilerBaselineRunner extends RunnerBase {
let createNewInstance = false;
before(() => {
- justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path.
+ justName = fileName.replace(/^.*[\\\/]/, ""); // strips the fileName from the path.
content = Harness.IO.readFile(fileName);
testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
units = testCaseContent.testUnitData;
tcSettings = testCaseContent.settings;
createNewInstance = false;
lastUnit = units[units.length - 1];
- rootDir = lastUnit.originalFilePath.indexOf('conformance') === -1 ? 'tests/cases/compiler/' : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf('/')) + '/';
+ rootDir = lastUnit.originalFilePath.indexOf("conformance") === -1 ? "tests/cases/compiler/" : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf("/")) + "/";
harnessCompiler = Harness.Compiler.getCompiler();
// We need to assemble the list of input files for the compiler and other related files on the 'filesystem' (ie in a multi-file test)
// If the last file in a test uses require or a triple slash reference we'll assume all other files will be brought in via references,
@@ -106,7 +106,7 @@ class CompilerBaselineRunner extends RunnerBase {
eventually to remove this limitation. */
for (let i = 0; i < tcSettings.length; ++i) {
// noImplicitAny is passed to getCompiler, but target is just passed in the settings blob to setCompilerSettings
- if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === 'target')) {
+ if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === "target")) {
harnessCompiler = Harness.Compiler.getCompiler();
harnessCompiler.setCompilerSettings(tcSettings);
createNewInstance = true;
@@ -148,9 +148,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
// check errors
- it('Correct errors for ' + fileName, () => {
+ it("Correct errors for " + fileName, () => {
if (this.errors) {
- Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.tsx?$/, '.errors.txt'), (): string => {
+ Harness.Baseline.runBaseline("Correct errors for " + fileName, justName.replace(/\.tsx?$/, ".errors.txt"), (): string => {
if (result.errors.length === 0) return null;
return getErrorBaseline(toBeCompiled, otherFiles, result);
});
@@ -158,12 +158,12 @@ class CompilerBaselineRunner extends RunnerBase {
});
// Source maps?
- it('Correct sourcemap content for ' + fileName, () => {
+ it("Correct sourcemap content for " + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
- Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
+ Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
let record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
- // Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
+ // Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required.
return null;
}
return record;
@@ -171,35 +171,35 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
- it('Correct JS output for ' + fileName, () => {
- if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) {
+ it("Correct JS output for " + fileName, () => {
+ if (!ts.fileExtensionIs(lastUnit.name, ".d.ts") && this.emit) {
if (result.files.length === 0 && result.errors.length === 0) {
- throw new Error('Expected at least one js file to be emitted or at least one error to be created.');
+ throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
// check js output
- Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
- let tsCode = '';
+ Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => {
+ let tsCode = "";
let tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
- tsCode += '//// [' + fileName + '] ////\r\n\r\n';
+ tsCode += "//// [" + fileName + "] ////\r\n\r\n";
}
for (let i = 0; i < tsSources.length; i++) {
- tsCode += '//// [' + Harness.Path.getFileName(tsSources[i].unitName) + ']\r\n';
- tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? '\r\n' : '');
+ tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
+ tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
}
- let jsCode = '';
+ let jsCode = "";
for (let i = 0; i < result.files.length; i++) {
- jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n';
+ jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.files[i]);
jsCode += result.files[i].code;
}
if (result.declFilesCode.length > 0) {
- jsCode += '\r\n\r\n';
+ jsCode += "\r\n\r\n";
for (let i = 0; i < result.declFilesCode.length; i++) {
- jsCode += '//// [' + Harness.Path.getFileName(result.declFilesCode[i].fileName) + ']\r\n';
+ jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
jsCode += result.declFilesCode[i].code;
}
@@ -210,13 +210,13 @@ class CompilerBaselineRunner extends RunnerBase {
}, options);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
- jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n';
- jsCode += '\r\n\r\n';
+ jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
+ jsCode += "\r\n\r\n";
jsCode += getErrorBaseline(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles, declFileCompilationResult.declResult);
}
if (jsCode.length > 0) {
- return tsCode + '\r\n\r\n' + jsCode;
+ return tsCode + "\r\n\r\n" + jsCode;
} else {
return null;
}
@@ -224,28 +224,28 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
- it('Correct Sourcemap output for ' + fileName, () => {
+ it("Correct Sourcemap output for " + fileName, () => {
if (options.inlineSourceMap) {
if (result.sourceMaps.length > 0) {
- throw new Error('No sourcemap files should be generated if inlineSourceMaps was set.');
+ throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
}
return null;
}
else if (options.sourceMap) {
if (result.sourceMaps.length !== result.files.length) {
- throw new Error('Number of sourcemap files should be same as js files.');
+ throw new Error("Number of sourcemap files should be same as js files.");
}
- Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.tsx?/, '.js.map'), () => {
+ Harness.Baseline.runBaseline("Correct Sourcemap output for " + fileName, justName.replace(/\.tsx?/, ".js.map"), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
return null;
}
- let sourceMapCode = '';
+ let sourceMapCode = "";
for (let i = 0; i < result.sourceMaps.length; i++) {
- sourceMapCode += '//// [' + Harness.Path.getFileName(result.sourceMaps[i].fileName) + ']\r\n';
+ sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
sourceMapCode += result.sourceMaps[i].code;
}
@@ -255,7 +255,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
- it('Correct type/symbol baselines for ' + fileName, () => {
+ it("Correct type/symbol baselines for " + fileName, () => {
if (fileName.indexOf("APISample") >= 0) {
return;
}
@@ -317,15 +317,15 @@ class CompilerBaselineRunner extends RunnerBase {
let fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
let pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
- let fullExtension = isSymbolBaseLine ? '.symbols' : '.types';
- let pullExtension = isSymbolBaseLine ? '.symbols.pull' : '.types.pull';
+ let fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
+ let pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
- Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
- Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
+ Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
+ Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
- Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
+ Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
@@ -334,7 +334,7 @@ class CompilerBaselineRunner extends RunnerBase {
let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
- let codeLines = file.content.split('\n');
+ let codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
@@ -354,30 +354,30 @@ class CompilerBaselineRunner extends RunnerBase {
typeMap[file.unitName][result.line] = typeInfo;
});
- typeLines.push('=== ' + file.unitName + ' ===\r\n');
+ typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
let currentCodeLine = codeLines[i];
- typeLines.push(currentCodeLine + '\r\n');
+ typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
let typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
- typeLines.push('>' + ty + '\r\n');
+ typeLines.push(">" + ty + "\r\n");
});
- if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === '')) {
+ if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
- typeLines.push('\r\n');
+ typeLines.push("\r\n");
}
}
}
else {
- typeLines.push('No type information for this code.');
+ typeLines.push("No type information for this code.");
}
}
});
- return typeLines.join('');
+ return typeLines.join("");
}
}
});
@@ -385,7 +385,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
public initializeTests() {
- describe(this.testSuiteName + ' tests', () => {
+ describe(this.testSuiteName + " tests", () => {
describe("Setup compiler for compiler baselines", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
@@ -416,23 +416,23 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = false;
this.output = false;
- let opts = this.options.split(',');
+ let opts = this.options.split(",");
for (let i = 0; i < opts.length; i++) {
switch (opts[i]) {
- case 'error':
+ case "error":
this.errors = true;
break;
- case 'emit':
+ case "emit":
this.emit = true;
break;
- case 'decl':
+ case "decl":
this.decl = true;
break;
- case 'output':
+ case "output":
this.output = true;
break;
default:
- throw new Error('unsupported flag');
+ throw new Error("unsupported flag");
}
}
}
diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts
index 272f4c1c1dd..1d2ad83d98a 100644
--- a/src/harness/fourslash.ts
+++ b/src/harness/fourslash.ts
@@ -13,11 +13,11 @@
// limitations under the License.
//
-///
-///
-///
-///
-///
+///
+///
+///
+///
+///
module FourSlash {
ts.disableIncrementalParsing = false;
@@ -100,12 +100,12 @@ module FourSlash {
}
let entityMap: ts.Map = {
- '&': '&',
- '"': '"',
- "'": ''',
- '/': '/',
- '<': '<',
- '>': '>'
+ "&": "&",
+ "\"": """,
+ "'": "'",
+ "/": "/",
+ "<": "<",
+ ">": ">"
};
export function escapeXmlAttributeValue(s: string) {
@@ -116,18 +116,18 @@ module FourSlash {
// To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames
// Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data
let metadataOptionNames = {
- baselineFile: 'BaselineFile',
- declaration: 'declaration',
- emitThisFile: 'emitThisFile', // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project
- fileName: 'Filename',
- mapRoot: 'mapRoot',
- module: 'module',
- out: 'out',
- outDir: 'outDir',
- sourceMap: 'sourceMap',
- sourceRoot: 'sourceRoot',
- allowNonTsExtensions: 'allowNonTsExtensions',
- resolveReference: 'ResolveReference', // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file
+ baselineFile: "BaselineFile",
+ declaration: "declaration",
+ emitThisFile: "emitThisFile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project
+ fileName: "Filename",
+ mapRoot: "mapRoot",
+ module: "module",
+ out: "out",
+ outDir: "outDir",
+ sourceMap: "sourceMap",
+ sourceRoot: "sourceRoot",
+ allowNonTsExtensions: "allowNonTsExtensions",
+ resolveReference: "ResolveReference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file
};
// List of allowed metadata names
@@ -285,7 +285,9 @@ module FourSlash {
case FourSlashTestType.Native:
return new Harness.LanguageService.NativeLanugageServiceAdapter(cancellationToken, compilationOptions);
case FourSlashTestType.Shims:
- return new Harness.LanguageService.ShimLanugageServiceAdapter(cancellationToken, compilationOptions);
+ return new Harness.LanguageService.ShimLanugageServiceAdapter(/*preprocessToResolve*/ false, cancellationToken, compilationOptions);
+ case FourSlashTestType.ShimsWithPreprocess:
+ return new Harness.LanguageService.ShimLanugageServiceAdapter(/*preprocessToResolve*/ true, cancellationToken, compilationOptions);
case FourSlashTestType.Server:
return new Harness.LanguageService.ServerLanugageServiceAdapter(cancellationToken, compilationOptions);
default:
@@ -326,7 +328,7 @@ module FourSlash {
// Add triple reference files into language-service host
ts.forEach(referencedFiles, referenceFile => {
// Fourslash insert tests/cases/fourslash into inputFile.unitName so we will properly append the same base directory to refFile path
- let referenceFilePath = this.basePath + '/' + referenceFile.fileName;
+ let referenceFilePath = this.basePath + "/" + referenceFile.fileName;
this.addMatchedInputFile(referenceFilePath);
});
@@ -334,7 +336,7 @@ module FourSlash {
ts.forEach(importedFiles, importedFile => {
// Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts"
// so convert them before making appropriate comparison
- let importedFilePath = this.basePath + '/' + importedFile.fileName + ".ts";
+ let importedFilePath = this.basePath + "/" + importedFile.fileName + ".ts";
this.addMatchedInputFile(importedFilePath);
});
@@ -364,14 +366,15 @@ module FourSlash {
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
+ InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
this.testData.files.forEach(file => {
- let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), '').substr(1);
+ let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1);
let fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf("."));
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
});
// Open the first file by default
@@ -384,7 +387,7 @@ module FourSlash {
}
// Entry points from fourslash.ts
- public goToMarker(name = '') {
+ public goToMarker(name = "") {
let marker = this.getMarkerByName(name);
if (this.activeFile.fileName !== marker.fileName) {
this.openFile(marker.fileName);
@@ -392,7 +395,7 @@ module FourSlash {
let content = this.getFileContent(marker.fileName);
if (marker.position === -1 || marker.position > content.length) {
- throw new Error('Marker "' + name + '" has been invalidated by unrecoverable edits to the file.');
+ throw new Error(`Marker "${name}" has been invalidated by unrecoverable edits to the file.`);
}
this.lastKnownMarker = name;
this.goToPosition(marker.position);
@@ -410,9 +413,9 @@ module FourSlash {
this.currentCaretPosition += count;
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
if (count > 0) {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
} else {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
}
}
@@ -423,8 +426,8 @@ module FourSlash {
let fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
- let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), '').substr(1);
- this.scenarioActions.push('');
+ let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1);
+ this.scenarioActions.push(``);
// Let the host know that this file is now open
this.languageServiceAdapterHost.openFile(fileToOpen.fileName);
@@ -439,7 +442,7 @@ module FourSlash {
let exists = this.anyErrorInRange(predicate, startMarker, endMarker);
- this.taoInvalidReason = 'verifyErrorExistsBetweenMarkers NYI';
+ this.taoInvalidReason = "verifyErrorExistsBetweenMarkers NYI";
if (exists !== negative) {
this.printErrorLog(negative, this.getAllDiagnostics());
@@ -492,7 +495,7 @@ module FourSlash {
};
}
- this.taoInvalidReason = 'verifyErrorExistsAfterMarker NYI';
+ this.taoInvalidReason = "verifyErrorExistsAfterMarker NYI";
let exists = this.anyErrorInRange(predicate, marker);
let diagnostics = this.getAllDiagnostics();
@@ -541,7 +544,7 @@ module FourSlash {
let errors = this.getDiagnostics(this.activeFile.fileName);
let actual = errors.length;
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
if (actual !== expected) {
this.printErrorLog(false, errors);
@@ -557,11 +560,11 @@ module FourSlash {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
- this.taoInvalidReason = 'verifyEval impossible';
+ this.taoInvalidReason = "verifyEval impossible";
- let evaluation = new Function(emit.outputFiles[0].text + ';\r\nreturn (' + expr + ');')();
+ let evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)();
if (evaluation !== value) {
- this.raiseError('Expected evaluation of expression "' + expr + '" to equal "' + value + '", but got "' + evaluation + '"');
+ this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`);
}
}
@@ -570,19 +573,19 @@ module FourSlash {
if (emit.outputFiles.length !== 1) {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
}
- this.taoInvalidReason = 'verifyGetEmitOutputForCurrentFile impossible';
+ this.taoInvalidReason = "verifyGetEmitOutputForCurrentFile impossible";
let actual = emit.outputFiles[0].text;
if (actual !== expected) {
- this.raiseError("Expected emit output to be '" + expected + "', but got '" + actual + "'");
+ this.raiseError(`Expected emit output to be "${expected}", but got "${actual}"`);
}
}
public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
if (text || documentation || kind) {
- this.taoInvalidReason = 'verifyMemberListContains only supports the "symbol" parameter';
+ this.taoInvalidReason = "verifyMemberListContains only supports the \"symbol\" parameter";
}
let members = this.getMemberListAtCaret();
@@ -600,11 +603,11 @@ module FourSlash {
this.verifyMemberListIsEmpty(false);
return;
} else {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
}
} else {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
}
let members = this.getMemberListAtCaret();
@@ -622,31 +625,31 @@ module FourSlash {
}
public verifyMemberListDoesNotContain(symbol: string) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
let members = this.getMemberListAtCaret();
if (members && members.entries.filter(e => e.name === symbol).length !== 0) {
- this.raiseError('Member list did contain ' + symbol);
+ this.raiseError(`Member list did contain ${symbol}`);
}
}
public verifyCompletionListItemsCountIsGreaterThan(count: number) {
- this.taoInvalidReason = 'verifyCompletionListItemsCountIsGreaterThan NYI';
+ this.taoInvalidReason = "verifyCompletionListItemsCountIsGreaterThan NYI";
let completions = this.getCompletionListAtCaret();
let itemsCount = completions.entries.length;
if (itemsCount <= count) {
- this.raiseError('Expected completion list items count to be greater than ' + count + ', but is actually ' + itemsCount);
+ this.raiseError(`Expected completion list items count to be greater than ${count}, but is actually ${itemsCount}`);
}
}
public verifyMemberListIsEmpty(negative: boolean) {
if (negative) {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
} else {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
}
let members = this.getMemberListAtCaret();
@@ -666,7 +669,7 @@ module FourSlash {
}
public verifyCompletionListIsEmpty(negative: boolean) {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
let completions = this.getCompletionListAtCaret();
if ((!completions || completions.entries.length === 0) && negative) {
@@ -730,12 +733,12 @@ module FourSlash {
return documentation === expectedDocumentation ? true : false;
}
// Because expectedText and expectedDocumentation are undefined, we assume that
- // users don't care to compare them so we will treat that entry as if the entry has matching text and documentation
+ // users don"t care to compare them so we will treat that entry as if the entry has matching text and documentation
// and keep it in the list of filtered entry.
return true;
}
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
let completions = this.getCompletionListAtCaret();
if (completions) {
@@ -763,7 +766,7 @@ module FourSlash {
}
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) {
- this.taoInvalidReason = 'verifyCompletionEntryDetails NYI';
+ this.taoInvalidReason = "verifyCompletionEntryDetails NYI";
let details = this.getCompletionEntryDetails(entryName);
@@ -779,30 +782,30 @@ module FourSlash {
}
public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
- this.taoInvalidReason = 'verifyReferencesAtPositionListContains NYI';
+ this.taoInvalidReason = "verifyReferencesAtPositionListContains NYI";
let references = this.getReferencesAtCaret();
if (!references || references.length === 0) {
- this.raiseError('verifyReferencesAtPositionListContains failed - found 0 references, expected at least one.');
+ this.raiseError("verifyReferencesAtPositionListContains failed - found 0 references, expected at least one.");
}
for (let i = 0; i < references.length; i++) {
let reference = references[i];
if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
- this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
+ this.raiseError(`verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${reference.isWriteAccess}, expected: ${isWriteAccess}.`);
}
return;
}
}
let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
- this.raiseError('verifyReferencesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(references) + ')');
+ this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(references)})`);
}
public verifyReferencesCountIs(count: number, localFilesOnly: boolean = true) {
- this.taoInvalidReason = 'verifyReferences NYI';
+ this.taoInvalidReason = "verifyReferences NYI";
let references = this.getReferencesAtCaret();
let referencesCount = 0;
@@ -865,8 +868,8 @@ module FourSlash {
public verifyQuickInfoString(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
[expectedText, expectedDocumentation].forEach(str => {
if (str) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
}
});
@@ -896,8 +899,8 @@ module FourSlash {
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[]) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
@@ -964,23 +967,23 @@ module FourSlash {
}
public verifyQuickInfoExists(negative: boolean) {
- this.taoInvalidReason = 'verifyQuickInfoExists NYI';
+ this.taoInvalidReason = "verifyQuickInfoExists NYI";
let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (negative) {
if (actualQuickInfo) {
- this.raiseError('verifyQuickInfoExists failed. Expected quick info NOT to exist');
+ this.raiseError("verifyQuickInfoExists failed. Expected quick info NOT to exist");
}
}
else {
if (!actualQuickInfo) {
- this.raiseError('verifyQuickInfoExists failed. Expected quick info to exist');
+ this.raiseError("verifyQuickInfoExists failed. Expected quick info to exist");
}
}
}
public verifyCurrentSignatureHelpIs(expected: string) {
- this.taoInvalidReason = 'verifyCurrentSignatureHelpIs NYI';
+ this.taoInvalidReason = "verifyCurrentSignatureHelpIs NYI";
let help = this.getActiveSignatureHelpItem();
assert.equal(
@@ -990,7 +993,7 @@ module FourSlash {
}
public verifyCurrentParameterIsletiable(isVariable: boolean) {
- this.taoInvalidReason = 'verifyCurrentParameterIsletiable NYI';
+ this.taoInvalidReason = "verifyCurrentParameterIsletiable NYI";
let signature = this.getActiveSignatureHelpItem();
assert.isNotNull(signature);
@@ -998,7 +1001,7 @@ module FourSlash {
}
public verifyCurrentParameterHelpName(name: string) {
- this.taoInvalidReason = 'verifyCurrentParameterHelpName NYI';
+ this.taoInvalidReason = "verifyCurrentParameterHelpName NYI";
let activeParameter = this.getActiveParameter();
let activeParameterName = activeParameter.name;
@@ -1006,7 +1009,7 @@ module FourSlash {
}
public verifyCurrentParameterSpanIs(parameter: string) {
- this.taoInvalidReason = 'verifyCurrentParameterSpanIs NYI';
+ this.taoInvalidReason = "verifyCurrentParameterSpanIs NYI";
let activeSignature = this.getActiveSignatureHelpItem();
let activeParameter = this.getActiveParameter();
@@ -1014,7 +1017,7 @@ module FourSlash {
}
public verifyCurrentParameterHelpDocComment(docComment: string) {
- this.taoInvalidReason = 'verifyCurrentParameterHelpDocComment NYI';
+ this.taoInvalidReason = "verifyCurrentParameterHelpDocComment NYI";
let activeParameter = this.getActiveParameter();
let activeParameterDocComment = activeParameter.documentation;
@@ -1022,27 +1025,27 @@ module FourSlash {
}
public verifyCurrentSignatureHelpParameterCount(expectedCount: number) {
- this.taoInvalidReason = 'verifyCurrentSignatureHelpParameterCount NYI';
+ this.taoInvalidReason = "verifyCurrentSignatureHelpParameterCount NYI";
assert.equal(this.getActiveSignatureHelpItem().parameters.length, expectedCount);
}
public verifyCurrentSignatureHelpTypeParameterCount(expectedCount: number) {
- this.taoInvalidReason = 'verifyCurrentSignatureHelpTypeParameterCount NYI';
+ this.taoInvalidReason = "verifyCurrentSignatureHelpTypeParameterCount NYI";
// assert.equal(this.getActiveSignatureHelpItem().typeParameters.length, expectedCount);
}
public verifyCurrentSignatureHelpDocComment(docComment: string) {
- this.taoInvalidReason = 'verifyCurrentSignatureHelpDocComment NYI';
+ this.taoInvalidReason = "verifyCurrentSignatureHelpDocComment NYI";
let actualDocComment = this.getActiveSignatureHelpItem().documentation;
assert.equal(ts.displayPartsToString(actualDocComment), docComment, assertionMessage("current signature help doc comment"));
}
public verifySignatureHelpCount(expected: number) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
let actual = help && help.items ? help.items.length : 0;
@@ -1050,14 +1053,14 @@ module FourSlash {
}
public verifySignatureHelpArgumentCount(expected: number) {
- this.taoInvalidReason = 'verifySignatureHelpArgumentCount NYI';
+ this.taoInvalidReason = "verifySignatureHelpArgumentCount NYI";
let signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
let actual = signatureHelpItems.argumentCount;
assert.equal(actual, expected);
}
public verifySignatureHelpPresent(shouldBePresent = true) {
- this.taoInvalidReason = 'verifySignatureHelpPresent NYI';
+ this.taoInvalidReason = "verifySignatureHelpPresent NYI";
let actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
if (shouldBePresent) {
@@ -1066,7 +1069,7 @@ module FourSlash {
}
} else {
if (actual) {
- this.raiseError("Expected no signature help, but got '" + JSON.stringify(actual) + "'");
+ this.raiseError(`Expected no signature help, but got "${JSON.stringify(actual)}"`);
}
}
}
@@ -1200,12 +1203,12 @@ module FourSlash {
}
public getBreakpointStatementLocation(pos: number) {
- this.taoInvalidReason = 'getBreakpointStatementLocation NYI';
+ this.taoInvalidReason = "getBreakpointStatementLocation NYI";
return this.languageService.getBreakpointStatementAtPosition(this.activeFile.fileName, pos);
}
public baselineCurrentFileBreakpointLocations() {
- this.taoInvalidReason = 'baselineCurrentFileBreakpointLocations impossible';
+ this.taoInvalidReason = "baselineCurrentFileBreakpointLocations impossible";
Harness.Baseline.runBaseline(
"Breakpoint Locations for " + this.activeFile.fileName,
@@ -1217,7 +1220,7 @@ module FourSlash {
}
public baselineGetEmitOutput() {
- this.taoInvalidReason = 'baselineGetEmitOutput impossible';
+ this.taoInvalidReason = "baselineGetEmitOutput impossible";
// Find file to be emitted
let emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on
@@ -1288,7 +1291,7 @@ module FourSlash {
let syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
let semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
let errorList = syntacticErrors.concat(semanticErrors);
- Harness.IO.log('Error list (' + errorList.length + ' errors)');
+ Harness.IO.log(`Error list (${errorList.length} errors)`);
if (errorList.length) {
errorList.forEach(err => {
@@ -1304,10 +1307,10 @@ module FourSlash {
for (let i = 0; i < this.testData.files.length; i++) {
let file = this.testData.files[i];
let active = (this.activeFile === file);
- Harness.IO.log('=== Script (' + file.fileName + ') ' + (active ? '(active, cursor at |)' : '') + ' ===');
+ Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`);
let content = this.getFileContent(file.fileName);
if (active) {
- content = content.substr(0, this.currentCaretPosition) + (makeCaretVisible ? '|' : "") + content.substr(this.currentCaretPosition);
+ content = content.substr(0, this.currentCaretPosition) + (makeCaretVisible ? "|" : "") + content.substr(this.currentCaretPosition);
}
if (makeWhitespaceVisible) {
content = TestState.makeWhitespaceVisible(content);
@@ -1343,7 +1346,7 @@ module FourSlash {
}
public deleteChar(count = 1) {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
let offset = this.currentCaretPosition;
let ch = "";
@@ -1377,7 +1380,7 @@ module FourSlash {
}
public replace(start: number, length: number, text: string) {
- this.taoInvalidReason = 'replace NYI';
+ this.taoInvalidReason = "replace NYI";
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, start, start + length, text);
this.updateMarkersForEdit(this.activeFile.fileName, start, start + length, text);
@@ -1385,7 +1388,7 @@ module FourSlash {
}
public deleteCharBehindMarker(count = 1) {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
let offset = this.currentCaretPosition;
let ch = "";
@@ -1419,10 +1422,10 @@ module FourSlash {
// Enters lines of text at the current caret position
public type(text: string) {
- if (text === '') {
- this.taoInvalidReason = 'Test used empty-insert workaround.';
+ if (text === "") {
+ this.taoInvalidReason = "Test used empty-insert workaround.";
} else {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
}
return this.typeHighFidelity(text);
@@ -1433,7 +1436,7 @@ module FourSlash {
// as much as possible
private typeHighFidelity(text: string) {
let offset = this.currentCaretPosition;
- let prevChar = ' ';
+ let prevChar = " ";
let checkCadence = (text.length >> 2) + 1;
for (let i = 0; i < text.length; i++) {
@@ -1445,10 +1448,10 @@ module FourSlash {
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch);
offset++;
- if (ch === '(' || ch === ',') {
+ if (ch === "(" || ch === ",") {
/* Signature help*/
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
- } else if (prevChar === ' ' && /A-Za-z_/.test(ch)) {
+ } else if (prevChar === " " && /A-Za-z_/.test(ch)) {
/* Completions */
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
@@ -1478,7 +1481,7 @@ module FourSlash {
// Enters text as if the user had pasted it
public paste(text: string) {
- this.scenarioActions.push('');
+ this.scenarioActions.push(``);
let start = this.currentCaretPosition;
let offset = this.currentCaretPosition;
@@ -1531,7 +1534,7 @@ module FourSlash {
// that happens, move it back one character
if (this.currentCaretPosition > 0) {
let ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition);
- if (ch === '\r') {
+ if (ch === "\r") {
this.currentCaretPosition--;
}
};
@@ -1556,8 +1559,8 @@ module FourSlash {
if (isFormattingEdit) {
let newContent = this.getFileContent(fileName);
- if (newContent.replace(/\s/g, '') !== oldContent.replace(/\s/g, '')) {
- this.raiseError('Formatting operation destroyed non-whitespace content');
+ if (newContent.replace(/\s/g, "") !== oldContent.replace(/\s/g, "")) {
+ this.raiseError("Formatting operation destroyed non-whitespace content");
}
}
return runningOffset;
@@ -1574,7 +1577,7 @@ module FourSlash {
}
public formatDocument() {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
let edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions);
this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true);
@@ -1582,7 +1585,7 @@ module FourSlash {
}
public formatSelection(start: number, end: number) {
- this.taoInvalidReason = 'formatSelection NYI';
+ this.taoInvalidReason = "formatSelection NYI";
let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions);
this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true);
@@ -1617,18 +1620,18 @@ module FourSlash {
public goToDefinition(definitionIndex: number) {
if (definitionIndex === 0) {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
} else {
- this.taoInvalidReason = 'GoToDefinition not supported for non-zero definition indices';
+ this.taoInvalidReason = "GoToDefinition not supported for non-zero definition indices";
}
let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
- this.raiseError('goToDefinition failed - expected to at least one definition location but got 0');
+ this.raiseError("goToDefinition failed - expected to at least one definition location but got 0");
}
if (definitionIndex >= definitions.length) {
- this.raiseError('goToDefinition failed - definitionIndex value (' + definitionIndex + ') exceeds definition list size (' + definitions.length + ')');
+ this.raiseError(`goToDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`);
}
let definition = definitions[definitionIndex];
@@ -1638,19 +1641,19 @@ module FourSlash {
public goToTypeDefinition(definitionIndex: number) {
if (definitionIndex === 0) {
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
}
else {
- this.taoInvalidReason = 'GoToTypeDefinition not supported for non-zero definition indices';
+ this.taoInvalidReason = "GoToTypeDefinition not supported for non-zero definition indices";
}
let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
- this.raiseError('goToTypeDefinition failed - expected to at least one definition location but got 0');
+ this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0");
}
if (definitionIndex >= definitions.length) {
- this.raiseError('goToTypeDefinition failed - definitionIndex value (' + definitionIndex + ') exceeds definition list size (' + definitions.length + ')');
+ this.raiseError(`goToTypeDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`);
}
let definition = definitions[definitionIndex];
@@ -1659,17 +1662,17 @@ module FourSlash {
}
public verifyDefinitionLocationExists(negative: boolean) {
- this.taoInvalidReason = 'verifyDefinitionLocationExists NYI';
+ this.taoInvalidReason = "verifyDefinitionLocationExists NYI";
let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
let foundDefinitions = definitions && definitions.length;
if (foundDefinitions && negative) {
- this.raiseError('goToDefinition - expected to 0 definition locations but got ' + definitions.length);
+ this.raiseError(`goToDefinition - expected to 0 definition locations but got ${definitions.length}`);
}
else if (!foundDefinitions && !negative) {
- this.raiseError('goToDefinition - expected to at least one definition location but got 0');
+ this.raiseError("goToDefinition - expected to at least one definition location but got 0");
}
}
@@ -1692,7 +1695,7 @@ module FourSlash {
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
- this.taoInvalidReason = 'verifyDefinititionsInfo NYI';
+ this.taoInvalidReason = "verifyDefinititionsInfo NYI";
let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
let actualDefinitionName = definitions && definitions.length ? definitions[0].name : "";
@@ -1716,15 +1719,15 @@ module FourSlash {
return this.testData.ranges.slice(0);
}
- public verifyCaretAtMarker(markerName = '') {
- this.taoInvalidReason = 'verifyCaretAtMarker NYI';
+ public verifyCaretAtMarker(markerName = "") {
+ this.taoInvalidReason = "verifyCaretAtMarker NYI";
let pos = this.getMarkerByName(markerName);
if (pos.fileName !== this.activeFile.fileName) {
- throw new Error('verifyCaretAtMarker failed - expected to be in file "' + pos.fileName + '", but was in file "' + this.activeFile.fileName + '"');
+ throw new Error(`verifyCaretAtMarker failed - expected to be in file "${pos.fileName}", but was in file "${this.activeFile.fileName}"`);
}
if (pos.position !== this.currentCaretPosition) {
- throw new Error('verifyCaretAtMarker failed - expected to be at marker "/*' + markerName + '*/, but was at position ' + this.currentCaretPosition + '(' + this.getLineColStringAtPosition(this.currentCaretPosition) + ')');
+ throw new Error(`verifyCaretAtMarker failed - expected to be at marker "/*${markerName}*/, but was at position ${this.currentCaretPosition}(${this.getLineColStringAtPosition(this.currentCaretPosition)})`);
}
}
@@ -1733,84 +1736,84 @@ module FourSlash {
}
public verifyIndentationAtCurrentPosition(numberOfSpaces: number) {
- this.taoInvalidReason = 'verifyIndentationAtCurrentPosition NYI';
+ this.taoInvalidReason = "verifyIndentationAtCurrentPosition NYI";
let actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition);
let lineCol = this.getLineColStringAtPosition(this.currentCaretPosition);
if (actual !== numberOfSpaces) {
- this.raiseError('verifyIndentationAtCurrentPosition failed at ' + lineCol + ' - expected: ' + numberOfSpaces + ', actual: ' + actual);
+ this.raiseError(`verifyIndentationAtCurrentPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`);
}
}
public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number) {
- this.taoInvalidReason = 'verifyIndentationAtPosition NYI';
+ this.taoInvalidReason = "verifyIndentationAtPosition NYI";
let actual = this.getIndentation(fileName, position);
let lineCol = this.getLineColStringAtPosition(position);
if (actual !== numberOfSpaces) {
- this.raiseError('verifyIndentationAtPosition failed at ' + lineCol + ' - expected: ' + numberOfSpaces + ', actual: ' + actual);
+ this.raiseError(`verifyIndentationAtPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`);
}
}
public verifyCurrentLineContent(text: string) {
- this.taoInvalidReason = 'verifyCurrentLineContent NYI';
+ this.taoInvalidReason = "verifyCurrentLineContent NYI";
let actual = this.getCurrentLineContent();
if (actual !== text) {
- throw new Error('verifyCurrentLineContent\n' +
- '\tExpected: "' + text + '"\n' +
- '\t Actual: "' + actual + '"');
+ throw new Error("verifyCurrentLineContent\n" +
+ "\tExpected: \"" + text + "\"\n" +
+ "\t Actual: \"" + actual + "\"");
}
}
public verifyCurrentFileContent(text: string) {
- this.taoInvalidReason = 'verifyCurrentFileContent NYI';
+ this.taoInvalidReason = "verifyCurrentFileContent NYI";
let actual = this.getFileContent(this.activeFile.fileName);
let replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n");
if (replaceNewlines(actual) !== replaceNewlines(text)) {
- throw new Error('verifyCurrentFileContent\n' +
- '\tExpected: "' + text + '"\n' +
- '\t Actual: "' + actual + '"');
+ throw new Error("verifyCurrentFileContent\n" +
+ "\tExpected: \"" + text + "\"\n" +
+ "\t Actual: \"" + actual + "\"");
}
}
public verifyTextAtCaretIs(text: string) {
- this.taoInvalidReason = 'verifyCurrentFileContent NYI';
+ this.taoInvalidReason = "verifyCurrentFileContent NYI";
let actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length);
if (actual !== text) {
- throw new Error('verifyTextAtCaretIs\n' +
- '\tExpected: "' + text + '"\n' +
- '\t Actual: "' + actual + '"');
+ throw new Error("verifyTextAtCaretIs\n" +
+ "\tExpected: \"" + text + "\"\n" +
+ "\t Actual: \"" + actual + "\"");
}
}
public verifyCurrentNameOrDottedNameSpanText(text: string) {
- this.taoInvalidReason = 'verifyCurrentNameOrDottedNameSpanText NYI';
+ this.taoInvalidReason = "verifyCurrentNameOrDottedNameSpanText NYI";
let span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition);
if (!span) {
- this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' +
- '\tExpected: "' + text + '"\n' +
- '\t Actual: undefined');
+ this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" +
+ "\tExpected: \"" + text + "\"\n" +
+ "\t Actual: undefined");
}
let actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span));
if (actual !== text) {
- this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' +
- '\tExpected: "' + text + '"\n' +
- '\t Actual: "' + actual + '"');
+ this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" +
+ "\tExpected: \"" + text + "\"\n" +
+ "\t Actual: \"" + actual + "\"");
}
}
private getNameOrDottedNameSpan(pos: number) {
- this.taoInvalidReason = 'getNameOrDottedNameSpan NYI';
+ this.taoInvalidReason = "getNameOrDottedNameSpan NYI";
return this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, pos, pos);
}
public baselineCurrentFileNameOrDottedNameSpans() {
- this.taoInvalidReason = 'baselineCurrentFileNameOrDottedNameSpans impossible';
+ this.taoInvalidReason = "baselineCurrentFileNameOrDottedNameSpans impossible";
Harness.Baseline.runBaseline(
"Name OrDottedNameSpans for " + this.activeFile.fileName,
@@ -1828,8 +1831,8 @@ module FourSlash {
private verifyClassifications(expected: { classificationType: string; text: string; textSpan?: TextSpan }[], actual: ts.ClassifiedSpan[]) {
if (actual.length !== expected.length) {
- this.raiseError('verifyClassifications failed - expected total classifications to be ' + expected.length +
- ', but was ' + actual.length +
+ this.raiseError("verifyClassifications failed - expected total classifications to be " + expected.length +
+ ", but was " + actual.length +
jsonMismatchString());
}
@@ -1839,8 +1842,8 @@ module FourSlash {
let expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType];
if (expectedType !== actualClassification.classificationType) {
- this.raiseError('verifyClassifications failed - expected classifications type to be ' +
- expectedType + ', but was ' +
+ this.raiseError("verifyClassifications failed - expected classifications type to be " +
+ expectedType + ", but was " +
actualClassification.classificationType +
jsonMismatchString());
}
@@ -1861,8 +1864,8 @@ module FourSlash {
let actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length);
if (expectedClassification.text !== actualText) {
- this.raiseError('verifyClassifications failed - expected classified text to be ' +
- expectedClassification.text + ', but was ' +
+ this.raiseError("verifyClassifications failed - expected classified text to be " +
+ expectedClassification.text + ", but was " +
actualText +
jsonMismatchString());
}
@@ -1883,7 +1886,7 @@ module FourSlash {
);
assert.equal(
expected.join(","),
- actual.fileNameList.map( file => {
+ actual.fileNames.map( file => {
return file.replace(this.basePath + "/", "");
}).join(",")
);
@@ -1905,19 +1908,19 @@ module FourSlash {
}
public verifyOutliningSpans(spans: TextSpan[]) {
- this.taoInvalidReason = 'verifyOutliningSpans NYI';
+ this.taoInvalidReason = "verifyOutliningSpans NYI";
let actual = this.languageService.getOutliningSpans(this.activeFile.fileName);
if (actual.length !== spans.length) {
- this.raiseError('verifyOutliningSpans failed - expected total spans to be ' + spans.length + ', but was ' + actual.length);
+ this.raiseError(`verifyOutliningSpans failed - expected total spans to be ${spans.length}, but was ${actual.length}`);
}
for (let i = 0; i < spans.length; i++) {
let expectedSpan = spans[i];
let actualSpan = actual[i];
if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) {
- this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start + ',' + ts.textSpanEnd(actualSpan.textSpan) + ')');
+ this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualSpan.textSpan.start},${ts.textSpanEnd(actualSpan.textSpan)})`);
}
}
}
@@ -1927,7 +1930,7 @@ module FourSlash {
descriptors.map(d => { return { text: d, priority: 0 }; }));
if (actual.length !== spans.length) {
- this.raiseError('verifyTodoComments failed - expected total spans to be ' + spans.length + ', but was ' + actual.length);
+ this.raiseError(`verifyTodoComments failed - expected total spans to be ${spans.length}, but was ${actual.length}`);
}
for (let i = 0; i < spans.length; i++) {
@@ -1936,18 +1939,44 @@ module FourSlash {
let actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length);
if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) {
- this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start + ',' + ts.textSpanEnd(actualCommentSpan) + ')');
+ this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualCommentSpan.start},${ts.textSpanEnd(actualCommentSpan)})`);
+ }
+ }
+ }
+
+ public verifyDocCommentTemplate(expected?: ts.TextInsertion) {
+ const name = "verifyDocCommentTemplate";
+ let actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition);
+
+ if (expected === undefined) {
+ if (actual) {
+ this.raiseError(name + ' failed - expected no template but got {newText: \"' + actual.newText + '\" caretOffset: ' + actual.caretOffset + '}');
+ }
+
+ return;
+ }
+ else {
+ if (actual === undefined) {
+ this.raiseError(name + ' failed - expected the template {newText: \"' + actual.newText + '\" caretOffset: ' + actual.caretOffset + '} but got nothing instead');
+ }
+
+ if (actual.newText !== expected.newText) {
+ this.raiseError(name + ' failed - expected insertion:\n' + expected.newText + '\nactual insertion:\n' + actual.newText);
+ }
+
+ if (actual.caretOffset !== expected.caretOffset) {
+ this.raiseError(name + ' failed - expected caretOffset: ' + expected.caretOffset + ',\nactual caretOffset:' + actual.caretOffset);
}
}
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
- this.taoInvalidReason = 'verifyMatchingBracePosition NYI';
+ this.taoInvalidReason = "verifyMatchingBracePosition NYI";
let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 2) {
- this.raiseError('verifyMatchingBracePosition failed - expected result to contain 2 spans, but it had ' + actual.length);
+ this.raiseError(`verifyMatchingBracePosition failed - expected result to contain 2 spans, but it had ${actual.length}`);
}
let actualMatchPosition = -1;
@@ -1956,21 +1985,21 @@ module FourSlash {
} else if (bracePosition === actual[1].start) {
actualMatchPosition = actual[0].start;
} else {
- this.raiseError('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start + ',' + ts.textSpanEnd(actual[0]) + ') and (' + actual[1].start + ',' + ts.textSpanEnd(actual[1]) + ')');
+ this.raiseError(`verifyMatchingBracePosition failed - could not find the brace position: ${bracePosition} in the returned list: (${actual[0].start},${ts.textSpanEnd(actual[0])}) and (${actual[1].start},${ts.textSpanEnd(actual[1])})`);
}
if (actualMatchPosition !== expectedMatchPosition) {
- this.raiseError('verifyMatchingBracePosition failed - expected: ' + actualMatchPosition + ', actual: ' + expectedMatchPosition);
+ this.raiseError(`verifyMatchingBracePosition failed - expected: ${actualMatchPosition}, actual: ${expectedMatchPosition}`);
}
}
public verifyNoMatchingBracePosition(bracePosition: number) {
- this.taoInvalidReason = 'verifyNoMatchingBracePosition NYI';
+ this.taoInvalidReason = "verifyNoMatchingBracePosition NYI";
let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 0) {
- this.raiseError('verifyNoMatchingBracePosition failed - expected: 0 spans, actual: ' + actual.length);
+ this.raiseError("verifyNoMatchingBracePosition failed - expected: 0 spans, actual: " + actual.length);
}
}
@@ -1979,7 +2008,7 @@ module FourSlash {
Report an error if expected value and actual value do not match.
*/
public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string) {
- this.taoInvalidReason = 'verifyNavigationItemsCount NYI';
+ this.taoInvalidReason = "verifyNavigationItemsCount NYI";
let items = this.languageService.getNavigateToItems(searchValue);
let actual = 0;
@@ -1994,7 +2023,7 @@ module FourSlash {
}
if (expected !== actual) {
- this.raiseError('verifyNavigationItemsCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.');
+ this.raiseError(`verifyNavigationItemsCount failed - found: ${actual} navigation items, expected: ${expected}.`);
}
}
@@ -2009,12 +2038,12 @@ module FourSlash {
matchKind: string,
fileName?: string,
parentName?: string) {
- this.taoInvalidReason = 'verifyNavigationItemsListContains NYI';
+ this.taoInvalidReason = "verifyNavigationItemsListContains NYI";
let items = this.languageService.getNavigateToItems(searchValue);
if (!items || items.length === 0) {
- this.raiseError('verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one.');
+ this.raiseError("verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one.");
}
for (let i = 0; i < items.length; i++) {
@@ -2030,18 +2059,18 @@ module FourSlash {
// if there was an explicit match kind specified, then it should be validated.
if (matchKind !== undefined) {
let missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName };
- this.raiseError('verifyNavigationItemsListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items) + ')');
+ this.raiseError(`verifyNavigationItemsListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items)})`);
}
}
public verifyGetScriptLexicalStructureListCount(expected: number) {
- this.taoInvalidReason = 'verifyNavigationItemsListContains impossible';
+ this.taoInvalidReason = "verifyNavigationItemsListContains impossible";
let items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
let actual = this.getNavigationBarItemsCount(items);
if (expected !== actual) {
- this.raiseError('verifyGetScriptLexicalStructureListCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.');
+ this.raiseError(`verifyGetScriptLexicalStructureListCount failed - found: ${actual} navigation items, expected: ${expected}.`);
}
}
@@ -2058,12 +2087,12 @@ module FourSlash {
}
public verifyGetScriptLexicalStructureListContains(name: string, kind: string) {
- this.taoInvalidReason = 'verifyGetScriptLexicalStructureListContains impossible';
+ this.taoInvalidReason = "verifyGetScriptLexicalStructureListContains impossible";
let items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
if (!items || items.length === 0) {
- this.raiseError('verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.');
+ this.raiseError("verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.");
}
if (this.navigationBarItemsContains(items, name, kind)) {
@@ -2071,7 +2100,7 @@ module FourSlash {
}
let missingItem = { name: name, kind: kind };
- this.raiseError('verifyGetScriptLexicalStructureListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items, null, " ") + ')');
+ this.raiseError(`verifyGetScriptLexicalStructureListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items, null, " ")})`);
}
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) {
@@ -2095,11 +2124,11 @@ module FourSlash {
let items = this.languageService.getNavigateToItems(searchValue);
let length = items && items.length;
- Harness.IO.log('NavigationItems list (' + length + ' items)');
+ Harness.IO.log(`NavigationItems list (${length} items)`);
for (let i = 0; i < length; i++) {
let item = items[i];
- Harness.IO.log('name: ' + item.name + ', kind: ' + item.kind + ', parentName: ' + item.containerName + ', fileName: ' + item.fileName);
+ Harness.IO.log(`name: ${item.name}, kind: ${item.kind}, parentName: ${item.containerName}, fileName: ${item.fileName}`);
}
}
@@ -2107,48 +2136,93 @@ module FourSlash {
let items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
let length = items && items.length;
- Harness.IO.log('NavigationItems list (' + length + ' items)');
+ Harness.IO.log(`NavigationItems list (${length} items)`);
for (let i = 0; i < length; i++) {
let item = items[i];
- Harness.IO.log('name: ' + item.text + ', kind: ' + item.kind);
+ Harness.IO.log(`name: ${item.text}, kind: ${item.kind}`);
}
}
- private getOccurancesAtCurrentPosition() {
+ private getOccurrencesAtCurrentPosition() {
return this.languageService.getOccurrencesAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
public verifyOccurrencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) {
- this.taoInvalidReason = 'verifyOccurrencesAtPositionListContains NYI';
+ this.taoInvalidReason = "verifyOccurrencesAtPositionListContains NYI";
- let occurances = this.getOccurancesAtCurrentPosition();
+ let occurrences = this.getOccurrencesAtCurrentPosition();
- if (!occurances || occurances.length === 0) {
- this.raiseError('verifyOccurancesAtPositionListContains failed - found 0 references, expected at least one.');
+ if (!occurrences || occurrences.length === 0) {
+ this.raiseError('verifyOccurrencesAtPositionListContains failed - found 0 references, expected at least one.');
}
- for (let i = 0; i < occurances.length; i++) {
- let occurance = occurances[i];
- if (occurance && occurance.fileName === fileName && occurance.textSpan.start === start && ts.textSpanEnd(occurance.textSpan) === end) {
- if (typeof isWriteAccess !== "undefined" && occurance.isWriteAccess !== isWriteAccess) {
- this.raiseError('verifyOccurancesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + occurance.isWriteAccess + ', expected: ' + isWriteAccess + '.');
+ for (let occurrence of occurrences) {
+ if (occurrence && occurrence.fileName === fileName && occurrence.textSpan.start === start && ts.textSpanEnd(occurrence.textSpan) === end) {
+ if (typeof isWriteAccess !== "undefined" && occurrence.isWriteAccess !== isWriteAccess) {
+ this.raiseError(`verifyOccurrencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${occurrence.isWriteAccess}, expected: ${isWriteAccess}.`);
}
return;
}
}
let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
- this.raiseError('verifyOccurancesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(occurances) + ')');
+ this.raiseError(`verifyOccurrencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(occurrences)})`);
}
public verifyOccurrencesAtPositionListCount(expectedCount: number) {
- this.taoInvalidReason = 'verifyOccurrencesAtPositionListCount NYI';
+ this.taoInvalidReason = "verifyOccurrencesAtPositionListCount NYI";
- let occurances = this.getOccurancesAtCurrentPosition();
- let actualCount = occurances ? occurances.length : 0;
+ let occurrences = this.getOccurrencesAtCurrentPosition();
+ let actualCount = occurrences ? occurrences.length : 0;
if (expectedCount !== actualCount) {
- this.raiseError('verifyOccurrencesAtPositionListCount failed - actual: ' + actualCount + ', expected:' + expectedCount);
+ this.raiseError(`verifyOccurrencesAtPositionListCount failed - actual: ${actualCount}, expected:${expectedCount}`);
+ }
+ }
+
+ private getDocumentHighlightsAtCurrentPosition(fileNamesToSearch: string[]) {
+ let filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name));
+ return this.languageService.getDocumentHighlights(this.activeFile.fileName, this.currentCaretPosition, filesToSearch);
+ }
+
+ public verifyDocumentHighlightsAtPositionListContains(fileName: string, start: number, end: number, fileNamesToSearch: string[], kind?: string) {
+ this.taoInvalidReason = 'verifyDocumentHighlightsAtPositionListContains NYI';
+
+ let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
+
+ if (!documentHighlights || documentHighlights.length === 0) {
+ this.raiseError('verifyDocumentHighlightsAtPositionListContains failed - found 0 highlights, expected at least one.');
+ }
+
+ for (let documentHighlight of documentHighlights) {
+ if (documentHighlight.fileName === fileName) {
+ let { highlightSpans } = documentHighlight;
+
+ for (let highlight of highlightSpans) {
+ if (highlight && highlight.textSpan.start === start && ts.textSpanEnd(highlight.textSpan) === end) {
+ if (typeof kind !== "undefined" && highlight.kind !== kind) {
+ this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - item "kind" value does not match, actual: ${highlight.kind}, expected: ${kind}.`);
+ }
+ return;
+ }
+ }
+ }
+ }
+
+ let missingItem = { fileName: fileName, start: start, end: end, kind: kind };
+ this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(documentHighlights)})`);
+ }
+
+ public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) {
+ this.taoInvalidReason = 'verifyDocumentHighlightsAtPositionListCount NYI';
+
+ let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch);
+ let actualCount = documentHighlights
+ ? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0)
+ : 0;
+
+ if (expectedCount !== actualCount) {
+ this.raiseError('verifyDocumentHighlightsAtPositionListCount failed - actual: ' + actualCount + ', expected:' + expectedCount);
}
}
@@ -2182,11 +2256,11 @@ module FourSlash {
}
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string) {
- this.scenarioActions.push('');
- this.scenarioActions.push('');
+ this.scenarioActions.push("");
+ this.scenarioActions.push(``);
if (text || documentation || kind) {
- this.taoInvalidReason = 'assertItemInCompletionList only supports the "name" parameter';
+ this.taoInvalidReason = "assertItemInCompletionList only supports the \"name\" parameter";
}
for (let i = 0; i < items.length; i++) {
@@ -2213,23 +2287,23 @@ module FourSlash {
let itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n");
- this.raiseError('Expected "' + JSON.stringify({ name, text, documentation, kind }) + '" to be in list [' + itemsString + ']');
+ this.raiseError(`Expected "${JSON.stringify({ name, text, documentation, kind })}" to be in list [${itemsString}]`);
}
private findFile(indexOrName: any) {
let result: FourSlashFile = null;
- if (typeof indexOrName === 'number') {
+ if (typeof indexOrName === "number") {
let index = indexOrName;
if (index >= this.testData.files.length) {
- throw new Error('File index (' + index + ') in openFile was out of range. There are only ' + this.testData.files.length + ' files in this test.');
+ throw new Error(`File index (${index}) in openFile was out of range. There are only ${this.testData.files.length} files in this test.`);
} else {
result = this.testData.files[index];
}
- } else if (typeof indexOrName === 'string') {
+ } else if (typeof indexOrName === "string") {
let name = indexOrName;
// names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName
- name = name.indexOf('/') === -1 ? (this.basePath + '/' + name) : name;
+ name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name;
let availableNames: string[] = [];
let foundIt = false;
@@ -2246,10 +2320,10 @@ module FourSlash {
}
if (!foundIt) {
- throw new Error('No test file named "' + name + '" exists. Available file names are:' + availableNames.join(', '));
+ throw new Error(`No test file named "${name}" exists. Available file names are: ${availableNames.join(", ")}`);
}
} else {
- throw new Error('Unknown argument type');
+ throw new Error("Unknown argument type");
}
return result;
@@ -2257,7 +2331,7 @@ module FourSlash {
private getLineColStringAtPosition(position: number) {
let pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position);
- return 'line ' + (pos.line + 1) + ', col ' + pos.character;
+ return `line ${(pos.line + 1)}, col ${pos.character}`;
}
public getMarkerByName(markerName: string) {
@@ -2265,21 +2339,21 @@ module FourSlash {
if (markerPos === undefined) {
let markerNames: string[] = [];
for (let m in this.testData.markerPositions) markerNames.push(m);
- throw new Error('Unknown marker "' + markerName + '" Available markers: ' + markerNames.map(m => '"' + m + '"').join(', '));
+ throw new Error(`Unknown marker "${markerName}" Available markers: ${markerNames.map(m => "\"" + m + "\"").join(", ")}`);
} else {
return markerPos;
}
}
private static makeWhitespaceVisible(text: string) {
- return text.replace(/ /g, '\u00B7').replace(/\r/g, '\u00B6').replace(/\n/g, '\u2193\n').replace(/\t/g, '\u2192\ ');
+ return text.replace(/ /g, "\u00B7").replace(/\r/g, "\u00B6").replace(/\n/g, "\u2193\n").replace(/\t/g, "\u2192\ ");
}
public getTestXmlData(): TestXmlData {
return {
actions: this.scenarioActions,
invalidReason: this.taoInvalidReason,
- originalName: ''
+ originalName: ""
};
}
@@ -2323,7 +2397,7 @@ module FourSlash {
currentTestState = new TestState(basePath, testType, testData);
- let result = '';
+ let result = "";
let host = Harness.Compiler.createCompilerHost(
[
{ unitName: Harness.Compiler.fourslashFileName, content: undefined },
@@ -2339,12 +2413,12 @@ module FourSlash {
let diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
if (diagnostics.length > 0) {
- throw new Error('Error compiling ' + fileName + ': ' +
- diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, ts.sys.newLine)).join('\r\n'));
+ throw new Error(`Error compiling ${fileName}: ` +
+ diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, ts.sys.newLine)).join("\r\n"));
}
program.emit(sourceFile);
- result = result || ''; // Might have an empty fourslash file
+ result = result || ""; // Might have an empty fourslash file
result = fourslashJsOutput + "\r\n" + result;
@@ -2365,12 +2439,12 @@ module FourSlash {
function chompLeadingSpace(content: string) {
let lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
- if ((lines[i].length !== 0) && (lines[i].charAt(0) !== ' ')) {
+ if ((lines[i].length !== 0) && (lines[i].charAt(0) !== " ")) {
return content;
}
}
- return lines.map(s => s.substr(1)).join('\n');
+ return lines.map(s => s.substr(1)).join("\n");
}
function parseTestData(basePath: string, contents: string, fileName: string): FourSlashData {
@@ -2386,7 +2460,7 @@ module FourSlash {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to string-based splitting instead and try to figure out the delimiting chars
- let lines = contents.split('\n');
+ let lines = contents.split("\n");
let markerPositions: MarkerMap = {};
let markers: Marker[] = [];
@@ -2401,23 +2475,23 @@ module FourSlash {
let line = lines[i];
let lineLength = line.length;
- if (lineLength > 0 && line.charAt(lineLength - 1) === '\r') {
+ if (lineLength > 0 && line.charAt(lineLength - 1) === "\r") {
line = line.substr(0, lineLength - 1);
}
- if (line.substr(0, 4) === '////') {
+ if (line.substr(0, 4) === "////") {
// Subfile content line
// Append to the current subfile content, inserting a newline needed
if (currentFileContent === null) {
- currentFileContent = '';
+ currentFileContent = "";
} else {
// End-of-line
- currentFileContent = currentFileContent + '\n';
+ currentFileContent = currentFileContent + "\n";
}
currentFileContent = currentFileContent + line.substr(4);
- } else if (line.substr(0, 2) === '//') {
+ } else if (line.substr(0, 2) === "//") {
// Comment line, check for global/file @options and record them
let match = optionRegex.exec(line.substr(2));
if (match) {
@@ -2425,7 +2499,7 @@ module FourSlash {
let fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]);
if (globalMetadataNamesIndex === -1) {
if (fileMetadataNamesIndex === -1) {
- throw new Error('Unrecognized metadata name "' + match[1] + '". Available global metadata names are: ' + globalMetadataNames.join(', ') + '; file metadata names are: ' + fileMetadataNames.join(', '));
+ throw new Error(`Unrecognized metadata name "${match[1]}". Available global metadata names are: ${globalMetadataNames.join(", ")}; file metadata names are: ${fileMetadataNames.join(", ")}`);
} else if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) {
// Found an @FileName directive, if this is not the first then create a new subfile
if (currentFileContent) {
@@ -2441,7 +2515,7 @@ module FourSlash {
currentFileName = fileName;
}
- currentFileName = basePath + '/' + match[2];
+ currentFileName = basePath + "/" + match[2];
currentFileOptions[match[1]] = match[2];
} else {
// Add other fileMetadata flag
@@ -2456,7 +2530,7 @@ module FourSlash {
}
}
// TODO: should be '==='?
- } else if (line == '' || lineLength === 0) {
+ } else if (line == "" || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
// Remove this behavior since it just causes errors now
} else {
@@ -2476,6 +2550,17 @@ module FourSlash {
}
}
+ // @Filename is the only directive that can be used in a test that contains tsconfig.json file.
+ if (containTSConfigJson(files)) {
+ let directive = getNonFileNameOptionInFileList(files);
+ if (!directive) {
+ directive = getNonFileNameOptionInObject(globalOptions);
+ }
+ if (directive) {
+ throw Error("It is not allowed to use tsconfig.json along with directive '" + directive + "'");
+ }
+ }
+
return {
markerPositions,
markers,
@@ -2485,6 +2570,23 @@ module FourSlash {
};
}
+ function containTSConfigJson(files: FourSlashFile[]): boolean {
+ return ts.forEach(files, f => f.fileOptions["Filename"] === "tsconfig.json");
+ }
+
+ function getNonFileNameOptionInFileList(files: FourSlashFile[]): string {
+ return ts.forEach(files, f => getNonFileNameOptionInObject(f.fileOptions));
+ }
+
+ function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): string {
+ for (let option in optionObject) {
+ if (option !== metadataOptionNames.fileName) {
+ return option;
+ }
+ }
+ return undefined;
+ }
+
const enum State {
none,
inSlashStarMarker,
@@ -2548,7 +2650,7 @@ module FourSlash {
content = chompLeadingSpace(content);
// Any slash-star comment with a character not in this string is not a marker.
- let validMarkerChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_';
+ let validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_";
/// The file content (minus metacharacters) so far
let output: string = "";
@@ -2683,7 +2785,7 @@ module FourSlash {
openMarker = null;
state = State.none;
} else if (validMarkerChars.indexOf(currentChar) < 0) {
- if (currentChar === '*' && i < content.length - 1 && content.charAt(i + 1) === '/') {
+ if (currentChar === "*" && i < content.length - 1 && content.charAt(i + 1) === "/") {
// The marker is about to be closed, ignore the 'invalid' char
} else {
// We've hit a non-valid marker character, so we were actually in a block comment
@@ -2698,10 +2800,10 @@ module FourSlash {
break;
}
- if (currentChar === '\n' && previousChar === '\r') {
+ if (currentChar === "\n" && previousChar === "\r") {
// Ignore trailing \n after a \r
continue;
- } else if (currentChar === '\n' || currentChar === '\r') {
+ } else if (currentChar === "\n" || currentChar === "\r") {
line++;
column = 1;
continue;
@@ -2735,4 +2837,4 @@ module FourSlash {
fileName: fileName
};
}
-}
\ No newline at end of file
+}
diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts
index 05a11c4f52d..d30a30d88e3 100644
--- a/src/harness/fourslashRunner.ts
+++ b/src/harness/fourslashRunner.ts
@@ -1,10 +1,11 @@
-///
-///
-///
+///
+///
+///
const enum FourSlashTestType {
Native,
Shims,
+ ShimsWithPreprocess,
Server
}
@@ -16,16 +17,20 @@ class FourSlashRunner extends RunnerBase {
super();
switch (testType) {
case FourSlashTestType.Native:
- this.basePath = 'tests/cases/fourslash';
- this.testSuiteName = 'fourslash';
+ this.basePath = "tests/cases/fourslash";
+ this.testSuiteName = "fourslash";
break;
case FourSlashTestType.Shims:
- this.basePath = 'tests/cases/fourslash/shims';
- this.testSuiteName = 'fourslash-shims';
+ this.basePath = "tests/cases/fourslash/shims";
+ this.testSuiteName = "fourslash-shims";
+ break;
+ case FourSlashTestType.ShimsWithPreprocess:
+ this.basePath = 'tests/cases/fourslash/shims-pp';
+ this.testSuiteName = 'fourslash-shims-pp';
break;
case FourSlashTestType.Server:
- this.basePath = 'tests/cases/fourslash/server';
- this.testSuiteName = 'fourslash-server';
+ this.basePath = "tests/cases/fourslash/server";
+ this.testSuiteName = "fourslash-server";
break;
}
}
@@ -35,25 +40,25 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
- describe(this.testSuiteName + ' tests', () => {
+ describe(this.testSuiteName + " tests", () => {
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
- let justName = fn.replace(/^.*[\\\/]/, '');
+ let justName = fn.replace(/^.*[\\\/]/, "");
// Convert to relative path
- let testIndex = fn.indexOf('tests/');
+ let testIndex = fn.indexOf("tests/");
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
- it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
+ it(this.testSuiteName + " test " + justName + " runs correctly", () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
});
});
- describe('Generate Tao XML', () => {
+ describe("Generate Tao XML", () => {
let invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
@@ -69,37 +74,37 @@ class FourSlashRunner extends RunnerBase {
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
let lines: string[] = [];
- lines.push('');
- lines.push('');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
+ lines.push("-->");
+ lines.push("");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
- lines.push('');
+ lines.push("");
} else {
- lines.push(' ');
+ lines.push(" ");
xml.actions.forEach(action => {
- lines.push(' ' + action);
+ lines.push(" " + action);
});
- lines.push(' ');
+ lines.push(" ");
}
});
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push(' ');
- lines.push('');
- Harness.IO.writeFile('built/local/fourslash.xml', lines.join('\r\n'));
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push(" ");
+ lines.push("");
+ Harness.IO.writeFile("built/local/fourslash.xml", lines.join("\r\n"));
});
});
}
@@ -108,6 +113,6 @@ class FourSlashRunner extends RunnerBase {
class GeneratedFourslashRunner extends FourSlashRunner {
constructor(testType: FourSlashTestType) {
super(testType);
- this.basePath += '/generated/';
+ this.basePath += "/generated/";
}
}
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index b6c10071cb1..a0366c0c40b 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -14,24 +14,27 @@
// limitations under the License.
//
-///
-///
-///
-///
-///
-///
-///
-///
-///
+///
+///
+///
+///
+///
+///
+///
+///
+///
-var Buffer: BufferConstructor = require('buffer').Buffer;
+// Block scoped definitions work poorly for global variables, temporarily enable var
+/* tslint:disable:no-var-keyword */
+var Buffer: BufferConstructor = require("buffer").Buffer;
// this will work in the browser via browserify
-var _chai: typeof chai = require('chai');
+var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
var expect: typeof _chai.expect = _chai.expect;
declare var __dirname: string; // Node-specific
var global = Function("return this").call(null);
+/* tslint:enable:no-var-keyword */
module Utils {
// Setup some globals based on the current environment
@@ -63,7 +66,7 @@ module Utils {
eval(fileContents);
break;
case ExecutionEnvironment.Node:
- let vm = require('vm');
+ let vm = require("vm");
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
} else {
@@ -71,7 +74,7 @@ module Utils {
}
break;
default:
- throw new Error('Unknown context');
+ throw new Error("Unknown context");
}
}
@@ -80,9 +83,9 @@ module Utils {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to use string-based splitting instead and try to figure out the delimiting chars
- let lines = content.split('\r\n');
+ let lines = content.split("\r\n");
if (lines.length === 1) {
- lines = content.split('\n');
+ lines = content.split("\n");
if (lines.length === 1) {
lines = content.split("\r");
@@ -93,7 +96,7 @@ module Utils {
/** Reads a file under /tests */
export function readTestFile(path: string) {
- if (path.indexOf('tests') < 0) {
+ if (path.indexOf("tests") < 0) {
path = "tests/" + path;
}
@@ -388,7 +391,7 @@ module Utils {
module Harness.Path {
export function getFileName(fullPath: string) {
- return fullPath.replace(/^.*[\\\/]/, '');
+ return fullPath.replace(/^.*[\\\/]/, "");
}
export function filePath(fullPath: string) {
@@ -412,6 +415,7 @@ module Harness {
log(text: string): void;
getMemoryUsage?(): number;
}
+ export var IO: IO;
module IOImpl {
declare class Enumerator {
@@ -484,8 +488,8 @@ module Harness {
declare let require: any;
let fs: any, pathModule: any;
if (require) {
- fs = require('fs');
- pathModule = require('path');
+ fs = require("fs");
+ pathModule = require("path");
} else {
fs = pathModule = {};
}
@@ -493,7 +497,7 @@ module Harness {
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let fileExists: typeof IO.fileExists = fs.existsSync;
- export let log: typeof IO.log = console.log;
+ export let log: typeof IO.log = s => console.log(s);
export function createDirectory(path: string) {
if (!directoryExists(path)) {
@@ -559,8 +563,8 @@ module Harness {
let serverRoot = "http://localhost:8888/";
// Unused?
- let newLine = '\r\n';
- let currentDirectory = () => '';
+ let newLine = "\r\n";
+ let currentDirectory = () => "";
let supportsCodePage = () => false;
module Http {
@@ -606,9 +610,9 @@ module Harness {
export function writeToServerSync(url: string, action: string, contents?: string): XHRResponse {
let xhr = new XMLHttpRequest();
try {
- let actionMsg = '?action=' + action;
- xhr.open('POST', url + actionMsg, false);
- xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
+ let actionMsg = "?action=" + action;
+ xhr.open("POST", url + actionMsg, false);
+ xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send(contents);
}
catch (e) {
@@ -624,7 +628,7 @@ module Harness {
}
export function deleteFile(path: string) {
- Http.writeToServerSync(serverRoot + path, 'DELETE', null);
+ Http.writeToServerSync(serverRoot + path, "DELETE", null);
}
export function directoryExists(path: string): boolean {
@@ -637,15 +641,15 @@ module Harness {
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
// path + fileName
- } else if (dirPath.indexOf('.') === -1) {
- dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
+ } else if (dirPath.indexOf(".") === -1) {
+ dirPath = dirPath.substring(0, dirPath.lastIndexOf("/"));
// path
} else {
// strip any trailing slash
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
}
- dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
+ dirPath = dirPath.substring(0, dirPath.lastIndexOf("/"));
}
return dirPath;
@@ -660,7 +664,7 @@ module Harness {
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
let response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
- let results = response.responseText.split(',');
+ let results = response.responseText.split(",");
if (spec) {
return results.filter(file => spec.test(file));
} else {
@@ -668,12 +672,12 @@ module Harness {
}
}
else {
- return [''];
+ return [""];
}
};
export let listFiles = Utils.memoize(_listFilesImpl);
- export let log = console.log;
+ export let log = (s: string) => console.log(s);
export function readFile(file: string) {
let response = Http.getFileFromServerSync(serverRoot + file);
@@ -685,12 +689,11 @@ module Harness {
}
export function writeFile(path: string, contents: string) {
- Http.writeToServerSync(serverRoot + path, 'WRITE', contents);
+ Http.writeToServerSync(serverRoot + path, "WRITE", contents);
}
}
}
- export var IO: IO;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
IO = IOImpl.CScript;
@@ -722,7 +725,7 @@ module Harness {
tcServicesFileName = "built/local/typescriptServices.js";
break;
default:
- throw new Error('Unknown context');
+ throw new Error("Unknown context");
}
export let tcServicesFile = IO.readFile(tcServicesFileName);
@@ -745,12 +748,12 @@ module Harness {
public Write(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
- this.currentLine = [(this.currentLine || ''), str].join('');
+ this.currentLine = [(this.currentLine || ""), str].join("");
}
public WriteLine(str: string) {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
- this.lines.push([(this.currentLine || ''), str].join(''));
+ this.lines.push([(this.currentLine || ""), str].join(""));
this.currentLine = undefined;
}
@@ -799,7 +802,7 @@ module Harness {
if (this.fileCollection.hasOwnProperty(p)) {
let current = this.fileCollection[p];
if (current.lines.length > 0) {
- if (p.indexOf('.d.ts') !== -1) { current.lines.unshift(['////[', Path.getFileName(p), ']'].join('')); }
+ if (p.indexOf(".d.ts") !== -1) { current.lines.unshift(["////[", Path.getFileName(p), "]"].join("")); }
result.push({ fileName: p, file: this.fileCollection[p] });
}
}
@@ -828,12 +831,12 @@ module Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
- export let defaultLibFileName = 'lib.d.ts';
- export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
- export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
+ export let defaultLibFileName = "lib.d.ts";
+ export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
+ export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
- export let fourslashFileName = 'fourslash.ts';
+ export let fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
@@ -865,6 +868,29 @@ module Harness {
}
};
inputFiles.forEach(register);
+
+ function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
+ fn = ts.normalizePath(fn);
+ if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
+ return filemap[getCanonicalFileName(fn)];
+ }
+ else if (currentDirectory) {
+ let canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
+ return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
+ }
+ else if (fn === fourslashFileName) {
+ let tsFn = "tests/cases/fourslash/" + fourslashFileName;
+ fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
+ return fourslashSourceFile;
+ }
+ else {
+ if (fn === defaultLibFileName) {
+ return languageVersion === ts.ScriptTarget.ES6 ? defaultES6LibSourceFile : defaultLibSourceFile;
+ }
+ // Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
+ return undefined;
+ }
+ }
let newLine =
newLineKind === ts.NewLineKind.CarriageReturnLineFeed ? carriageReturnLineFeed :
@@ -873,33 +899,14 @@ module Harness {
return {
getCurrentDirectory,
- getSourceFile: (fn, languageVersion) => {
- fn = ts.normalizePath(fn);
- if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
- return filemap[getCanonicalFileName(fn)];
- }
- else if (currentDirectory) {
- let canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
- return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
- }
- else if (fn === fourslashFileName) {
- let tsFn = 'tests/cases/fourslash/' + fourslashFileName;
- fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
- return fourslashSourceFile;
- }
- else {
- if (fn === defaultLibFileName) {
- return languageVersion === ts.ScriptTarget.ES6 ? defaultES6LibSourceFile : defaultLibSourceFile;
- }
- // Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
- return undefined;
- }
- },
+ getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
writeFile,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
- getNewLine: () => newLine
+ getNewLine: () => newLine,
+ fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
+ readFile: (fileName: string): string => { throw new Error("NotYetImplemented"); }
};
}
@@ -974,7 +981,7 @@ module Harness {
settingsCallback(null);
}
- let newLine = '\r\n';
+ let newLine = "\r\n";
options.skipDefaultLibCheck = true;
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
@@ -1011,19 +1018,19 @@ module Harness {
// "fileName", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve"
case "module":
case "modulegentarget":
- if (typeof setting.value === 'string') {
- if (setting.value.toLowerCase() === 'amd') {
+ if (typeof setting.value === "string") {
+ if (setting.value.toLowerCase() === "amd") {
options.module = ts.ModuleKind.AMD;
- } else if (setting.value.toLowerCase() === 'umd') {
+ } else if (setting.value.toLowerCase() === "umd") {
options.module = ts.ModuleKind.UMD;
- } else if (setting.value.toLowerCase() === 'commonjs') {
+ } else if (setting.value.toLowerCase() === "commonjs") {
options.module = ts.ModuleKind.CommonJS;
- } else if (setting.value.toLowerCase() === 'system') {
+ } else if (setting.value.toLowerCase() === "system") {
options.module = ts.ModuleKind.System;
- } else if (setting.value.toLowerCase() === 'unspecified') {
+ } else if (setting.value.toLowerCase() === "unspecified") {
options.module = ts.ModuleKind.None;
} else {
- throw new Error('Unknown module type ' + setting.value);
+ throw new Error("Unknown module type " + setting.value);
}
} else {
options.module = setting.value;
@@ -1031,152 +1038,152 @@ module Harness {
break;
case "target":
- case 'codegentarget':
- if (typeof setting.value === 'string') {
- if (setting.value.toLowerCase() === 'es3') {
+ case "codegentarget":
+ if (typeof setting.value === "string") {
+ if (setting.value.toLowerCase() === "es3") {
options.target = ts.ScriptTarget.ES3;
- } else if (setting.value.toLowerCase() === 'es5') {
+ } else if (setting.value.toLowerCase() === "es5") {
options.target = ts.ScriptTarget.ES5;
- } else if (setting.value.toLowerCase() === 'es6') {
+ } else if (setting.value.toLowerCase() === "es6") {
options.target = ts.ScriptTarget.ES6;
} else {
- throw new Error('Unknown compile target ' + setting.value);
+ throw new Error("Unknown compile target " + setting.value);
}
} else {
options.target = setting.value;
}
break;
- case 'experimentaldecorators':
- options.experimentalDecorators = setting.value === 'true';
+ case "experimentaldecorators":
+ options.experimentalDecorators = setting.value === "true";
break;
- case 'emitdecoratormetadata':
- options.emitDecoratorMetadata = setting.value === 'true';
+ case "emitdecoratormetadata":
+ options.emitDecoratorMetadata = setting.value === "true";
break;
- case 'experimentalasyncfunctions':
- options.experimentalAsyncFunctions = setting.value === 'true';
+ case "experimentalasyncfunctions":
+ options.experimentalAsyncFunctions = setting.value === "true";
break;
- case 'noemithelpers':
- options.noEmitHelpers = setting.value === 'true';
+ case "noemithelpers":
+ options.noEmitHelpers = setting.value === "true";
break;
- case 'noemitonerror':
- options.noEmitOnError = setting.value === 'true';
+ case "noemitonerror":
+ options.noEmitOnError = setting.value === "true";
break;
- case 'noresolve':
- options.noResolve = setting.value === 'true';
+ case "noresolve":
+ options.noResolve = setting.value === "true";
break;
- case 'noimplicitany':
- options.noImplicitAny = setting.value === 'true';
+ case "noimplicitany":
+ options.noImplicitAny = setting.value === "true";
break;
- case 'nolib':
- options.noLib = setting.value === 'true';
+ case "nolib":
+ options.noLib = setting.value === "true";
break;
- case 'out':
- case 'outfileoption':
+ case "out":
+ case "outfileoption":
options.out = setting.value;
break;
- case 'outdiroption':
- case 'outdir':
+ case "outdiroption":
+ case "outdir":
options.outDir = setting.value;
break;
- case 'skipdefaultlibcheck':
+ case "skipdefaultlibcheck":
options.skipDefaultLibCheck = setting.value === "true";
break;
- case 'sourceroot':
+ case "sourceroot":
options.sourceRoot = setting.value;
break;
- case 'maproot':
+ case "maproot":
options.mapRoot = setting.value;
break;
- case 'sourcemap':
- options.sourceMap = setting.value === 'true';
+ case "sourcemap":
+ options.sourceMap = setting.value === "true";
break;
- case 'declaration':
- options.declaration = setting.value === 'true';
+ case "declaration":
+ options.declaration = setting.value === "true";
break;
- case 'newline':
- if (setting.value.toLowerCase() === 'crlf') {
+ case "newline":
+ if (setting.value.toLowerCase() === "crlf") {
options.newLine = ts.NewLineKind.CarriageReturnLineFeed;
}
- else if (setting.value.toLowerCase() === 'lf') {
+ else if (setting.value.toLowerCase() === "lf") {
options.newLine = ts.NewLineKind.LineFeed;
}
else {
- throw new Error('Unknown option for newLine: ' + setting.value);
+ throw new Error("Unknown option for newLine: " + setting.value);
}
break;
- case 'comments':
- options.removeComments = setting.value === 'false';
+ case "comments":
+ options.removeComments = setting.value === "false";
break;
- case 'stripinternal':
- options.stripInternal = setting.value === 'true';
+ case "stripinternal":
+ options.stripInternal = setting.value === "true";
- case 'usecasesensitivefilenames':
- useCaseSensitiveFileNames = setting.value === 'true';
+ case "usecasesensitivefilenames":
+ useCaseSensitiveFileNames = setting.value === "true";
break;
- case 'filename':
+ case "filename":
// Not supported yet
break;
- case 'emitbom':
- options.emitBOM = setting.value === 'true';
+ case "emitbom":
+ options.emitBOM = setting.value === "true";
break;
- case 'errortruncation':
- options.noErrorTruncation = setting.value === 'false';
+ case "errortruncation":
+ options.noErrorTruncation = setting.value === "false";
break;
- case 'preserveconstenums':
- options.preserveConstEnums = setting.value === 'true';
+ case "preserveconstenums":
+ options.preserveConstEnums = setting.value === "true";
break;
- case 'isolatedmodules':
- options.isolatedModules = setting.value === 'true';
+ case "isolatedmodules":
+ options.isolatedModules = setting.value === "true";
break;
- case 'suppressimplicitanyindexerrors':
- options.suppressImplicitAnyIndexErrors = setting.value === 'true';
+ case "suppressimplicitanyindexerrors":
+ options.suppressImplicitAnyIndexErrors = setting.value === "true";
break;
- case 'includebuiltfile':
+ case "includebuiltfile":
let builtFileName = libFolder + setting.value;
includeBuiltFiles.push({ unitName: builtFileName, content: normalizeLineEndings(IO.readFile(builtFileName), newLine) });
break;
- case 'inlinesourcemap':
- options.inlineSourceMap = setting.value === 'true';
+ case "inlinesourcemap":
+ options.inlineSourceMap = setting.value === "true";
break;
- case 'inlinesources':
- options.inlineSources = setting.value === 'true';
+ case "inlinesources":
+ options.inlineSources = setting.value === "true";
break;
- case 'jsx':
- options.jsx = setting.value.toLowerCase() === 'react' ? ts.JsxEmit.React :
- setting.value.toLowerCase() === 'preserve' ? ts.JsxEmit.Preserve :
+ case "jsx":
+ options.jsx = setting.value.toLowerCase() === "react" ? ts.JsxEmit.React :
+ setting.value.toLowerCase() === "preserve" ? ts.JsxEmit.Preserve :
ts.JsxEmit.None;
break;
default:
- throw new Error('Unsupported compiler setting ' + setting.flag);
+ throw new Error("Unsupported compiler setting " + setting.flag);
}
}
}
@@ -1189,7 +1196,7 @@ module Harness {
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory?: string) {
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
- throw new Error('There were no errors and declFiles generated did not match number of js files generated');
+ throw new Error("There were no errors and declFiles generated did not match number of js files generated");
}
let declInputFiles: { unitName: string; content: string }[] = [];
@@ -1250,8 +1257,8 @@ module Harness {
}
function normalizeLineEndings(text: string, lineEnding: string): string {
- let normalized = text.replace(/\r\n?/g, '\n');
- if (lineEnding !== '\n') {
+ let normalized = text.replace(/\r\n?/g, "\n");
+ if (lineEnding !== "\n") {
normalized = normalized.replace(/\n/g, lineEnding);
}
return normalized;
@@ -1282,10 +1289,10 @@ module Harness {
let message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
let errLines = RunnerBase.removeFullPaths(message)
- .split('\n')
- .map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
+ .split("\n")
+ .map(s => s.length > 0 && s.charAt(s.length - 1) === "\r" ? s.substr(0, s.length - 1) : s)
.filter(s => s.length > 0)
- .map(s => '!!! ' + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s);
+ .map(s => "!!! " + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s);
errLines.forEach(e => outputLines.push(e));
totalErrorsReported++;
@@ -1305,7 +1312,7 @@ module Harness {
// Header
- outputLines.push('==== ' + inputFile.unitName + ' (' + fileErrors.length + ' errors) ====');
+ outputLines.push("==== " + inputFile.unitName + " (" + fileErrors.length + " errors) ====");
// Make sure we emit something for every error
let markedErrorCount = 0;
@@ -1314,13 +1321,13 @@ module Harness {
// we have to string-based splitting instead and try to figure out the delimiting chars
let lineStarts = ts.computeLineStarts(inputFile.content);
- let lines = inputFile.content.split('\n');
+ let lines = inputFile.content.split("\n");
if (lines.length === 1) {
lines = lines[0].split("\r");
}
lines.forEach((line, lineIndex) => {
- if (line.length > 0 && line.charAt(line.length - 1) === '\r') {
+ if (line.length > 0 && line.charAt(line.length - 1) === "\r") {
line = line.substr(0, line.length - 1);
}
@@ -1333,7 +1340,7 @@ module Harness {
nextLineStart = lineStarts[lineIndex + 1];
}
// Emit this line from the original file
- outputLines.push(' ' + line);
+ outputLines.push(" " + line);
fileErrors.forEach(err => {
// Does any error start or continue on to this line? Emit squiggles
let end = ts.textSpanEnd(err);
@@ -1345,7 +1352,7 @@ module Harness {
// Calculate the start of the squiggle
let squiggleStart = Math.max(0, relativeOffset);
// TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another
- outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~'));
+ outputLines.push(" " + line.substr(0, squiggleStart).replace(/[^\s]/g, " ") + new Array(Math.min(length, line.length - squiggleStart) + 1).join("~"));
// If the error ended here, or we're at the end of the file, emit its message
if ((lineIndex === lines.length - 1) || nextLineStart > end) {
@@ -1360,7 +1367,7 @@ module Harness {
});
// Verify we didn't miss any errors in this file
- assert.equal(markedErrorCount, fileErrors.length, 'count of errors in ' + inputFile.unitName);
+ assert.equal(markedErrorCount, fileErrors.length, "count of errors in " + inputFile.unitName);
});
let numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@@ -1373,10 +1380,10 @@ module Harness {
});
// Verify we didn't miss any errors in total
- assert.equal(totalErrorsReported + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, 'total number of errors');
+ assert.equal(totalErrorsReported + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, "total number of errors");
return minimalDiagnosticsToString(diagnostics) +
- ts.sys.newLine + ts.sys.newLine + outputLines.join('\r\n');
+ ts.sys.newLine + ts.sys.newLine + outputLines.join("\r\n");
}
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
@@ -1384,15 +1391,15 @@ module Harness {
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
// Emit them
- let result = '';
+ let result = "";
for (let outputFile of outputFiles) {
// Some extra spacing if this isn't the first file
if (result.length) {
- result += '\r\n\r\n';
+ result += "\r\n\r\n";
}
// FileName header + content
- result += '/*====== ' + outputFile.fileName + ' ======*/\r\n';
+ result += "/*====== " + outputFile.fileName + " ======*/\r\n";
result += outputFile.code;
}
@@ -1400,7 +1407,7 @@ module Harness {
return result;
function cleanName(fn: string) {
- let lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
+ let lastSlash = ts.normalizeSlashes(fn).lastIndexOf("/");
return fn.substr(lastSlash + 1).toLowerCase();
}
}
@@ -1418,7 +1425,7 @@ module Harness {
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
- throw new Error('compileString NYI');
+ throw new Error("compileString NYI");
}
export interface GeneratedFile {
@@ -1432,26 +1439,26 @@ module Harness {
}
export function isTS(fileName: string) {
- return stringEndsWith(fileName, '.ts');
+ return stringEndsWith(fileName, ".ts");
}
export function isTSX(fileName: string) {
- return stringEndsWith(fileName, '.tsx');
+ return stringEndsWith(fileName, ".tsx");
}
export function isDTS(fileName: string) {
- return stringEndsWith(fileName, '.d.ts');
+ return stringEndsWith(fileName, ".d.ts");
}
export function isJS(fileName: string) {
- return stringEndsWith(fileName, '.js');
+ return stringEndsWith(fileName, ".js");
}
export function isJSX(fileName: string) {
- return stringEndsWith(fileName, '.jsx');
+ return stringEndsWith(fileName, ".jsx");
}
export function isJSMap(fileName: string) {
- return stringEndsWith(fileName, '.js.map');
+ return stringEndsWith(fileName, ".js.map") || stringEndsWith(fileName, ".jsx.map");
}
/** Contains the code and errors of a compilation and some helper methods to check its status. */
@@ -1478,7 +1485,7 @@ module Harness {
this.sourceMaps.push(emittedFile);
}
else {
- throw new Error('Unrecognized file extension for file ' + emittedFile.fileName);
+ throw new Error("Unrecognized file extension for file " + emittedFile.fileName);
}
});
@@ -1587,10 +1594,10 @@ module Harness {
// Subfile content line
// Append to the current subfile content, inserting a newline needed
if (currentFileContent === null) {
- currentFileContent = '';
+ currentFileContent = "";
} else {
// End-of-line
- currentFileContent = currentFileContent + '\n';
+ currentFileContent = currentFileContent + "\n";
}
currentFileContent = currentFileContent + line;
}
@@ -1601,7 +1608,7 @@ module Harness {
// EOF, push whatever remains
let newTestFile2 = {
- content: currentFileContent || '',
+ content: currentFileContent || "",
name: currentFileName,
fileOptions: currentFileOptions,
originalFilePath: fileName,
@@ -1623,27 +1630,27 @@ module Harness {
export function localPath(fileName: string, baselineFolder?: string, subfolder?: string) {
if (baselineFolder === undefined) {
- return baselinePath(fileName, 'local', 'tests/baselines', subfolder);
+ return baselinePath(fileName, "local", "tests/baselines", subfolder);
}
else {
- return baselinePath(fileName, 'local', baselineFolder, subfolder);
+ return baselinePath(fileName, "local", baselineFolder, subfolder);
}
}
function referencePath(fileName: string, baselineFolder?: string, subfolder?: string) {
if (baselineFolder === undefined) {
- return baselinePath(fileName, 'reference', 'tests/baselines', subfolder);
+ return baselinePath(fileName, "reference", "tests/baselines", subfolder);
}
else {
- return baselinePath(fileName, 'reference', baselineFolder, subfolder);
+ return baselinePath(fileName, "reference", baselineFolder, subfolder);
}
}
function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) {
if (subfolder !== undefined) {
- return Harness.userSpecifiedRoot + baselineFolder + '/' + subfolder + '/' + type + '/' + fileName;
+ return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName;
} else {
- return Harness.userSpecifiedRoot + baselineFolder + '/' + type + '/' + fileName;
+ return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName;
}
}
@@ -1677,7 +1684,7 @@ module Harness {
let actual = generateContent();
if (actual === undefined) {
- throw new Error('The generated content was "undefined". Return "null" if no baselining is required."');
+ throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\"");
}
// Store the content in the 'local' folder so we
@@ -1700,10 +1707,10 @@ module Harness {
let refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (actual === null) {
- actual = '';
+ actual = "";
}
- let expected = '';
+ let expected = "";
if (IO.fileExists(refFileName)) {
expected = IO.readFile(refFileName);
}
@@ -1712,10 +1719,10 @@ module Harness {
}
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
- let encoded_actual = (new Buffer(actual)).toString('utf8');
+ let encoded_actual = (new Buffer(actual)).toString("utf8");
if (expected != encoded_actual) {
// Overwrite & issue error
- let errMsg = 'The baseline file ' + relativeFileName + ' has changed';
+ let errMsg = "The baseline file " + relativeFileName + " has changed";
throw new Error(errMsg);
}
}
@@ -1744,7 +1751,7 @@ module Harness {
}
export function isLibraryFile(filePath: string): boolean {
- return (Path.getFileName(filePath) === 'lib.d.ts') || (Path.getFileName(filePath) === 'lib.core.d.ts');
+ return (Path.getFileName(filePath) === "lib.d.ts") || (Path.getFileName(filePath) === "lib.core.d.ts");
}
export function isBuiltFile(filePath: string): boolean {
diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts
index 3c543e50566..f228bc862d8 100644
--- a/src/harness/harnessLanguageService.ts
+++ b/src/harness/harnessLanguageService.ts
@@ -1,7 +1,7 @@
-///
-///
-///
-///
+///
+///
+///
+///
module Harness.LanguageService {
export class ScriptInfo {
@@ -203,9 +203,35 @@ module Harness.LanguageService {
/// Shim adapter
class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceShimHost, ts.CoreServicesShimHost {
private nativeHost: NativeLanguageServiceHost;
- constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
+
+ public getModuleResolutionsForFile: (fileName: string)=> string;
+
+ constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
this.nativeHost = new NativeLanguageServiceHost(cancellationToken, options);
+
+ if (preprocessToResolve) {
+ let compilerOptions = this.nativeHost.getCompilationSettings()
+ let moduleResolutionHost: ts.ModuleResolutionHost = {
+ fileExists: fileName => this.getScriptInfo(fileName) !== undefined,
+ readFile: fileName => {
+ let scriptInfo = this.getScriptInfo(fileName);
+ return scriptInfo && scriptInfo.content;
+ }
+ };
+ this.getModuleResolutionsForFile = (fileName) => {
+ let scriptInfo = this.getScriptInfo(fileName);
+ let preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true);
+ let imports: ts.Map = {};
+ for (let module of preprocessInfo.importedFiles) {
+ let resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
+ if (resolutionInfo.resolvedFileName) {
+ imports[module.fileName] = resolutionInfo.resolvedFileName;
+ }
+ }
+ return JSON.stringify(imports);
+ }
+ }
}
getFilenames(): string[] { return this.nativeHost.getFilenames(); }
@@ -229,7 +255,11 @@ module Harness.LanguageService {
readDirectory(rootDir: string, extension: string): string {
throw new Error("NYI");
}
-
+ fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
+ readFile(fileName: string) {
+ let snapshot = this.nativeHost.getScriptSnapshot(fileName);
+ return snapshot && snapshot.getText(0, snapshot.getLength());
+ }
log(s: string): void { this.nativeHost.log(s); }
trace(s: string): void { this.nativeHost.trace(s); }
error(s: string): void { this.nativeHost.error(s); }
@@ -242,7 +272,7 @@ module Harness.LanguageService {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
- let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
+ let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n");
let entries: ts.ClassificationInfo[] = [];
let i = 0;
let position = 0;
@@ -381,6 +411,9 @@ module Harness.LanguageService {
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: ts.FormatCodeOptions): ts.TextChange[] {
return unwrapJSONCallResult(this.shim.getFormattingEditsAfterKeystroke(fileName, position, key, JSON.stringify(options)));
}
+ getDocCommentTemplateAtPosition(fileName: string, position: number): ts.TextInsertion {
+ return unwrapJSONCallResult(this.shim.getDocCommentTemplateAtPosition(fileName, position));
+ }
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
@@ -396,8 +429,8 @@ module Harness.LanguageService {
export class ShimLanugageServiceAdapter implements LanguageServiceAdapter {
private host: ShimLanguageServiceHost;
private factory: ts.TypeScriptServicesFactory;
- constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
- this.host = new ShimLanguageServiceHost(cancellationToken, options);
+ constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
+ this.host = new ShimLanguageServiceHost(preprocessToResolve, cancellationToken, options);
this.factory = new TypeScript.Services.TypeScriptServicesFactory();
}
getHost() { return this.host; }
@@ -416,6 +449,7 @@ module Harness.LanguageService {
let convertResult: ts.PreProcessedFileInfo = {
referencedFiles: [],
importedFiles: [],
+ ambientExternalModules: [],
isLibFile: shimResult.isLibFile
};
diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts
index c7b57a7d51f..db82a47d362 100644
--- a/src/harness/loggedIO.ts
+++ b/src/harness/loggedIO.ts
@@ -73,7 +73,7 @@ interface PlaybackControl {
module Playback {
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
- let recordLogFileNameBase = '';
+ let recordLogFileNameBase = "";
interface Memoized {
(s: string): T;
@@ -99,7 +99,7 @@ module Playback {
return {
timestamp: (new Date()).toString(),
arguments: [],
- currentDirectory: '',
+ currentDirectory: "",
filesRead: [],
filesWritten: [],
filesDeleted: [],
@@ -110,7 +110,7 @@ module Playback {
dirExists: [],
dirsCreated: [],
pathsResolved: [],
- executingPath: ''
+ executingPath: ""
};
}
@@ -170,7 +170,7 @@ module Playback {
if (defaultValue !== undefined) {
return defaultValue;
} else {
- throw new Error('No matching result in log array for: ' + JSON.stringify(expectedFields));
+ throw new Error("No matching result in log array for: " + JSON.stringify(expectedFields));
}
}
return results[0].result;
@@ -195,7 +195,7 @@ module Playback {
}
// If we got here, we didn't find a match
if (defaultValue === undefined) {
- throw new Error('No matching result in log array for path: ' + expectedPath);
+ throw new Error("No matching result in log array for path: " + expectedPath);
} else {
return defaultValue;
}
@@ -203,7 +203,7 @@ module Playback {
let pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
- let key = left + '-~~-' + right;
+ let key = left + "-~~-" + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
@@ -233,14 +233,14 @@ module Playback {
wrapper.endRecord = () => {
if (recordLog !== undefined) {
let i = 0;
- let fn = () => recordLogFileNameBase + i + '.json';
+ let fn = () => recordLogFileNameBase + i + ".json";
while (underlying.fileExists(fn())) i++;
underlying.writeFile(fn(), JSON.stringify(recordLog));
recordLog = undefined;
}
};
- Object.defineProperty(wrapper, 'args', {
+ Object.defineProperty(wrapper, "args", {
get() {
if (replayLog !== undefined) {
return replayLog.arguments;
@@ -276,7 +276,7 @@ module Playback {
wrapper.getCurrentDirectory = () => {
if (replayLog !== undefined) {
- return replayLog.currentDirectory || '';
+ return replayLog.currentDirectory || "";
} else if (recordLog !== undefined) {
return recordLog.currentDirectory = underlying.getCurrentDirectory();
} else {
@@ -286,7 +286,7 @@ module Playback {
wrapper.resolvePath = recordReplay(wrapper.resolvePath, underlying)(
(path) => callAndRecord(underlying.resolvePath(path), recordLog.pathsResolved, { path: path }),
- memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + '/' + path : ts.normalizeSlashes(path))));
+ memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + "/" + path : ts.normalizeSlashes(path))));
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
(path) => {
@@ -299,7 +299,7 @@ module Playback {
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path: path, contents: contents, bom: false }),
- (path, contents) => noOpReplay('writeFile'));
+ (path, contents) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {
diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts
index 5ea118aacbf..1790956755a 100644
--- a/src/harness/projectsRunner.ts
+++ b/src/harness/projectsRunner.ts
@@ -74,7 +74,7 @@ class ProjectRunner extends RunnerBase {
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
}
- let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
+ let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, "").replace(/\.json/, "");
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
@@ -191,7 +191,9 @@ class ProjectRunner extends RunnerBase {
getCurrentDirectory,
getCanonicalFileName: Harness.Compiler.getCanonicalFileName,
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
- getNewLine: () => ts.sys.newLine
+ getNewLine: () => ts.sys.newLine,
+ fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
+ readFile: fileName => Harness.IO.readFile(fileName)
};
}
}
@@ -331,9 +333,9 @@ class ProjectRunner extends RunnerBase {
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
- let name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
+ let name = "Compiling project for " + testCase.scenario + ": testcase " + testCaseFileName;
- describe('Projects tests', () => {
+ describe("Projects tests", () => {
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
let compilerResult: BatchCompileProjectTestCaseResult;
@@ -367,27 +369,27 @@ class ProjectRunner extends RunnerBase {
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
- it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
- Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
+ it("Resolution information of (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
+ Harness.Baseline.runBaseline("Resolution information of (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".json", () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
});
});
- it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
+ it("Errors for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.errors.length) {
- Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
+ Harness.Baseline.runBaseline("Errors for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".errors.txt", () => {
return getErrorsBaseline(compilerResult);
});
}
});
- it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
+ it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
- Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
+ Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
@@ -400,9 +402,9 @@ class ProjectRunner extends RunnerBase {
});
- it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
+ it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
- Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
+ Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
@@ -411,11 +413,11 @@ class ProjectRunner extends RunnerBase {
// Verify that all the generated .d.ts files compile
- it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
+ it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
let dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
- Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
+ Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
return getErrorsBaseline(dTsCompileResult);
});
}
diff --git a/src/harness/runner.ts b/src/harness/runner.ts
index e4ed604e980..3d97938011c 100644
--- a/src/harness/runner.ts
+++ b/src/harness/runner.ts
@@ -13,12 +13,12 @@
// limitations under the License.
//
-///
-///
-///
-///
-///
-///
+///
+///
+///
+///
+///
+///
let runners: RunnerBase[] = [];
let iterations: number = 1;
@@ -32,13 +32,13 @@ function runTests(runners: RunnerBase[]) {
}
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
-let mytestconfig = 'mytest.config';
-let testconfig = 'test.config';
+let mytestconfig = "mytest.config";
+let testconfig = "test.config";
let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
- (Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : '');
+ (Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : "");
-if (testConfigFile !== '') {
+if (testConfigFile !== "") {
let testConfig = JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
@@ -51,33 +51,36 @@ if (testConfigFile !== '') {
}
switch (option) {
- case 'compiler':
+ case "compiler":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions));
runners.push(new ProjectRunner());
break;
- case 'conformance':
+ case "conformance":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
break;
- case 'project':
+ case "project":
runners.push(new ProjectRunner());
break;
- case 'fourslash':
+ case "fourslash":
runners.push(new FourSlashRunner(FourSlashTestType.Native));
break;
- case 'fourslash-shims':
+ case "fourslash-shims":
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
break;
+ case 'fourslash-shims-pp':
+ runners.push(new FourSlashRunner(FourSlashTestType.ShimsWithPreprocess));
+ break;
case 'fourslash-server':
runners.push(new FourSlashRunner(FourSlashTestType.Server));
break;
- case 'fourslash-generated':
+ case "fourslash-generated":
runners.push(new GeneratedFourslashRunner(FourSlashTestType.Native));
break;
- case 'rwc':
+ case "rwc":
runners.push(new RWCRunner());
break;
- case 'test262':
+ case "test262":
runners.push(new Test262BaselineRunner());
break;
}
@@ -98,10 +101,11 @@ if (runners.length === 0) {
// language services
runners.push(new FourSlashRunner(FourSlashTestType.Native));
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
+ runners.push(new FourSlashRunner(FourSlashTestType.ShimsWithPreprocess));
runners.push(new FourSlashRunner(FourSlashTestType.Server));
// runners.push(new GeneratedFourslashRunner());
}
-ts.sys.newLine = '\r\n';
+ts.sys.newLine = "\r\n";
runTests(runners);
diff --git a/src/harness/runnerbase.ts b/src/harness/runnerbase.ts
index 406ca7caeae..afe757ea829 100644
--- a/src/harness/runnerbase.ts
+++ b/src/harness/runnerbase.ts
@@ -33,7 +33,7 @@ abstract class RunnerBase {
// when running in the browser the 'full path' is the host name, shows up in error baselines
let localHost = /http:\/localhost:\d+/g;
- fixedPath = fixedPath.replace(localHost, '');
+ fixedPath = fixedPath.replace(localHost, "");
return fixedPath;
}
}
\ No newline at end of file
diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts
index 54aeff18efd..d8b52ec2e39 100644
--- a/src/harness/rwcRunner.ts
+++ b/src/harness/rwcRunner.ts
@@ -1,7 +1,7 @@
-///
-///
-///
-///
+///
+///
+///
+///
module RWC {
function runWithIOLog(ioLog: IOLog, fn: () => void) {
@@ -26,8 +26,8 @@ module RWC {
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
- Subfolder: 'rwc',
- Baselinefolder: 'internal/baselines'
+ Subfolder: "rwc",
+ Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
@@ -49,7 +49,7 @@ module RWC {
useCustomLibraryFile = undefined;
});
- it('can compile', () => {
+ it("can compile", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
@@ -74,10 +74,11 @@ module RWC {
});
// Add files to compilation
+ let isInInputList = (resolvedPath: string) => (inputFile: { unitName: string; content: string; }) => inputFile.unitName === resolvedPath;
for (let fileRead of ioLog.filesRead) {
// Check if the file is already added into the set of input files.
- var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
- let inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
+ const resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
+ let inInputList = ts.forEach(inputFiles, isInInputList(resolvedPath));
if (!Harness.isLibraryFile(fileRead.path)) {
if (inInputList) {
@@ -130,14 +131,14 @@ module RWC {
});
- it('has the expected emitted code', () => {
- Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
+ it("has the expected emitted code", () => {
+ Harness.Baseline.runBaseline("has the expected emitted code", baseName + ".output.js", () => {
return Harness.Compiler.collateOutputs(compilerResult.files);
}, false, baselineOpts);
});
- it('has the expected declaration file content', () => {
- Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
+ it("has the expected declaration file content", () => {
+ Harness.Baseline.runBaseline("has the expected declaration file content", baseName + ".d.ts", () => {
if (!compilerResult.declFilesCode.length) {
return null;
}
@@ -146,8 +147,8 @@ module RWC {
}, false, baselineOpts);
});
- it('has the expected source maps', () => {
- Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
+ it("has the expected source maps", () => {
+ Harness.Baseline.runBaseline("has the expected source maps", baseName + ".map", () => {
if (!compilerResult.sourceMaps.length) {
return null;
}
@@ -156,16 +157,16 @@ module RWC {
}, false, baselineOpts);
});
- /*it('has correct source map record', () => {
+ /*it("has correct source map record", () => {
if (compilerOptions.sourceMap) {
- Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
+ Harness.Baseline.runBaseline("has correct source map record", baseName + ".sourcemap.txt", () => {
return compilerResult.getSourceMapRecord();
}, false, baselineOpts);
}
});*/
- it('has the expected errors', () => {
- Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
+ it("has the expected errors", () => {
+ Harness.Baseline.runBaseline("has the expected errors", baseName + ".errors.txt", () => {
if (compilerResult.errors.length === 0) {
return null;
}
@@ -176,9 +177,9 @@ module RWC {
// Ideally, a generated declaration file will have no errors. But we allow generated
// declaration file errors as part of the baseline.
- it('has the expected errors in generated declaration files', () => {
+ it("has the expected errors in generated declaration files", () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
- Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
+ Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
let declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts
index 767dd37949f..55ca9ea9651 100644
--- a/src/harness/sourceMapRecorder.ts
+++ b/src/harness/sourceMapRecorder.ts
@@ -13,7 +13,7 @@
// limitations under the License.
//
-///
+///
module Harness.SourceMapRecoder {
@@ -50,11 +50,11 @@ module Harness.SourceMapRecoder {
return true;
}
- if (sourceMapMappings.charAt(decodingIndex) == ',') {
+ if (sourceMapMappings.charAt(decodingIndex) == ",") {
return true;
}
- if (sourceMapMappings.charAt(decodingIndex) == ';') {
+ if (sourceMapMappings.charAt(decodingIndex) == ";") {
return true;
}
@@ -117,7 +117,7 @@ module Harness.SourceMapRecoder {
}
while (decodingIndex < sourceMapMappings.length) {
- if (sourceMapMappings.charAt(decodingIndex) == ';') {
+ if (sourceMapMappings.charAt(decodingIndex) == ";") {
// New line
decodeOfEncodedMapping.emittedLine++;
decodeOfEncodedMapping.emittedColumn = 1;
@@ -125,7 +125,7 @@ module Harness.SourceMapRecoder {
continue;
}
- if (sourceMapMappings.charAt(decodingIndex) == ',') {
+ if (sourceMapMappings.charAt(decodingIndex) == ",") {
// Next entry is on same line - no action needed
decodingIndex++;
continue;
@@ -459,6 +459,6 @@ module Harness.SourceMapRecoder {
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
- return sourceMapRecoder.lines.join('\r\n');
+ return sourceMapRecoder.lines.join("\r\n");
}
}
diff --git a/src/harness/test262Runner.ts b/src/harness/test262Runner.ts
index e34e58844ac..d9bbd55e7a3 100644
--- a/src/harness/test262Runner.ts
+++ b/src/harness/test262Runner.ts
@@ -1,9 +1,9 @@
-///
-///
+///
+///
class Test262BaselineRunner extends RunnerBase {
- private static basePath = 'internal/cases/test262';
- private static helpersFilePath = 'tests/cases/test262-harness/helpers.d.ts';
+ private static basePath = "internal/cases/test262";
+ private static helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
private static helperFile = {
unitName: Test262BaselineRunner.helpersFilePath,
content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath)
@@ -15,8 +15,8 @@ class Test262BaselineRunner extends RunnerBase {
module: ts.ModuleKind.CommonJS
};
private static baselineOptions: Harness.Baseline.BaselineOptions = {
- Subfolder: 'test262',
- Baselinefolder: 'internal/baselines'
+ Subfolder: "test262",
+ Baselinefolder: "internal/baselines"
};
private static getTestFilePath(filename: string): string {
@@ -24,7 +24,7 @@ class Test262BaselineRunner extends RunnerBase {
}
private runTest(filePath: string) {
- describe('test262 test for ' + filePath, () => {
+ describe("test262 test for " + filePath, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let testState: {
@@ -36,7 +36,7 @@ class Test262BaselineRunner extends RunnerBase {
before(() => {
let content = Harness.IO.readFile(filePath);
- let testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
+ let testFilename = ts.removeFileExtension(filePath).replace(/\//g, "_") + ".test";
let testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
let inputFiles = testCaseContent.testUnitData.map(unit => {
@@ -61,15 +61,15 @@ class Test262BaselineRunner extends RunnerBase {
testState = undefined;
});
- it('has the expected emitted code', () => {
- Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => {
+ it("has the expected emitted code", () => {
+ Harness.Baseline.runBaseline("has the expected emitted code", testState.filename + ".output.js", () => {
let files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
return Harness.Compiler.collateOutputs(files);
}, false, Test262BaselineRunner.baselineOptions);
});
- it('has the expected errors', () => {
- Harness.Baseline.runBaseline('has the expected errors', testState.filename + '.errors.txt', () => {
+ it("has the expected errors", () => {
+ Harness.Baseline.runBaseline("has the expected errors", testState.filename + ".errors.txt", () => {
let errors = testState.compilerResult.errors;
if (errors.length === 0) {
return null;
@@ -79,13 +79,13 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
- it('satisfies inletiants', () => {
+ it("satisfies inletiants", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
- it('has the expected AST', () => {
- Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt', () => {
+ it("has the expected AST", () => {
+ Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts
index 27cb3574473..0fef0779965 100644
--- a/src/harness/typeWriter.ts
+++ b/src/harness/typeWriter.ts
@@ -71,4 +71,4 @@ class TypeWriterWalker {
symbol: symbolString
});
}
-}
+}
\ No newline at end of file
diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts
index 32e8fb45ce4..8eec72f1a4c 100644
--- a/src/lib/dom.generated.d.ts
+++ b/src/lib/dom.generated.d.ts
@@ -11962,7 +11962,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
onvolumechange: (ev: Event) => any;
onwaiting: (ev: Event) => any;
opener: Window;
- orientation: string;
+ orientation: string | number;
outerHeight: number;
outerWidth: number;
pageXOffset: number;
@@ -12777,7 +12777,7 @@ declare var onunload: (ev: Event) => any;
declare var onvolumechange: (ev: Event) => any;
declare var onwaiting: (ev: Event) => any;
declare var opener: Window;
-declare var orientation: string;
+declare var orientation: string | number;
declare var outerHeight: number;
declare var outerWidth: number;
declare var pageXOffset: number;
@@ -12952,4 +12952,4 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any,
declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
-declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
\ No newline at end of file
+declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts
index 5c41869e487..db8b02f34d7 100644
--- a/src/lib/webworker.generated.d.ts
+++ b/src/lib/webworker.generated.d.ts
@@ -806,7 +806,7 @@ interface EventListenerObject {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
- (event: Event | string, source?: string, fileno?: number, columnNumber?: number): void;
+ (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
diff --git a/src/server/client.ts b/src/server/client.ts
index 3ad7230cf33..ae234750d88 100644
--- a/src/server/client.ts
+++ b/src/server/client.ts
@@ -183,7 +183,7 @@ namespace ts.server {
return {
configFileName: response.body.configFileName,
- fileNameList: response.body.fileNameList
+ fileNames: response.body.fileNames
};
}
@@ -527,8 +527,33 @@ namespace ts.server {
});
}
- getDocumentHighlights(fileName: string, position: number): DocumentHighlights[] {
- throw new Error("Not Implemented Yet.");
+ getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
+ let { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
+ let args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
+
+ let request = this.processRequest(CommandNames.DocumentHighlights, args);
+ let response = this.processResponse(request);
+
+ let self = this;
+ return response.body.map(convertToDocumentHighlights);
+
+ function convertToDocumentHighlights(item: ts.server.protocol.DocumentHighlightsItem): ts.DocumentHighlights {
+ let { file, highlightSpans } = item;
+
+ return {
+ fileName: file,
+ highlightSpans: highlightSpans.map(convertHighlightSpan)
+ };
+
+ function convertHighlightSpan(span: ts.server.protocol.HighlightSpan): ts.HighlightSpan {
+ let start = self.lineOffsetToPosition(file, span.start);
+ let end = self.lineOffsetToPosition(file, span.end);
+ return {
+ textSpan: ts.createTextSpanFromBounds(start, end),
+ kind: span.kind
+ };
+ }
+ }
}
getOutliningSpans(fileName: string): OutliningSpan[] {
@@ -538,6 +563,10 @@ namespace ts.server {
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
}
+
+ getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
+ throw new Error("Not Implemented Yet.");
+ }
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts
index 6f4ab914345..8e9f4485069 100644
--- a/src/server/editorServices.ts
+++ b/src/server/editorServices.ts
@@ -78,15 +78,76 @@ namespace ts.server {
return this.snap().getChangeRange(oldSnapshot);
}
}
-
+
+ interface TimestampedResolvedModule extends ResolvedModule {
+ lastCheckTime: number;
+ }
+
export class LSHost implements ts.LanguageServiceHost {
ls: ts.LanguageService = null;
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.Map = {};
roots: ScriptInfo[] = [];
-
+ private resolvedModuleNames: ts.FileMap