Merge remote-tracking branch 'upstream/master' into loadJsFromModules

This commit is contained in:
Bill Ticehurst
2016-05-23 17:14:23 -07:00
190 changed files with 92448 additions and 23985 deletions
+60 -49
View File
@@ -160,7 +160,7 @@ var harnessSources = harnessCoreSources.concat([
"protocol.d.ts",
"session.ts",
"client.ts",
"editorServices.ts",
"editorServices.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}));
@@ -174,7 +174,7 @@ var es2015LibrarySources = [
"es2015.proxy.d.ts",
"es2015.reflect.d.ts",
"es2015.symbol.d.ts",
"es2015.symbol.wellknown.d.ts",
"es2015.symbol.wellknown.d.ts"
];
var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
@@ -183,25 +183,25 @@ var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
var es2016LibrarySource = [ "es2016.array.include.d.ts" ];
var es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
});
var es2017LibrarySource = ["es2017.object.d.ts"];
var es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
});
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"];
var librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"], },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"], },
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
@@ -209,8 +209,8 @@ var librarySourceMap = [
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] },
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources), },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts"), },
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
@@ -251,7 +251,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = true;
var host = (process.env.TYPESCRIPT_HOST || process.env.host || "node");
var host = process.env.TYPESCRIPT_HOST || process.env.host || "node";
var compilerFilename = "tsc.js";
var LKGCompiler = path.join(LKGDirectory, compilerFilename);
var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
@@ -300,7 +300,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
options += " --out " + outFile;
}
else {
options += " --module commonjs"
options += " --module commonjs";
}
if(opts.noResolve) {
@@ -315,7 +315,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
}
if (opts.stripInternal) {
options += " --stripInternal"
options += " --stripInternal";
}
var cmd = host + " " + compilerPath + " " + options + " ";
@@ -453,9 +453,9 @@ file(scriptsTsdJson);
task("tsd-scripts", [scriptsTsdJson], function () {
var cmd = "tsd --config " + scriptsTsdJson + " install";
console.log(cmd)
console.log(cmd);
exec(cmd);
}, { async: true })
}, { async: true });
var importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests");
var importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js");
@@ -525,9 +525,10 @@ compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, cop
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
var lsslFile = path.join(builtLocalDirectory, "tslssl.js");
var tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
compileFile(
lsslFile,
tsserverLibraryFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
@@ -536,7 +537,7 @@ compileFile(
// Local target to build the language service server library
desc("Builds language service server library");
task("lssl", [lsslFile]);
task("lssl", [tsserverLibraryFile, tsserverLibraryDefinitionFile]);
// Local target to build the compiler and services
desc("Builds the full compiler and services");
@@ -595,8 +596,8 @@ 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
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile].concat(libraryTargets);
task("LKG", ["clean", "release", "local", "lssl"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
});
@@ -622,7 +623,7 @@ directory(builtLocalDirectory);
var run = path.join(builtLocalDirectory, "run.js");
compileFile(run, harnessSources, [builtLocalDirectory, tscFile].concat(libraryTargets).concat(harnessSources), [], /*useBuiltCompiler:*/ true);
var internalTests = "internal/"
var internalTests = "internal/";
var localBaseline = "tests/baselines/local/";
var refBaseline = "tests/baselines/reference/";
@@ -709,15 +710,16 @@ function runConsoleTests(defaultReporter, defaultSubsets) {
testTimeout = 100000;
}
colors = process.env.colors || process.env.color
colors = process.env.colors || process.env.color;
colors = colors ? ' --no-colors ' : ' --colors ';
reporter = process.env.reporter || process.env.r || defaultReporter;
var lintFlag = process.env.lint !== 'false';
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
var subsetRegexes;
if(defaultSubsets.length === 0) {
subsetRegexes = [tests]
subsetRegexes = [tests];
}
else {
var subsets = tests ? tests.split("|") : defaultSubsets;
@@ -728,19 +730,20 @@ function runConsoleTests(defaultReporter, defaultSubsets) {
tests = subsetRegex ? ' -g "' + subsetRegex + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd, function () {
function finish() {
deleteTemporaryProjectOutput();
if (i === 0) {
complete();
}
exec(cmd, function () {
if (lintFlag && i === 0) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
complete();
});
lint.invoke();
}
else {
complete();
}
});
finish();
}, finish);
});
}
@@ -750,7 +753,7 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
runConsoleTests('min', ['compiler', 'conformance', 'Projects', 'fourslash']);
}, {async: true});
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false.");
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false lint=true.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', []);
}, {async: true});
@@ -763,8 +766,8 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
}, { async: true });
// Browser tests
var nodeServerOutFile = 'tests/webTestServer.js'
var nodeServerInFile = 'tests/webTestServer.ts'
var nodeServerOutFile = "tests/webTestServer.js";
var nodeServerInFile = "tests/webTestServer.ts";
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
@@ -776,7 +779,7 @@ task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function()
desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]");
task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() {
cleanTestDirs();
host = "node"
host = "node";
port = process.env.port || process.env.p || '8888';
browser = process.env.browser || process.env.b || "IE";
tests = process.env.test || process.env.tests || process.env.t;
@@ -790,13 +793,13 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFi
}
tests = tests ? tests : '';
var cmd = host + " tests/webTestServer.js " + port + " " + browser + " " + tests
var cmd = host + " tests/webTestServer.js " + port + " " + browser + " " + tests;
console.log(cmd);
exec(cmd);
}, {async: true});
function getDiffTool() {
var program = process.env['DIFF']
var program = process.env['DIFF'];
if (!program) {
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
@@ -825,11 +828,11 @@ task("tests-debug", ["setDebugMode", "tests"]);
// Makes the test results the new baseline
desc("Makes the most recent test results the new baseline, overwriting the old baseline");
task("baseline-accept", function(hardOrSoft) {
if (!hardOrSoft || hardOrSoft == "hard") {
if (!hardOrSoft || hardOrSoft === "hard") {
jake.rmRf(refBaseline);
fs.renameSync(localBaseline, refBaseline);
}
else if (hardOrSoft == "soft") {
else if (hardOrSoft === "soft") {
var files = jake.readdirR(localBaseline);
for (var i in files) {
jake.cpR(files[i], refBaseline);
@@ -908,14 +911,14 @@ task("update-sublime", ["local", serverFile], function() {
});
var tslintRuleDir = "scripts/tslint";
var tslintRules = ([
var tslintRules = [
"nextLineRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule",
"noInOperatorRule",
"noIncrementDecrementRule"
]);
];
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
});
@@ -940,7 +943,7 @@ function getLinterOptions() {
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
console.log("Linting '" + path + "'.")
console.log("Linting '" + path + "'.");
return ll.lint();
}
@@ -961,6 +964,7 @@ function lintFileAsync(options, path, cb) {
var servicesLintTargets = [
"navigateTo.ts",
"navigationBar.ts",
"outliningElementsCollector.ts",
"patternMatcher.ts",
"services.ts",
@@ -971,19 +975,26 @@ var servicesLintTargets = [
});
var lintTargets = compilerSources
.concat(harnessCoreSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f) }))
.concat(serverCoreSources)
.concat(["client.ts"].map(function(f) { return path.join(serverDirectory, f); }))
.concat(tslintRulesFiles)
.concat(servicesLintTargets);
desc("Runs tslint on the compiler sources");
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
var failed = 0;
var fileMatcher = RegExp(process.env.f || process.env.file || process.env.files || "");
for (var i in lintTargets) {
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
var target = lintTargets[i];
if (fileMatcher.test(target)) {
var result = lintFile(lintOptions, target);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
}
}
}
if (failed > 0) {
+1283 -1285
View File
File diff suppressed because it is too large Load Diff
+477 -479
View File
File diff suppressed because it is too large Load Diff
+8 -17
View File
@@ -20,13 +20,13 @@ interface Map<K, V> {
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
set(key: K, value?: V): this;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(entries?: [K, V][]): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
@@ -36,51 +36,42 @@ interface WeakMap<K, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
set(key: K, value?: V): this;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
new <T>(values?: T[]): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
new <T>(values?: T[]): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
+80 -67
View File
@@ -17,48 +17,48 @@ and limitations under the License.
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
fill(value: T, start?: number, end?: number): this;
/**
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
copyWithin(target: number, start: number, end?: number): this;
}
interface ArrayConstructor {
@@ -130,7 +130,7 @@ interface Math {
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
@@ -206,14 +206,14 @@ interface Math {
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 10‍‍16.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -226,7 +226,7 @@ interface NumberConstructor {
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
@@ -239,30 +239,30 @@ interface NumberConstructor {
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
@@ -271,12 +271,12 @@ interface NumberConstructor {
interface Object {
/**
* Determines whether an object has a property with the specified name.
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
@@ -285,7 +285,7 @@ interface Object {
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
@@ -293,7 +293,7 @@ interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -302,7 +302,7 @@ interface ObjectConstructor {
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -312,7 +312,7 @@ interface ObjectConstructor {
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
@@ -340,17 +340,17 @@ interface ObjectConstructor {
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
@@ -374,47 +374,60 @@ interface RegExp {
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp, flags?: string): RegExp;
(pattern: RegExp, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
@@ -422,15 +435,15 @@ interface String {
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
@@ -490,10 +503,10 @@ interface StringConstructor {
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
}
+55 -3
View File
@@ -16,9 +16,17 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
}
interface IteratorResult<T> {
done: boolean;
value?: T;
value: T;
}
interface Iterator<T> {
@@ -27,11 +35,18 @@ interface Iterator<T> {
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> { }
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -64,7 +79,13 @@ interface ArrayConstructor {
from<T>(iterable: Iterable<T>): Array<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Map<K, V> {
[Symbol.iterator](): IterableIterator<[K,V]>;
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
@@ -80,6 +101,23 @@ interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Set<T> {
[Symbol.iterator](): IterableIterator<T>;
entries(): IterableIterator<[T, T]>;
keys(): IterableIterator<T>;
values(): IterableIterator<T>;
}
interface SetConstructor {
new <T>(iterable: Iterable<T>): Set<T>;
}
interface WeakSet<T> { }
interface WeakSetConstructor {
new <T>(iterable: Iterable<T>): WeakSet<T>;
}
interface Promise<T> { }
interface PromiseConstructor {
@@ -104,11 +142,17 @@ declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -140,6 +184,7 @@ interface Int8ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -171,6 +216,7 @@ interface Uint8ArrayConstructor {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -205,6 +251,7 @@ interface Uint8ClampedArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -238,6 +285,7 @@ interface Int16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -269,6 +317,7 @@ interface Uint16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -300,6 +349,7 @@ interface Int32ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -331,6 +381,7 @@ interface Uint32ArrayConstructor {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -362,6 +413,7 @@ interface Float32ArrayConstructor {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
+8 -37
View File
@@ -29,12 +29,6 @@ interface SymbolConstructor {
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
@@ -89,9 +83,6 @@ interface Symbol {
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
@@ -132,7 +123,6 @@ interface Date {
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
@@ -140,6 +130,14 @@ interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface Set<T> {
readonly [Symbol.toStringTag]: "Set";
}
interface WeakSet<T> {
readonly [Symbol.toStringTag]: "WeakSet";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
@@ -159,21 +157,6 @@ interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
@@ -239,9 +222,6 @@ interface RegExpConstructor {
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
@@ -295,7 +275,6 @@ interface DataView {
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
@@ -304,7 +283,6 @@ interface Int8Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
@@ -313,7 +291,6 @@ interface Uint8Array {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
@@ -322,7 +299,6 @@ interface Uint8ClampedArray {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
@@ -331,7 +307,6 @@ interface Int16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
@@ -340,7 +315,6 @@ interface Uint16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
@@ -349,7 +323,6 @@ interface Int32Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
@@ -358,7 +331,6 @@ interface Uint32Array {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
@@ -367,6 +339,5 @@ interface Float32Array {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
+18
View File
@@ -0,0 +1,18 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
+30
View File
@@ -0,0 +1,30 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
entries(o: any): [string, any][];
}
+806 -806
View File
File diff suppressed because it is too large Load Diff
+1449 -1410
View File
File diff suppressed because it is too large Load Diff
+294
View File
@@ -0,0 +1,294 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// Windows Script Host APIS
/////////////////////////////
interface ActiveXObject {
new (s: string): any;
}
declare var ActiveXObject: ActiveXObject;
interface ITextWriter {
Write(s: string): void;
WriteLine(s: string): void;
Close(): void;
}
interface TextStreamBase {
/**
* The column number of the current character position in an input stream.
*/
Column: number;
/**
* The current line number in an input stream.
*/
Line: number;
/**
* Closes a text stream.
* It is not necessary to close standard streams; they close automatically when the process ends. If
* you close a standard stream, be aware that any other pointers to that standard stream become invalid.
*/
Close(): void;
}
interface TextStreamWriter extends TextStreamBase {
/**
* Sends a string to an output stream.
*/
Write(s: string): void;
/**
* Sends a specified number of blank lines (newline characters) to an output stream.
*/
WriteBlankLines(intLines: number): void;
/**
* Sends a string followed by a newline character to an output stream.
*/
WriteLine(s: string): void;
}
interface TextStreamReader extends TextStreamBase {
/**
* Returns a specified number of characters from an input stream, starting at the current pointer position.
* Does not return until the ENTER key is pressed.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
Read(characters: number): string;
/**
* Returns all characters from an input stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadAll(): string;
/**
* Returns an entire line from an input stream.
* Although this method extracts the newline character, it does not add it to the returned string.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
*/
ReadLine(): string;
/**
* Skips a specified number of characters when reading from an input text stream.
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
* @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)
*/
Skip(characters: number): void;
/**
* Skips the next line when reading from an input text stream.
* Can only be used on a stream in reading mode, not writing or appending mode.
*/
SkipLine(): void;
/**
* Indicates whether the stream pointer position is at the end of a line.
*/
AtEndOfLine: boolean;
/**
* Indicates whether the stream pointer position is at the end of a stream.
*/
AtEndOfStream: boolean;
}
declare var WScript: {
/**
* Outputs text to either a message box (under WScript.exe) or the command console window followed by
* a newline (under CScript.exe).
*/
Echo(s: any): void;
/**
* Exposes the write-only error output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdErr: TextStreamWriter;
/**
* Exposes the write-only output stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdOut: TextStreamWriter;
Arguments: { length: number; Item(n: number): string; };
/**
* The full path of the currently running script.
*/
ScriptFullName: string;
/**
* Forces the script to stop immediately, with an optional exit code.
*/
Quit(exitCode?: number): number;
/**
* The Windows Script Host build version number.
*/
BuildVersion: number;
/**
* Fully qualified path of the host executable.
*/
FullName: string;
/**
* Gets/sets the script mode - interactive(true) or batch(false).
*/
Interactive: boolean;
/**
* The name of the host executable (WScript.exe or CScript.exe).
*/
Name: string;
/**
* Path of the directory containing the host executable.
*/
Path: string;
/**
* The filename of the currently running script.
*/
ScriptName: string;
/**
* Exposes the read-only input stream for the current script.
* Can be accessed only while using CScript.exe.
*/
StdIn: TextStreamReader;
/**
* Windows Script Host version
*/
Version: string;
/**
* Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.
*/
ConnectObject(objEventSource: any, strPrefix: string): void;
/**
* Creates a COM object.
* @param strProgiID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
CreateObject(strProgID: string, strPrefix?: string): any;
/**
* Disconnects a COM object from its event sources.
*/
DisconnectObject(obj: any): void;
/**
* Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.
* @param strPathname Fully qualified path to the file containing the object persisted to disk.
* For objects in memory, pass a zero-length string.
* @param strProgID
* @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.
*/
GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;
/**
* Suspends script execution for a specified length of time, then continues execution.
* @param intTime Interval (in milliseconds) to suspend script execution.
*/
Sleep(intTime: number): void;
};
/**
* Allows enumerating over a COM collection, which may not have indexed item access.
*/
interface Enumerator<T> {
/**
* Returns true if the current item is the last one in the collection, or the collection is empty,
* or the current item is undefined.
*/
atEnd(): boolean;
/**
* Returns the current item in the collection
*/
item(): T;
/**
* Resets the current item in the collection to the first item. If there are no items in the collection,
* the current item is set to undefined.
*/
moveFirst(): void;
/**
* Moves the current item to the next item in the collection. If the enumerator is at the end of
* the collection or the collection is empty, the current item is set to undefined.
*/
moveNext(): void;
}
interface EnumeratorConstructor {
new <T>(collection: any): Enumerator<T>;
new (collection: any): Enumerator<any>;
}
declare var Enumerator: EnumeratorConstructor;
/**
* Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.
*/
interface VBArray<T> {
/**
* Returns the number of dimensions (1-based).
*/
dimensions(): number;
/**
* Takes an index for each dimension in the array, and returns the item at the corresponding location.
*/
getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;
/**
* Returns the smallest available index for a given dimension.
* @param dimension 1-based dimension (defaults to 1)
*/
lbound(dimension?: number): number;
/**
* Returns the largest available index for a given dimension.
* @param dimension 1-based dimension (defaults to 1)
*/
ubound(dimension?: number): number;
/**
* Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,
* each successive dimension is appended to the end of the array.
* Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]
*/
toArray(): T[];
}
interface VBArrayConstructor {
new <T>(safeArray: any): VBArray<T>;
new (safeArray: any): VBArray<any>;
}
declare var VBArray: VBArrayConstructor;
+18 -7
View File
@@ -24,6 +24,16 @@ interface EventInit {
cancelable?: boolean;
}
interface IDBIndexParameters {
multiEntry?: boolean;
unique?: boolean;
}
interface IDBObjectStoreParameters {
autoIncrement?: boolean;
keyPath?: IDBKeyPath;
}
interface EventListener {
(evt: Event): void;
}
@@ -100,12 +110,12 @@ declare var Console: {
interface Coordinates {
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly altitude: number | null;
readonly altitudeAccuracy: number | null;
readonly heading: number | null;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
readonly speed: number | null;
}
declare var Coordinates: {
@@ -192,7 +202,7 @@ declare var DOMException: {
interface DOMStringList {
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
item(index: number): string | null;
[index: number]: string;
}
@@ -475,7 +485,7 @@ declare var IDBTransaction: {
}
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number;
readonly newVersion: number | null;
readonly oldVersion: number;
}
@@ -728,7 +738,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string;
getResponseHeader(header: string): string | null;
msCachingEnabled(): boolean;
open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
overrideMimeType(mime: string): void;
@@ -1007,4 +1017,5 @@ declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBKeyPath = string;
type IDBValidKey = number | string | Date | IDBArrayKey;
+4304 -3482
View File
File diff suppressed because it is too large Load Diff
+5897 -4657
View File
File diff suppressed because it is too large Load Diff
+8618
View File
File diff suppressed because it is too large Load Diff
+51467
View File
File diff suppressed because one or more lines are too long
+216 -165
View File
@@ -160,173 +160,174 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
StringLiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
GlobalModuleExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
SyntaxList = 279,
Count = 280,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 137,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 137,
LastToken = 138,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -335,7 +336,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 138,
FirstNode = 139,
}
enum NodeFlags {
None = 0,
@@ -370,8 +371,9 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
Modifier = 1023,
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
@@ -405,9 +407,6 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -1047,6 +1046,34 @@ declare namespace ts {
postParameterName?: Identifier;
isBracketed: boolean;
}
enum FlowFlags {
Unreachable = 1,
Start = 2,
BranchLabel = 4,
LoopLabel = 8,
Assignment = 16,
TrueCondition = 32,
FalseCondition = 64,
Referenced = 128,
Shared = 256,
Label = 12,
Condition = 96,
}
interface FlowNode {
flags: FlowFlags;
id?: number;
}
interface FlowLabel extends FlowNode {
antecedents: FlowNode[];
}
interface FlowAssignment extends FlowNode {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
interface FlowCondition extends FlowNode {
expression: Expression;
antecedent: FlowNode;
}
interface AmdDependency {
path: string;
name: string;
@@ -1077,6 +1104,7 @@ declare namespace ts {
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile;
getSourceFileByPath(path: Path): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
@@ -1169,11 +1197,13 @@ declare namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@@ -1233,6 +1263,7 @@ declare namespace ts {
WriteTypeArgumentsOfSignature = 32,
InElementType = 64,
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
}
enum SymbolFormatFlags {
None = 0,
@@ -1356,11 +1387,13 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
Never = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
Narrowable = 97793,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1525,13 +1558,13 @@ declare namespace ts {
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
[option: string]: CompilerOptionsValue | undefined;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
[option: string]: string[] | boolean | undefined;
}
interface DiscoverTypingsInfo {
fileNames: string[];
@@ -1585,6 +1618,7 @@ declare namespace ts {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
}
interface ModuleResolutionHost {
@@ -1592,6 +1626,7 @@ declare namespace ts {
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
@@ -1611,6 +1646,7 @@ declare namespace ts {
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
@@ -1637,6 +1673,11 @@ declare namespace ts {
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
interface System {
args: string[];
newLine: string;
@@ -1657,6 +1698,7 @@ declare namespace ts {
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
}
interface FileWatcher {
close(): void;
@@ -1843,6 +1885,7 @@ declare namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1898,7 +1941,7 @@ declare namespace ts {
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -1951,6 +1994,7 @@ declare namespace ts {
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -2266,6 +2310,7 @@ declare namespace ts {
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2279,6 +2324,8 @@ declare namespace ts {
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2289,8 +2336,12 @@ declare namespace ts {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
}
type DocumentRegistryBucketKey = string & {
__bucketKey: any;
};
namespace ScriptElementKind {
const unknown: string;
const warning: string;
+6353 -5102
View File
File diff suppressed because it is too large Load Diff
+216 -165
View File
@@ -160,173 +160,174 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
StringLiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
GlobalModuleExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
SyntaxList = 279,
Count = 280,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 137,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 137,
LastToken = 138,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -335,7 +336,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 138,
FirstNode = 139,
}
enum NodeFlags {
None = 0,
@@ -370,8 +371,9 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
Modifier = 1023,
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
@@ -405,9 +407,6 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -1047,6 +1046,34 @@ declare namespace ts {
postParameterName?: Identifier;
isBracketed: boolean;
}
enum FlowFlags {
Unreachable = 1,
Start = 2,
BranchLabel = 4,
LoopLabel = 8,
Assignment = 16,
TrueCondition = 32,
FalseCondition = 64,
Referenced = 128,
Shared = 256,
Label = 12,
Condition = 96,
}
interface FlowNode {
flags: FlowFlags;
id?: number;
}
interface FlowLabel extends FlowNode {
antecedents: FlowNode[];
}
interface FlowAssignment extends FlowNode {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
interface FlowCondition extends FlowNode {
expression: Expression;
antecedent: FlowNode;
}
interface AmdDependency {
path: string;
name: string;
@@ -1077,6 +1104,7 @@ declare namespace ts {
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile;
getSourceFileByPath(path: Path): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
@@ -1169,11 +1197,13 @@ declare namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@@ -1233,6 +1263,7 @@ declare namespace ts {
WriteTypeArgumentsOfSignature = 32,
InElementType = 64,
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
}
enum SymbolFormatFlags {
None = 0,
@@ -1356,11 +1387,13 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
Never = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
Narrowable = 97793,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1525,13 +1558,13 @@ declare namespace ts {
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
[option: string]: CompilerOptionsValue | undefined;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
[option: string]: string[] | boolean | undefined;
}
interface DiscoverTypingsInfo {
fileNames: string[];
@@ -1585,6 +1618,7 @@ declare namespace ts {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
}
interface ModuleResolutionHost {
@@ -1592,6 +1626,7 @@ declare namespace ts {
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
@@ -1611,6 +1646,7 @@ declare namespace ts {
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
@@ -1637,6 +1673,11 @@ declare namespace ts {
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
interface System {
args: string[];
newLine: string;
@@ -1657,6 +1698,7 @@ declare namespace ts {
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
}
interface FileWatcher {
close(): void;
@@ -1843,6 +1885,7 @@ declare namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1898,7 +1941,7 @@ declare namespace ts {
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -1951,6 +1994,7 @@ declare namespace ts {
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -2266,6 +2310,7 @@ declare namespace ts {
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2279,6 +2324,8 @@ declare namespace ts {
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2289,8 +2336,12 @@ declare namespace ts {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
}
type DocumentRegistryBucketKey = string & {
__bucketKey: any;
};
namespace ScriptElementKind {
const unknown: string;
const warning: string;
+6353 -5102
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -67,7 +67,7 @@ function getNightlyVersionString(versionString: string): string {
const now = new Date();
const timeStr = now.toISOString().replace(/:|T|\.|-/g, "").slice(0, 8);
return `${versionString}-dev.${timeStr}`;
return `${versionString}-dev.${timeStr}-1.0`;
}
main();
+3 -3
View File
@@ -1764,8 +1764,8 @@ namespace ts {
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
case SyntaxKind.GlobalModuleExportDeclaration:
return bindGlobalModuleExportDeclaration(<GlobalModuleExportDeclaration>node);
case SyntaxKind.NamespaceExportDeclaration:
return bindNamespaceExportDeclaration(<NamespaceExportDeclaration>node);
case SyntaxKind.ImportClause:
return bindImportClause(<ImportClause>node);
case SyntaxKind.ExportDeclaration:
@@ -1815,7 +1815,7 @@ namespace ts {
}
}
function bindGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration) {
function bindNamespaceExportDeclaration(node: NamespaceExportDeclaration) {
if (node.modifiers && node.modifiers.length) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here));
}
+297 -225
View File
@@ -79,6 +79,7 @@ namespace ts {
getIndexTypeOfType,
getBaseTypes,
getReturnTypeOfSignature,
getNonNullableType,
getSymbolsInScope,
getSymbolAtLocation,
getShorthandAssignmentValueSymbol,
@@ -120,9 +121,9 @@ namespace ts {
const nullType = createIntrinsicType(TypeFlags.Null | nullableWideningFlags, "null");
const emptyArrayElementType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined");
const unknownType = createIntrinsicType(TypeFlags.Any, "unknown");
const neverType = createIntrinsicType(TypeFlags.Never, "never");
const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
const nothingType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
const emptyGenericType = <GenericType><ObjectType>createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
emptyGenericType.instantiations = {};
@@ -638,6 +639,7 @@ namespace ts {
let propertyWithInvalidInitializer: Node;
const errorLocation = location;
let grandparent: Node;
let isInExternalModule = false;
loop: while (location) {
// Locals of a source file are not in scope (because they get merged into the global symbol table)
@@ -685,6 +687,7 @@ namespace ts {
switch (location.kind) {
case SyntaxKind.SourceFile:
if (!isExternalOrCommonJsModule(<SourceFile>location)) break;
isInExternalModule = true;
case SyntaxKind.ModuleDeclaration:
const moduleExports = getSymbolOfNode(location).exports;
if (location.kind === SyntaxKind.SourceFile || isAmbientModule(location)) {
@@ -878,6 +881,14 @@ namespace ts {
checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
}
}
// If we're in an external module, we can't reference symbols created from UMD export declarations
if (result && isInExternalModule) {
const decls = result.declarations;
if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) {
error(errorLocation, Diagnostics.Identifier_0_must_be_imported_from_a_module, name);
}
}
}
return result;
}
@@ -1075,7 +1086,7 @@ namespace ts {
return getExternalModuleMember(<ImportDeclaration>node.parent.parent.parent, node);
}
function getTargetOfGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration): Symbol {
function getTargetOfGlobalModuleExportDeclaration(node: NamespaceExportDeclaration): Symbol {
return resolveExternalModuleSymbol(node.parent.symbol);
}
@@ -1103,8 +1114,8 @@ namespace ts {
return getTargetOfExportSpecifier(<ExportSpecifier>node);
case SyntaxKind.ExportAssignment:
return getTargetOfExportAssignment(<ExportAssignment>node);
case SyntaxKind.GlobalModuleExportDeclaration:
return getTargetOfGlobalModuleExportDeclaration(<GlobalModuleExportDeclaration>node);
case SyntaxKind.NamespaceExportDeclaration:
return getTargetOfGlobalModuleExportDeclaration(<NamespaceExportDeclaration>node);
}
}
@@ -2029,12 +2040,7 @@ namespace ts {
writeUnionOrIntersectionType(<UnionOrIntersectionType>type, flags);
}
else if (type.flags & TypeFlags.Anonymous) {
if (type === nothingType) {
writer.writeKeyword("nothing");
}
else {
writeAnonymousType(<ObjectType>type, flags);
}
writeAnonymousType(<ObjectType>type, flags);
}
else if (type.flags & TypeFlags.StringLiteral) {
writer.writeStringLiteral(`"${escapeString((<StringLiteralType>type).text)}"`);
@@ -2749,7 +2755,7 @@ namespace ts {
// assigned by contextual typing.
function getTypeForBindingElementParent(node: VariableLikeDeclaration) {
const symbol = getSymbolOfNode(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
}
function getTextOfPropertyName(name: PropertyName): string {
@@ -2884,8 +2890,12 @@ namespace ts {
return undefined;
}
function addOptionality(type: Type, optional: boolean): Type {
return strictNullChecks && optional ? addNullableKind(type, TypeFlags.Undefined) : type;
}
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration): Type {
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type {
if (declaration.flags & NodeFlags.JavaScriptFile) {
// If this is a variable in a JavaScript file, then use the JSDoc type (if it has
// one as its type), otherwise fallback to the below standard TS codepaths to
@@ -2915,8 +2925,7 @@ namespace ts {
// Use type from type annotation if one is present
if (declaration.type) {
const type = getTypeFromTypeNode(declaration.type);
return strictNullChecks && declaration.questionToken ? addNullableKind(type, TypeFlags.Undefined) : type;
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
}
if (declaration.kind === SyntaxKind.Parameter) {
@@ -2938,13 +2947,13 @@ namespace ts {
? getContextuallyTypedThisType(func)
: getContextuallyTypedParameterType(<ParameterDeclaration>declaration);
if (type) {
return strictNullChecks && declaration.questionToken ? addNullableKind(type, TypeFlags.Undefined) : type;
return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality);
}
}
// Use the type of the initializer expression if one is present
if (declaration.initializer) {
return checkExpressionCached(declaration.initializer);
return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality);
}
// If it is a short-hand property assignment, use the type of the identifier
@@ -3047,7 +3056,7 @@ namespace ts {
// binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
// tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
function getWidenedTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, reportErrors?: boolean): Type {
let type = getTypeForVariableLikeDeclaration(declaration);
let type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
if (type) {
if (reportErrors) {
reportErrorsFromWidening(declaration, type);
@@ -3215,7 +3224,9 @@ namespace ts {
function getTypeOfFuncClassEnumModule(symbol: Symbol): Type {
const links = getSymbolLinks(symbol);
if (!links.type) {
links.type = createObjectType(TypeFlags.Anonymous, symbol);
const type = createObjectType(TypeFlags.Anonymous, symbol);
links.type = strictNullChecks && symbol.flags & SymbolFlags.Optional ?
addNullableKind(type, TypeFlags.Undefined) : type;
}
return links.type;
}
@@ -3670,6 +3681,7 @@ namespace ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.StringLiteralType:
return true;
case SyntaxKind.ArrayType:
@@ -4577,12 +4589,7 @@ namespace ts {
function getErasedSignature(signature: Signature): Signature {
if (!signature.typeParameters) return signature;
if (!signature.erasedSignatureCache) {
if (signature.target) {
signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper);
}
else {
signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
}
signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
}
return signature.erasedSignatureCache;
}
@@ -5005,7 +5012,7 @@ namespace ts {
if (type.flags & TypeFlags.Undefined) typeSet.containsUndefined = true;
if (type.flags & TypeFlags.Null) typeSet.containsNull = true;
}
else if (type !== nothingType && !contains(typeSet, type)) {
else if (type !== neverType && !contains(typeSet, type)) {
typeSet.push(type);
}
}
@@ -5046,7 +5053,7 @@ namespace ts {
// a named type that circularly references itself.
function getUnionType(types: Type[], noSubtypeReduction?: boolean): Type {
if (types.length === 0) {
return nothingType;
return neverType;
}
if (types.length === 1) {
return types[0];
@@ -5066,7 +5073,7 @@ namespace ts {
if (typeSet.length === 0) {
return typeSet.containsNull ? nullType :
typeSet.containsUndefined ? undefinedType :
nothingType;
neverType;
}
else if (typeSet.length === 1) {
return typeSet[0];
@@ -5150,7 +5157,7 @@ namespace ts {
function getTypeFromStringLiteralTypeNode(node: StringLiteralTypeNode): Type {
const links = getNodeLinks(node);
if (!links.resolvedType) {
links.resolvedType = getStringLiteralTypeForText(node.text);
links.resolvedType = getStringLiteralTypeForText(unescapeIdentifier(node.text));
}
return links.resolvedType;
}
@@ -5214,6 +5221,8 @@ namespace ts {
return undefinedType;
case SyntaxKind.NullKeyword:
return nullType;
case SyntaxKind.NeverKeyword:
return neverType;
case SyntaxKind.ThisType:
case SyntaxKind.ThisKeyword:
return getTypeFromThisTypeNode(node);
@@ -5460,7 +5469,7 @@ namespace ts {
const declaration = <DeclarationWithTypeParameters>node;
if (declaration.typeParameters) {
for (const d of declaration.typeParameters) {
if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(d.symbol))) {
if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) {
return true;
}
}
@@ -5859,28 +5868,28 @@ namespace ts {
return isIdenticalTo(source, target);
}
if (target.flags & TypeFlags.Any) return Ternary.True;
if (source.flags & TypeFlags.Undefined) {
if (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void) || source === emptyArrayElementType) return Ternary.True;
}
if (source.flags & TypeFlags.Null) {
if (!strictNullChecks || target.flags & TypeFlags.Null) return Ternary.True;
}
if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True;
if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) {
if (result = enumRelatedTo(source, target, reportErrors)) {
return result;
if (!(target.flags & TypeFlags.Never)) {
if (target.flags & TypeFlags.Any || source.flags & TypeFlags.Never) return Ternary.True;
if (source.flags & TypeFlags.Undefined) {
if (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void) || source === emptyArrayElementType) return Ternary.True;
}
if (source.flags & TypeFlags.Null) {
if (!strictNullChecks || target.flags & TypeFlags.Null) return Ternary.True;
}
if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True;
if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) {
if (result = enumRelatedTo(source, target, reportErrors)) {
return result;
}
}
if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True;
if (relation === assignableRelation || relation === comparableRelation) {
if (source.flags & TypeFlags.Any) return Ternary.True;
if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True;
}
if (source.flags & TypeFlags.Boolean && target.flags & TypeFlags.Boolean) {
return Ternary.True;
}
}
if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True;
if (relation === assignableRelation || relation === comparableRelation) {
if (isTypeAny(source)) return Ternary.True;
if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True;
}
if (source.flags & TypeFlags.Boolean && target.flags & TypeFlags.Boolean) {
return Ternary.True;
}
if (source.flags & TypeFlags.FreshObjectLiteral) {
@@ -6026,7 +6035,7 @@ namespace ts {
if (type.flags & TypeFlags.ObjectType) {
const resolved = resolveStructuredTypeMembers(type);
if ((relation === assignableRelation || relation === comparableRelation) &&
(type === globalObjectType || resolved.properties.length === 0) ||
(type === globalObjectType || isEmptyObjectType(resolved)) ||
resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) {
return true;
}
@@ -6041,6 +6050,14 @@ namespace ts {
return false;
}
function isEmptyObjectType(t: ResolvedType) {
return t.properties.length === 0 &&
t.callSignatures.length === 0 &&
t.constructSignatures.length === 0 &&
!t.stringIndexInfo &&
!t.numberIndexInfo;
}
function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean {
if (!(target.flags & TypeFlags.ObjectLiteralPatternWithComputedProperties) && maybeTypeOfKind(target, TypeFlags.ObjectType)) {
for (const prop of getPropertiesOfObjectType(source)) {
@@ -6367,7 +6384,7 @@ namespace ts {
if (kind === SignatureKind.Construct && sourceSignatures.length && targetSignatures.length) {
if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) {
// An abstract constructor type is not assignable to a non-abstract constructor type
// as it would otherwise be possible to new an abstract class. Note that the assignability
// as it would otherwise be possible to new an abstract class. Note that the assignability
// check we perform for an extends clause excludes construct signatures from the target,
// so this check never proceeds.
if (reportErrors) {
@@ -6824,41 +6841,59 @@ namespace ts {
getSignaturesOfType(type, SignatureKind.Construct).length === 0;
}
function createTransientSymbol(source: Symbol, type: Type) {
const symbol = <TransientSymbol>createSymbol(source.flags | SymbolFlags.Transient, source.name);
symbol.declarations = source.declarations;
symbol.parent = source.parent;
symbol.type = type;
symbol.target = source;
if (source.valueDeclaration) {
symbol.valueDeclaration = source.valueDeclaration;
}
return symbol;
}
function transformTypeOfMembers(type: Type, f: (propertyType: Type) => Type) {
const members: SymbolTable = {};
for (const property of getPropertiesOfObjectType(type)) {
const original = getTypeOfSymbol(property);
const updated = f(original);
members[property.name] = updated === original ? property : createTransientSymbol(property, updated);
};
return members;
}
/**
* If the the provided object literal is subject to the excess properties check,
* create a new that is exempt. Recursively mark object literal members as exempt.
* Leave signatures alone since they are not subject to the check.
*/
function getRegularTypeOfObjectLiteral(type: Type): Type {
if (type.flags & TypeFlags.FreshObjectLiteral) {
let regularType = (<FreshObjectLiteralType>type).regularType;
if (!regularType) {
regularType = <ResolvedType>createType((<ResolvedType>type).flags & ~TypeFlags.FreshObjectLiteral);
regularType.symbol = (<ResolvedType>type).symbol;
regularType.members = (<ResolvedType>type).members;
regularType.properties = (<ResolvedType>type).properties;
regularType.callSignatures = (<ResolvedType>type).callSignatures;
regularType.constructSignatures = (<ResolvedType>type).constructSignatures;
regularType.stringIndexInfo = (<ResolvedType>type).stringIndexInfo;
regularType.numberIndexInfo = (<ResolvedType>type).numberIndexInfo;
(<FreshObjectLiteralType>type).regularType = regularType;
}
if (!(type.flags & TypeFlags.FreshObjectLiteral)) {
return type;
}
const regularType = (<FreshObjectLiteralType>type).regularType;
if (regularType) {
return regularType;
}
return type;
const resolved = <ResolvedType>type;
const members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
const regularNew = createAnonymousType(resolved.symbol,
members,
resolved.callSignatures,
resolved.constructSignatures,
resolved.stringIndexInfo,
resolved.numberIndexInfo);
regularNew.flags = resolved.flags & ~TypeFlags.FreshObjectLiteral;
(<FreshObjectLiteralType>type).regularType = regularNew;
return regularNew;
}
function getWidenedTypeOfObjectLiteral(type: Type): Type {
const properties = getPropertiesOfObjectType(type);
const members: SymbolTable = {};
forEach(properties, p => {
const propType = getTypeOfSymbol(p);
const widenedType = getWidenedType(propType);
if (propType !== widenedType) {
const symbol = <TransientSymbol>createSymbol(p.flags | SymbolFlags.Transient, p.name);
symbol.declarations = p.declarations;
symbol.parent = p.parent;
symbol.type = widenedType;
symbol.target = p;
if (p.valueDeclaration) symbol.valueDeclaration = p.valueDeclaration;
p = symbol;
}
members[p.name] = p;
const members = transformTypeOfMembers(type, prop => {
const widened = getWidenedType(prop);
return prop === widened ? prop : widened;
});
const stringIndexInfo = getIndexInfoOfType(type, IndexKind.String);
const numberIndexInfo = getIndexInfoOfType(type, IndexKind.Number);
@@ -7485,7 +7520,7 @@ namespace ts {
function getTypeWithFacts(type: Type, include: TypeFacts) {
if (!(type.flags & TypeFlags.Union)) {
return getTypeFacts(type) & include ? type : nothingType;
return getTypeFacts(type) & include ? type : neverType;
}
let firstType: Type;
let types: Type[];
@@ -7502,7 +7537,7 @@ namespace ts {
}
}
}
return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : nothingType;
return firstType ? types ? getUnionType(types, /*noSubtypeReduction*/ true) : firstType : neverType;
}
function getTypeWithDefault(type: Type, defaultExpression: Expression) {
@@ -7614,15 +7649,16 @@ namespace ts {
getInitialTypeOfBindingElement(<BindingElement>node);
}
function getFlowTypeOfReference(reference: Node, declaredType: Type, initialType: Type) {
function getFlowTypeOfReference(reference: Node, declaredType: Type, assumeInitialized: boolean) {
let key: string;
if (!reference.flowNode || declaredType === initialType && !(declaredType.flags & TypeFlags.Narrowable)) {
if (!reference.flowNode || assumeInitialized && !(declaredType.flags & TypeFlags.Narrowable)) {
return declaredType;
}
const initialType = assumeInitialized ? declaredType : addNullableKind(declaredType, TypeFlags.Undefined);
const visitedFlowStart = visitedFlowCount;
const result = getTypeAtFlowNode(reference.flowNode);
visitedFlowCount = visitedFlowStart;
if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull) === nothingType) {
if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull) === neverType) {
return declaredType;
}
return result;
@@ -7710,7 +7746,7 @@ namespace ts {
function getTypeAtFlowCondition(flow: FlowCondition) {
let type = getTypeAtFlowNode(flow.antecedent);
if (type !== nothingType) {
if (type !== neverType) {
// If we have an antecedent type (meaning we're reachable in some way), we first
// attempt to narrow the antecedent type. If that produces the nothing type, then
// we take the type guard as an indication that control could reach here in a
@@ -7720,7 +7756,7 @@ namespace ts {
// narrow that.
const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0;
type = narrowType(type, flow.expression, assumeTrue);
if (type === nothingType) {
if (type === neverType) {
type = narrowType(declaredType, flow.expression, assumeTrue);
}
}
@@ -7942,7 +7978,7 @@ namespace ts {
const targetType = type.flags & TypeFlags.TypeParameter ? getApparentType(type) : type;
return isTypeAssignableTo(candidate, targetType) ? candidate :
isTypeAssignableTo(type, candidate) ? type :
nothingType;
neverType;
}
function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type {
@@ -8092,11 +8128,11 @@ namespace ts {
return type;
}
const declaration = localOrExportSymbol.valueDeclaration;
const defaultsToDeclaredType = !strictNullChecks || type.flags & TypeFlags.Any || !declaration ||
const assumeInitialized = !strictNullChecks || (type.flags & TypeFlags.Any) !== 0 || !declaration ||
getRootDeclaration(declaration).kind === SyntaxKind.Parameter || isInAmbientContext(declaration) ||
getContainingFunctionOrModule(declaration) !== getContainingFunctionOrModule(node);
const flowType = getFlowTypeOfReference(node, type, defaultsToDeclaredType ? type : addNullableKind(type, TypeFlags.Undefined));
if (strictNullChecks && !(type.flags & TypeFlags.Any) && !(getNullableKind(type) & TypeFlags.Undefined) && getNullableKind(flowType) & TypeFlags.Undefined) {
const flowType = getFlowTypeOfReference(node, type, assumeInitialized);
if (!assumeInitialized && !(getNullableKind(type) & TypeFlags.Undefined) && getNullableKind(flowType) & TypeFlags.Undefined) {
error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
// Return the declared type to reduce follow-on errors
return type;
@@ -8344,7 +8380,7 @@ namespace ts {
if (isClassLike(container.parent)) {
const symbol = getSymbolOfNode(container.parent);
const type = container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (<InterfaceType>getDeclaredTypeOfSymbol(symbol)).thisType;
return getFlowTypeOfReference(node, type, type);
return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true);
}
if (isInJavaScriptFile(node)) {
@@ -8601,7 +8637,12 @@ namespace ts {
}
return createArrayType(getUnionType(restTypes));
}
return checkExpression(iife.arguments[indexOfParameter]);
const links = getNodeLinks(iife);
const cached = links.resolvedSignature;
links.resolvedSignature = anySignature;
const type = checkExpression(iife.arguments[indexOfParameter]);
links.resolvedSignature = cached;
return type;
}
}
const contextualSignature = getContextualSignature(func);
@@ -9504,20 +9545,18 @@ namespace ts {
* element is not a class element, or the class element type cannot be determined, returns 'undefined'.
* For example, in the element <MyClass>, the element instance type is `MyClass` (not `typeof MyClass`).
*/
function getJsxElementInstanceType(node: JsxOpeningLikeElement) {
const valueType = checkExpression(node.tagName);
function getJsxElementInstanceType(node: JsxOpeningLikeElement, valueType: Type) {
Debug.assert(!(valueType.flags & TypeFlags.Union));
if (isTypeAny(valueType)) {
// Short-circuit if the class tag is using an element type 'any'
return anyType;
}
// Resolve the signatures, preferring constructors
// Resolve the signatures, preferring constructor
let signatures = getSignaturesOfType(valueType, SignatureKind.Construct);
if (signatures.length === 0) {
// No construct signatures, try call signatures
signatures = getSignaturesOfType(valueType, SignatureKind.Call);
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));
@@ -9565,6 +9604,103 @@ namespace ts {
}
}
/**
* Given React element instance type and the class type, resolve the Jsx type
* Pass elemType to handle individual type in the union typed element type.
*/
function getResolvedJsxType(node: JsxOpeningLikeElement, elemType?: Type, elemClassType?: Type): Type {
if (!elemType) {
elemType = checkExpression(node.tagName);
}
if (elemType.flags & TypeFlags.Union) {
const types = (<UnionOrIntersectionType> elemType).types;
return getUnionType(types.map(type => {
return getResolvedJsxType(node, type, elemClassType);
}));
}
// Get the element instance type (the result of newing or invoking this tag)
const elemInstanceType = getJsxElementInstanceType(node, elemType);
if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) {
// Is this is a stateless function component? See if its single signature's return type is
// assignable to the JSX Element Type
if (jsxElementType) {
const callSignatures = elemType && getSignaturesOfType(elemType, SignatureKind.Call);
const callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0];
const callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
return paramType;
}
}
}
// Issue an error if this return type isn't assignable to JSX.ElementClass
if (elemClassType) {
checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
if (isTypeAny(elemInstanceType)) {
return elemInstanceType;
}
const propsName = getJsxElementPropertiesName();
if (propsName === undefined) {
// There is no type ElementAttributesProperty, return 'any'
return anyType;
}
else if (propsName === "") {
// If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
return elemInstanceType;
}
else {
const attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName);
if (!attributesType) {
// There is no property named 'props' on this instance type
return emptyObjectType;
}
else if (isTypeAny(attributesType) || (attributesType === unknownType)) {
// Props is of type 'any' or unknown
return attributesType;
}
else if (attributesType.flags & TypeFlags.Union) {
// Props cannot be a union type
error(node.tagName, Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType));
return anyType;
}
else {
// Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
let apparentAttributesType = attributesType;
const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
if (intrinsicClassAttribs !== unknownType) {
const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
if (typeParams) {
if (typeParams.length === 1) {
apparentAttributesType = intersectTypes(createTypeReference(<GenericType>intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType);
}
}
else {
apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs);
}
}
const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
return apparentAttributesType;
}
}
}
/**
* Given an opening/self-closing element, get the 'element attributes type', i.e. the type that tells
* us which attributes are valid on a given element.
@@ -9580,96 +9716,15 @@ namespace ts {
else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) {
return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, IndexKind.String).type;
}
else {
return links.resolvedJsxType = unknownType;
}
}
else {
// Get the element instance type (the result of newing or invoking this tag)
const elemInstanceType = getJsxElementInstanceType(node);
const elemClassType = getJsxGlobalElementClassType();
if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) {
// Is this is a stateless function component? See if its single signature's return type is
// assignable to the JSX Element Type
if (jsxElementType) {
const elemType = checkExpression(node.tagName);
const callSignatures = elemType && getSignaturesOfType(elemType, SignatureKind.Call);
const callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0];
const callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
if (intrinsicAttributes !== unknownType) {
paramType = intersectTypes(intrinsicAttributes, paramType);
}
return links.resolvedJsxType = paramType;
}
}
}
// Issue an error if this return type isn't assignable to JSX.ElementClass
if (elemClassType) {
checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
if (isTypeAny(elemInstanceType)) {
return links.resolvedJsxType = elemInstanceType;
}
const propsName = getJsxElementPropertiesName();
if (propsName === undefined) {
// There is no type ElementAttributesProperty, return 'any'
return links.resolvedJsxType = anyType;
}
else if (propsName === "") {
// If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
return links.resolvedJsxType = elemInstanceType;
}
else {
const attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName);
if (!attributesType) {
// There is no property named 'props' on this instance type
return links.resolvedJsxType = emptyObjectType;
}
else if (isTypeAny(attributesType) || (attributesType === unknownType)) {
// Props is of type 'any' or unknown
return links.resolvedJsxType = attributesType;
}
else if (attributesType.flags & TypeFlags.Union) {
// Props cannot be a union type
error(node.tagName, Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType));
return links.resolvedJsxType = anyType;
}
else {
// Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
let apparentAttributesType = attributesType;
const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes);
if (intrinsicClassAttribs !== unknownType) {
const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
if (typeParams) {
if (typeParams.length === 1) {
apparentAttributesType = intersectTypes(createTypeReference(<GenericType>intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType);
}
}
else {
apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs);
}
}
const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes);
if (intrinsicAttribs !== unknownType) {
apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
}
return links.resolvedJsxType = apparentAttributesType;
}
}
return links.resolvedJsxType = getResolvedJsxType(node, undefined, elemClassType);
}
return links.resolvedJsxType = unknownType;
}
return links.resolvedJsxType;
}
@@ -9919,7 +9974,8 @@ namespace ts {
}
const propType = getTypeOfSymbol(prop);
if (node.kind !== SyntaxKind.PropertyAccessExpression || !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) || isAssignmentTarget(node)) {
if (node.kind !== SyntaxKind.PropertyAccessExpression || isAssignmentTarget(node) ||
!(propType.flags & TypeFlags.Union) && !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor))) {
return propType;
}
const leftmostNode = getLeftmostIdentifierOrThis(node);
@@ -9936,7 +9992,7 @@ namespace ts {
return propType;
}
}
return getFlowTypeOfReference(node, propType, propType);
return getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true);
}
function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean {
@@ -11455,6 +11511,12 @@ namespace ts {
const links = getSymbolLinks(parameter);
if (!links.type) {
links.type = instantiateType(contextualType, mapper);
// if inference didn't come up with anything but {}, fall back to the binding pattern if present.
if (links.type === emptyObjectType &&
(parameter.valueDeclaration.name.kind === SyntaxKind.ObjectBindingPattern ||
parameter.valueDeclaration.name.kind === SyntaxKind.ArrayBindingPattern)) {
links.type = getTypeFromBindingPattern(<BindingPattern>parameter.valueDeclaration.name);
}
assignBindingElementTypes(<ParameterDeclaration>parameter.valueDeclaration);
}
else if (isInferentialContext(mapper)) {
@@ -11534,7 +11596,7 @@ namespace ts {
let types: Type[];
const funcIsGenerator = !!func.asteriskToken;
if (funcIsGenerator) {
types = checkAndAggregateYieldOperandTypes(<Block>func.body, contextualMapper);
types = checkAndAggregateYieldOperandTypes(func, contextualMapper);
if (types.length === 0) {
const iterableIteratorAny = createIterableIteratorType(anyType);
if (compilerOptions.noImplicitAny) {
@@ -11545,8 +11607,10 @@ namespace ts {
}
}
else {
const hasImplicitReturn = !!(func.flags & NodeFlags.HasImplicitReturn);
types = checkAndAggregateReturnExpressionTypes(<Block>func.body, contextualMapper, isAsync, hasImplicitReturn);
types = checkAndAggregateReturnExpressionTypes(func, contextualMapper);
if (!types) {
return neverType;
}
if (types.length === 0) {
if (isAsync) {
// For an async function, the return type will not be void, but rather a Promise for void.
@@ -11555,12 +11619,9 @@ namespace ts {
error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type);
return unknownType;
}
return promiseType;
}
else {
return voidType;
}
return voidType;
}
}
// When yield/return statements are contextually typed we allow the return type to be a union type.
@@ -11604,10 +11665,10 @@ namespace ts {
}
}
function checkAndAggregateYieldOperandTypes(body: Block, contextualMapper?: TypeMapper): Type[] {
function checkAndAggregateYieldOperandTypes(func: FunctionLikeDeclaration, contextualMapper: TypeMapper): Type[] {
const aggregatedTypes: Type[] = [];
forEachYieldExpression(body, yieldExpression => {
forEachYieldExpression(<Block>func.body, yieldExpression => {
const expr = yieldExpression.expression;
if (expr) {
let type = checkExpressionCached(expr, contextualMapper);
@@ -11626,10 +11687,12 @@ namespace ts {
return aggregatedTypes;
}
function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper: TypeMapper, isAsync: boolean, hasImplicitReturn: boolean): Type[] {
function checkAndAggregateReturnExpressionTypes(func: FunctionLikeDeclaration, contextualMapper: TypeMapper): Type[] {
const isAsync = isAsyncFunctionLike(func);
const aggregatedTypes: Type[] = [];
let hasOmittedExpressions = false;
forEachReturnStatement(body, returnStatement => {
let hasReturnWithNoExpression = !!(func.flags & NodeFlags.HasImplicitReturn);
let hasReturnOfTypeNever = false;
forEachReturnStatement(<Block>func.body, returnStatement => {
const expr = returnStatement.expression;
if (expr) {
let type = checkExpressionCached(expr, contextualMapper);
@@ -11638,17 +11701,24 @@ namespace ts {
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body should be unwrapped to its awaited type, which should be wrapped in
// the native Promise<T> type by the caller.
type = checkAwaitedType(type, body.parent, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
type = checkAwaitedType(type, func, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
}
if (!contains(aggregatedTypes, type)) {
if (type === neverType) {
hasReturnOfTypeNever = true;
}
else if (!contains(aggregatedTypes, type)) {
aggregatedTypes.push(type);
}
}
else {
hasOmittedExpressions = true;
hasReturnWithNoExpression = true;
}
});
if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) {
if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever ||
func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction)) {
return undefined;
}
if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) {
if (!contains(aggregatedTypes, undefinedType)) {
aggregatedTypes.push(undefinedType);
}
@@ -11683,7 +11753,10 @@ namespace ts {
const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn;
if (returnType && !hasExplicitReturn) {
if (returnType === neverType) {
error(func.type, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
}
else if (returnType && !hasExplicitReturn) {
// minimal check: function has syntactic return type annotation and no explicit return statements in the body
// this function does not conform to the specification.
// NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
@@ -11837,8 +11910,14 @@ namespace ts {
if (symbol.flags & SymbolFlags.Property &&
(expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) &&
(expr as PropertyAccessExpression | ElementAccessExpression).expression.kind === SyntaxKind.ThisKeyword) {
// Look for if this is the constructor for the class that `symbol` is a property of.
const func = getContainingFunction(expr);
return !(func && func.kind === SyntaxKind.Constructor && func.parent === symbol.valueDeclaration.parent);
if (!(func && func.kind === SyntaxKind.Constructor))
return true;
// If func.parent is a class and symbol is a (readonly) property of that class, or
// if func is a constructor and symbol is a (readonly) parameter property declared in it,
// then symbol is writeable here.
return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent);
}
return true;
}
@@ -12809,7 +12888,7 @@ namespace ts {
if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(
<BindingPattern>name,
predicateVariableNode,
predicateVariableName)) {
predicateVariableName)) {
return true;
}
}
@@ -13394,7 +13473,7 @@ namespace ts {
// Abstract methods can't have an implementation -- in particular, they don't need one.
if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
!(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract)) {
!(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken) {
reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
}
@@ -14747,7 +14826,7 @@ namespace ts {
arrayType = getUnionType(filter((arrayOrStringType as UnionType).types, t => !(t.flags & TypeFlags.StringLike)));
}
else if (arrayOrStringType.flags & TypeFlags.StringLike) {
arrayType = nothingType;
arrayType = neverType;
}
const hasStringConstituent = arrayOrStringType !== arrayType;
let reportedError = false;
@@ -14759,7 +14838,7 @@ namespace ts {
// Now that we've removed all the StringLike types, if no constituents remain, then the entire
// arrayOrStringType was a string.
if (arrayType === nothingType) {
if (arrayType === neverType) {
return stringType;
}
}
@@ -14820,7 +14899,7 @@ namespace ts {
if (func) {
const signature = getSignatureFromDeclaration(func);
const returnType = getReturnTypeOfSignature(signature);
if (strictNullChecks || node.expression) {
if (strictNullChecks || node.expression || returnType === neverType) {
const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
if (func.asteriskToken) {
@@ -16343,14 +16422,11 @@ namespace ts {
function checkSourceFileWorker(node: SourceFile) {
const links = getNodeLinks(node);
if (!(links.flags & NodeCheckFlags.TypeChecked)) {
// Check whether the file has declared it is the default lib,
// and whether the user has specifically chosen to avoid checking it.
if (compilerOptions.skipDefaultLibCheck) {
// If the user specified '--noLib' and a file has a '/// <reference no-default-lib="true"/>',
// then we should treat that file as a default lib.
if (node.hasNoDefaultLib) {
return;
}
// If skipLibCheck is enabled, skip type checking if file is a declaration file.
// If skipDefaultLibCheck is enabled, skip type checking if file contains a
// '/// <reference no-default-lib="true"/>' directive.
if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) {
return;
}
// Grammar checking
@@ -16837,7 +16913,7 @@ namespace ts {
}
if (isBindingPattern(node)) {
return getTypeForVariableLikeDeclaration(<VariableLikeDeclaration>node.parent);
return getTypeForVariableLikeDeclaration(<VariableLikeDeclaration>node.parent, /*includeOptionality*/ true);
}
if (isInRightSideOfImportOrExportAssignment(<Identifier>node)) {
@@ -17431,7 +17507,7 @@ namespace ts {
if (file.moduleAugmentations.length) {
(augmentations || (augmentations = [])).push(file.moduleAugmentations);
}
if (file.wasReferenced && file.symbol && file.symbol.globalExports) {
if (file.symbol && file.symbol.globalExports) {
mergeSymbolTable(globals, file.symbol.globalExports);
}
});
@@ -18284,7 +18360,7 @@ namespace ts {
}
if (node.parent.kind === SyntaxKind.ObjectLiteralExpression) {
if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional)) {
if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) {
return true;
}
else if (node.body === undefined) {
@@ -18293,9 +18369,6 @@ namespace ts {
}
if (isClassLike(node.parent)) {
if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional)) {
return true;
}
// Technically, computed properties in ambient contexts is disallowed
// for property declarations and accessors too, not just methods.
// However, property declarations disallow computed names in general,
@@ -18517,8 +18590,7 @@ namespace ts {
function checkGrammarProperty(node: PropertyDeclaration) {
if (isClassLike(node.parent)) {
if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional) ||
checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) {
if (checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) {
return true;
}
}
+10 -5
View File
@@ -139,6 +139,11 @@ namespace ts {
name: "skipDefaultLibCheck",
type: "boolean",
},
{
name: "skipLibCheck",
type: "boolean",
description: Diagnostics.Skip_type_checking_of_declaration_files,
},
{
name: "out",
type: "string",
@@ -706,11 +711,11 @@ namespace ts {
}
else {
// by default exclude node_modules, and any specificied output directory
exclude = ["node_modules"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
exclude = ["node_modules", "bower_components", "jspm_packages"];
}
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
exclude = map(exclude, normalizeSlashes);
+2 -1
View File
@@ -395,6 +395,7 @@ namespace ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
@@ -1129,7 +1130,7 @@ namespace ts {
// what we want, namely the name expression enclosed in brackets.
writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && hasQuestionToken(node)) {
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.Parameter) && hasQuestionToken(node)) {
write("?");
}
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
+20 -8
View File
@@ -315,10 +315,6 @@
"category": "Error",
"code": 1110
},
"A class member cannot be declared optional.": {
"category": "Error",
"code": 1112
},
"A 'default' clause cannot appear more than once in a 'switch' statement.": {
"category": "Error",
"code": 1113
@@ -447,7 +443,7 @@
"category": "Error",
"code": 1147
},
"Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"Cannot use imports, exports, or module augmentations when '--module' is 'none'.": {
"category": "Error",
"code": 1148
},
@@ -1751,6 +1747,10 @@
"category": "Error",
"code": 2533
},
"A function returning 'never' cannot have a reachable end point.": {
"category": "Error",
"code": 2534
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -1923,6 +1923,10 @@
"category": "Error",
"code": 2685
},
"Identifier '{0}' must be imported from a module": {
"category": "Error",
"code": 2686
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2296,7 +2300,7 @@
"category": "Error",
"code": 5062
},
"Substututions for pattern '{0}' should be an array.": {
"Substitutions for pattern '{0}' should be an array.": {
"category": "Error",
"code": 5063
},
@@ -2348,6 +2352,10 @@
"category": "Message",
"code": 6011
},
"Skip type checking of declaration files.": {
"category": "Message",
"code": 6012
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"category": "Message",
"code": 6015
@@ -2752,13 +2760,17 @@
"category": "Message",
"code": 6130
},
"Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'.": {
"category": "Error",
"code": 6131
},
"The maximum dependency depth to search under node_modules and load JavaScript files": {
"category": "Message",
"code": 6131
"code": 6132
},
"No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'": {
"category": "Message",
"code": 6132
"code": 6133
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
+6 -4
View File
@@ -303,8 +303,8 @@ namespace ts {
case SyntaxKind.ImportClause:
return visitNode(cbNode, (<ImportClause>node).name) ||
visitNode(cbNode, (<ImportClause>node).namedBindings);
case SyntaxKind.GlobalModuleExportDeclaration:
return visitNode(cbNode, (<GlobalModuleExportDeclaration>node).name);
case SyntaxKind.NamespaceExportDeclaration:
return visitNode(cbNode, (<NamespaceExportDeclaration>node).name);
case SyntaxKind.NamespaceImport:
return visitNode(cbNode, (<NamespaceImport>node).name);
@@ -2368,6 +2368,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
@@ -2410,6 +2411,7 @@ namespace ts {
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.LessThanToken:
@@ -5342,8 +5344,8 @@ namespace ts {
return nextToken() === SyntaxKind.SlashToken;
}
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): GlobalModuleExportDeclaration {
const exportDeclaration = <GlobalModuleExportDeclaration>createNode(SyntaxKind.GlobalModuleExportDeclaration, fullStart);
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): NamespaceExportDeclaration {
const exportDeclaration = <NamespaceExportDeclaration>createNode(SyntaxKind.NamespaceExportDeclaration, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
parseExpected(SyntaxKind.AsKeyword);
+10 -9
View File
@@ -1771,10 +1771,6 @@ namespace ts {
reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd);
}
if (file) {
file.wasReferenced = file.wasReferenced || isReference;
}
// If this was a file found by a node_modules search, set the nodeModuleSearchDistance to parent distance + 1.
if (isFileFromNodeSearch) {
const newDistance = (refFile && refFile.nodeModuleSearchDistance) === undefined ? 1 : refFile.nodeModuleSearchDistance + 1;
@@ -1797,7 +1793,6 @@ namespace ts {
filesByName.set(path, file);
if (file) {
file.wasReferenced = file.wasReferenced || isReference;
file.path = path;
// Default to same distance as parent. Add one if found by a search.
@@ -2051,7 +2046,7 @@ namespace ts {
}
}
else {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substututions_for_pattern_0_should_be_an_array, key));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key));
}
}
}
@@ -2110,7 +2105,7 @@ namespace ts {
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
}
// Cannot specify module gen target of es6 when below es6
@@ -2119,8 +2114,14 @@ namespace ts {
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
if (outFile) {
if (options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
else if (options.module === undefined && firstExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
// there has to be common source directory if user specified --outdir || --sourceRoot
+1
View File
@@ -91,6 +91,7 @@ namespace ts {
"let": SyntaxKind.LetKeyword,
"module": SyntaxKind.ModuleKeyword,
"namespace": SyntaxKind.NamespaceKeyword,
"never": SyntaxKind.NeverKeyword,
"new": SyntaxKind.NewKeyword,
"null": SyntaxKind.NullKeyword,
"number": SyntaxKind.NumberKeyword,
+8 -6
View File
@@ -164,6 +164,7 @@ namespace ts {
IsKeyword,
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
@@ -276,7 +277,7 @@ namespace ts {
ModuleDeclaration,
ModuleBlock,
CaseBlock,
GlobalModuleExportDeclaration,
NamespaceExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
@@ -1340,8 +1341,8 @@ namespace ts {
name: Identifier;
}
// @kind(SyntaxKind.GlobalModuleImport)
export interface GlobalModuleExportDeclaration extends DeclarationStatement {
// @kind(SyntaxKind.NamespaceExportDeclaration)
export interface NamespaceExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
@@ -1600,8 +1601,6 @@ namespace ts {
/* @internal */ commonJsModuleIndicator: Node;
// The number of times node_modules was searched to locate the package containing this file
/* @internal */ nodeModuleSearchDistance?: number;
// True if the file was a root file in a compilation or a /// reference targets
/* @internal */ wasReferenced?: boolean;
/* @internal */ identifiers: Map<string>;
/* @internal */ nodeCount: number;
@@ -1774,6 +1773,7 @@ namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
@@ -2172,11 +2172,12 @@ namespace ts {
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
Never = 0x08000000, // Never type
/* @internal */
Nullable = Undefined | Null,
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null | Never,
/* @internal */
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
StringLike = String | StringLiteral,
@@ -2505,6 +2506,7 @@ namespace ts {
maxNodeModuleJsDepth?: number;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
skipLibCheck?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;
+11 -3
View File
@@ -613,6 +613,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.VoidExpression;
@@ -1260,8 +1261,15 @@ namespace ts {
else if (lhs.expression.kind === SyntaxKind.PropertyAccessExpression) {
// chained dot, e.g. x.y.z = expr; this var is the 'x.y' part
const innerPropertyAccess = <PropertyAccessExpression>lhs.expression;
if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier && innerPropertyAccess.name.text === "prototype") {
return SpecialPropertyAssignmentKind.PrototypeProperty;
if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier) {
// module.exports.name = expr
const innerPropertyAccessIdentifier = <Identifier>innerPropertyAccess.expression;
if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") {
return SpecialPropertyAssignmentKind.ExportsProperty;
}
if (innerPropertyAccess.name.text === "prototype") {
return SpecialPropertyAssignmentKind.PrototypeProperty;
}
}
}
@@ -1635,7 +1643,7 @@ namespace ts {
// export default ...
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.GlobalModuleExportDeclaration ||
node.kind === SyntaxKind.NamespaceExportDeclaration ||
node.kind === SyntaxKind.ImportClause && !!(<ImportClause>node).name ||
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.ImportSpecifier ||
+40 -22
View File
@@ -1968,12 +1968,12 @@ namespace FourSlash {
}
}
public verifyGetScriptLexicalStructureListCount(expected: number) {
public verifyNavigationBarCount(expected: number) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const actual = this.getNavigationBarItemsCount(items);
if (expected !== actual) {
this.raiseError(`verifyGetScriptLexicalStructureListCount failed - found: ${actual} navigation items, expected: ${expected}.`);
this.raiseError(`verifyNavigationBarCount failed - found: ${actual} navigation items, expected: ${expected}.`);
}
}
@@ -1989,36 +1989,50 @@ namespace FourSlash {
return result;
}
public verifyGetScriptLexicalStructureListContains(name: string, kind: string) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
public verifyNavigationBarContains(name: string, kind: string, fileName?: string, parentName?: string, isAdditionalSpan?: boolean, markerPosition?: number) {
fileName = fileName || this.activeFile.fileName;
const items = this.languageService.getNavigationBarItems(fileName);
if (!items || items.length === 0) {
this.raiseError("verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.");
this.raiseError("verifyNavigationBarContains failed - found 0 navigation items, expected at least one.");
}
if (this.navigationBarItemsContains(items, name, kind)) {
if (this.navigationBarItemsContains(items, name, kind, parentName)) {
return;
}
const missingItem = { name: name, kind: kind };
this.raiseError(`verifyGetScriptLexicalStructureListContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(items, undefined, 2)})`);
const missingItem = { name, kind, parentName };
this.raiseError(`verifyNavigationBarContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(items, undefined, 2)})`);
}
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) {
if (items) {
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string, parentName?: string) {
function recur(items: ts.NavigationBarItem[], curParentName: string) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item && item.text === name && item.kind === kind) {
if (item && item.text === name && item.kind === kind && (!parentName || curParentName === parentName)) {
return true;
}
if (this.navigationBarItemsContains(item.childItems, name, kind)) {
if (recur(item.childItems, item.text)) {
return true;
}
}
return false;
}
return recur(items, "");
}
return false;
public verifyNavigationBarChildItem(parent: string, name: string, kind: string) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.text === parent) {
if (this.navigationBarItemsContains(item.childItems, name, kind))
return;
const missingItem = { name, kind };
this.raiseError(`verifyNavigationBarChildItem failed - could not find the item: ${JSON.stringify(missingItem)} in the children list: (${JSON.stringify(item.childItems, undefined, 2)})`);
}
}
}
public printNavigationItems(searchValue: string) {
@@ -2033,11 +2047,11 @@ namespace FourSlash {
}
}
public printScriptLexicalStructureItems() {
public printNavigationBar() {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const length = items && items.length;
Harness.IO.log(`NavigationItems list (${length} items)`);
Harness.IO.log(`Navigation bar (${length} items)`);
for (let i = 0; i < length; i++) {
const item = items[i];
@@ -3029,19 +3043,23 @@ namespace FourSlashInterface {
this.DocCommentTemplate(/*expectedText*/ undefined, /*expectedOffset*/ undefined, /*empty*/ true);
}
public getScriptLexicalStructureListCount(count: number) {
this.state.verifyGetScriptLexicalStructureListCount(count);
public navigationBarCount(count: number) {
this.state.verifyNavigationBarCount(count);
}
// TODO: figure out what to do with the unused arguments.
public getScriptLexicalStructureListContains(
public navigationBarContains(
name: string,
kind: string,
fileName?: string,
parentName?: string,
isAdditionalSpan?: boolean,
markerPosition?: number) {
this.state.verifyGetScriptLexicalStructureListContains(name, kind);
this.state.verifyNavigationBarContains(name, kind, fileName, parentName, isAdditionalSpan, markerPosition);
}
public navigationBarChildItem(parent: string, name: string, kind: string) {
this.state.verifyNavigationBarChildItem(parent, name, kind);
}
public navigationItemsListCount(count: number, searchValue: string, matchKind?: string) {
@@ -3234,8 +3252,8 @@ namespace FourSlashInterface {
this.state.printNavigationItems(searchValue);
}
public printScriptLexicalStructureItems() {
this.state.printScriptLexicalStructureItems();
public printNavigationBar() {
this.state.printNavigationBar();
}
public printReferences() {
+8
View File
@@ -641,6 +641,14 @@ namespace Harness.LanguageService {
startGroup(): void {
}
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any {
return setTimeout(callback, ms, args);
}
clearTimeout(timeoutId: any): void {
clearTimeout(timeoutId);
}
}
export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
+20 -19
View File
@@ -1,6 +1,6 @@
declare var require: any, process: any;
var fs: any = require('fs');
var path: any = require('path');
declare const require: any, process: any;
const fs: any = require("fs");
const path: any = require("path");
function instrumentForRecording(fn: string, tscPath: string) {
instrument(tscPath, `
@@ -14,31 +14,31 @@ ts.sys = Playback.wrapSystem(ts.sys);
ts.sys.startReplay("${ logFilename }");`);
}
function instrument(tscPath: string, prepareCode: string, cleanupCode: string = '') {
var bak = tscPath + '.bak';
function instrument(tscPath: string, prepareCode: string, cleanupCode = "") {
const bak = `${tscPath}.bak`;
fs.exists(bak, (backupExists: boolean) => {
var filename = tscPath;
let filename = tscPath;
if (backupExists) {
filename = bak;
}
fs.readFile(filename, 'utf-8', (err: any, tscContent: string) => {
fs.readFile(filename, "utf-8", (err: any, tscContent: string) => {
if (err) throw err;
fs.writeFile(bak, tscContent, (err: any) => {
if (err) throw err;
fs.readFile(path.resolve(path.dirname(tscPath) + '/loggedIO.js'), 'utf-8', (err: any, loggerContent: string) => {
fs.readFile(path.resolve(path.dirname(tscPath) + "/loggedIO.js"), "utf-8", (err: any, loggerContent: string) => {
if (err) throw err;
var invocationLine = 'ts.executeCommandLine(ts.sys.args);';
var index1 = tscContent.indexOf(invocationLine);
const invocationLine = "ts.executeCommandLine(ts.sys.args);";
const index1 = tscContent.indexOf(invocationLine);
if (index1 < 0) {
throw new Error("Could not find " + invocationLine);
throw new Error(`Could not find ${invocationLine}`);
}
var index2 = index1 + invocationLine.length;
var newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + '\r\n';
const index2 = index1 + invocationLine.length;
const newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + "\r\n";
fs.writeFile(tscPath, newContent);
});
});
@@ -46,15 +46,16 @@ function instrument(tscPath: string, prepareCode: string, cleanupCode: string =
});
}
var isJson = (arg: string) => arg.indexOf(".json") > 0;
const isJson = (arg: string) => arg.indexOf(".json") > 0;
var record = process.argv.indexOf('record');
var tscPath = process.argv[process.argv.length - 1];
const record = process.argv.indexOf("record");
const tscPath = process.argv[process.argv.length - 1];
if (record >= 0) {
console.log('Instrumenting ' + tscPath + ' for recording');
console.log(`Instrumenting ${tscPath} for recording`);
instrumentForRecording(process.argv[record + 1], tscPath);
} else if (process.argv.some(isJson)) {
var filename = process.argv.filter(isJson)[0];
}
else if (process.argv.some(isJson)) {
const filename = process.argv.filter(isJson)[0];
instrumentForReplay(filename, tscPath);
}
+4 -4
View File
@@ -16,12 +16,12 @@ interface Array<T> {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
/**
* Returns the this object after filling the section identified by start and end with value
@@ -493,4 +493,4 @@ interface StringConstructor {
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
}
+32 -47
View File
@@ -864,6 +864,7 @@ declare const RegExp: RegExpConstructor;
interface Error {
name: string;
message: string;
stack?: string;
}
interface ErrorConstructor {
@@ -948,38 +949,22 @@ interface JSON {
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
parse(text: string, reviver?: (key: any, value: any) => any): any;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
*/
stringify(value: any): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
*/
stringify(value: any, replacer: (key: string, value: any) => any): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer Array that transforms the results.
*/
stringify(value: any, replacer: any[]): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string;
stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer Array that transforms the results.
* @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: any[], space: string | number): string;
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
*/
@@ -1527,12 +1512,12 @@ interface Int8Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -1800,12 +1785,12 @@ interface Uint8Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -2074,12 +2059,12 @@ interface Uint8ClampedArray {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -2347,12 +2332,12 @@ interface Int16Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -2621,12 +2606,12 @@ interface Uint16Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -2894,12 +2879,12 @@ interface Int32Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -3167,12 +3152,12 @@ interface Uint32Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -3440,12 +3425,12 @@ interface Float32Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
@@ -3714,12 +3699,12 @@ interface Float64Array {
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
+168 -155
View File
@@ -1,5 +1,5 @@
/// <reference path="session.ts" />
namespace ts.server {
export interface SessionClientHost extends LanguageServiceHost {
@@ -21,27 +21,26 @@ namespace ts.server {
export class SessionClient implements LanguageService {
private sequence: number = 0;
private fileMapping: ts.Map<string> = {};
private lineMaps: ts.Map<number[]> = {};
private messages: string[] = [];
private lastRenameEntry: RenameEntry;
constructor(private host: SessionClientHost) {
}
public onMessage(message: string): void {
public onMessage(message: string): void {
this.messages.push(message);
}
private writeMessage(message: string): void {
private writeMessage(message: string): void {
this.host.writeMessage(message);
}
private getLineMap(fileName: string): number[] {
var lineMap = ts.lookUp(this.lineMaps, fileName);
private getLineMap(fileName: string): number[] {
let lineMap = ts.lookUp(this.lineMaps, fileName);
if (!lineMap) {
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
lineMap = this.lineMaps[fileName] = ts.computeLineStarts(scriptSnapshot.getText(0, scriptSnapshot.getLength()));
const scriptSnapshot = this.host.getScriptSnapshot(fileName);
lineMap = this.lineMaps[fileName] = ts.computeLineStarts(scriptSnapshot.getText(0, scriptSnapshot.getLength()));
}
return lineMap;
}
@@ -51,7 +50,7 @@ namespace ts.server {
}
private positionToOneBasedLineOffset(fileName: string, position: number): protocol.Location {
var lineOffset = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
const lineOffset = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
return {
line: lineOffset.line + 1,
offset: lineOffset.character + 1
@@ -59,8 +58,8 @@ namespace ts.server {
}
private convertCodeEditsToTextChange(fileName: string, codeEdit: protocol.CodeEdit): ts.TextChange {
var start = this.lineOffsetToPosition(fileName, codeEdit.start);
var end = this.lineOffsetToPosition(fileName, codeEdit.end);
const start = this.lineOffsetToPosition(fileName, codeEdit.start);
const end = this.lineOffsetToPosition(fileName, codeEdit.end);
return {
span: ts.createTextSpanFromBounds(start, end),
@@ -69,12 +68,13 @@ namespace ts.server {
}
private processRequest<T extends protocol.Request>(command: string, args?: any): T {
var request: protocol.Request = {
seq: this.sequence++,
const request: protocol.Request = {
seq: this.sequence,
type: "request",
arguments: args,
command
};
this.sequence++;
this.writeMessage(JSON.stringify(request));
@@ -82,34 +82,29 @@ namespace ts.server {
}
private processResponse<T extends protocol.Response>(request: protocol.Request): T {
var lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not receive any responses.");
// Read the content length
var contentLengthPrefix = "Content-Length: ";
var lines = lastMessage.split("\r\n");
Debug.assert(lines.length >= 2, "Malformed response: Expected 3 lines in the response.");
var contentLengthText = lines[0];
Debug.assert(contentLengthText.indexOf(contentLengthPrefix) === 0, "Malformed response: Response text did not contain content-length header.");
var contentLength = parseInt(contentLengthText.substring(contentLengthPrefix.length));
// Read the body
var responseBody = lines[2];
// Verify content length
Debug.assert(responseBody.length + 1 === contentLength, "Malformed response: Content length did not match the response's body length.");
try {
var response: T = JSON.parse(responseBody);
}
catch (e) {
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error details: " + e.message);
let foundResponseMessage = false;
let lastMessage: string;
let response: T;
while (!foundResponseMessage) {
lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not receive any responses.");
const responseBody = processMessage(lastMessage);
try {
response = JSON.parse(responseBody);
// the server may emit events before emitting the response. We
// want to ignore these events for testing purpose.
if (response.type === "response") {
foundResponseMessage = true;
}
}
catch (e) {
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error details: " + e.message);
}
}
// verify the sequence numbers
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequence number did not match request sequence number.");
// unmarshal errors
if (!response.success) {
throw new Error("Error " + response.message);
@@ -118,15 +113,33 @@ namespace ts.server {
Debug.assert(!!response.body, "Malformed response: Unexpected empty response body.");
return response;
function processMessage(message: string) {
// Read the content length
const contentLengthPrefix = "Content-Length: ";
const lines = message.split("\r\n");
Debug.assert(lines.length >= 2, "Malformed response: Expected 3 lines in the response.");
const contentLengthText = lines[0];
Debug.assert(contentLengthText.indexOf(contentLengthPrefix) === 0, "Malformed response: Response text did not contain content-length header.");
const contentLength = parseInt(contentLengthText.substring(contentLengthPrefix.length));
// Read the body
const responseBody = lines[2];
// Verify content length
Debug.assert(responseBody.length + 1 === contentLength, "Malformed response: Content length did not match the response's body length.");
return responseBody;
}
}
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content, scriptKindName };
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
const args: protocol.OpenRequestArgs = { file: fileName, fileContent: content, scriptKindName };
this.processRequest(CommandNames.Open, args);
}
closeFile(fileName: string): void {
var args: protocol.FileRequestArgs = { file: fileName };
const args: protocol.FileRequestArgs = { file: fileName };
this.processRequest(CommandNames.Close, args);
}
@@ -134,10 +147,10 @@ namespace ts.server {
// clear the line map after an edit
this.lineMaps[fileName] = undefined;
var lineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const lineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.ChangeRequestArgs = {
const args: protocol.ChangeRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -150,18 +163,18 @@ namespace ts.server {
}
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset
};
var request = this.processRequest<protocol.QuickInfoRequest>(CommandNames.Quickinfo, args);
var response = this.processResponse<protocol.QuickInfoResponse>(request);
const request = this.processRequest<protocol.QuickInfoRequest>(CommandNames.Quickinfo, args);
const response = this.processResponse<protocol.QuickInfoResponse>(request);
var start = this.lineOffsetToPosition(fileName, response.body.start);
var end = this.lineOffsetToPosition(fileName, response.body.end);
const start = this.lineOffsetToPosition(fileName, response.body.start);
const end = this.lineOffsetToPosition(fileName, response.body.end);
return {
kind: response.body.kind,
@@ -173,68 +186,68 @@ namespace ts.server {
}
getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo {
var args: protocol.ProjectInfoRequestArgs = {
const args: protocol.ProjectInfoRequestArgs = {
file: fileName,
needFileNameList: needFileNameList
};
var request = this.processRequest<protocol.ProjectInfoRequest>(CommandNames.ProjectInfo, args);
var response = this.processResponse<protocol.ProjectInfoResponse>(request);
const request = this.processRequest<protocol.ProjectInfoRequest>(CommandNames.ProjectInfo, args);
const response = this.processResponse<protocol.ProjectInfoResponse>(request);
return {
configFileName: response.body.configFileName,
fileNames: response.body.fileNames
};
}
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionsRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.CompletionsRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
prefix: undefined
};
var request = this.processRequest<protocol.CompletionsRequest>(CommandNames.Completions, args);
var response = this.processResponse<protocol.CompletionsResponse>(request);
const request = this.processRequest<protocol.CompletionsRequest>(CommandNames.Completions, args);
const response = this.processResponse<protocol.CompletionsResponse>(request);
return {
return {
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: response.body
};
}
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionDetailsRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.CompletionDetailsRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
entryNames: [entryName]
};
var request = this.processRequest<protocol.CompletionDetailsRequest>(CommandNames.CompletionDetails, args);
var response = this.processResponse<protocol.CompletionDetailsResponse>(request);
const request = this.processRequest<protocol.CompletionDetailsRequest>(CommandNames.CompletionDetails, args);
const response = this.processResponse<protocol.CompletionDetailsResponse>(request);
Debug.assert(response.body.length === 1, "Unexpected length of completion details response body.");
return response.body[0];
}
getNavigateToItems(searchValue: string): NavigateToItem[] {
var args: protocol.NavtoRequestArgs = {
const args: protocol.NavtoRequestArgs = {
searchValue,
file: this.host.getScriptFileNames()[0]
};
var request = this.processRequest<protocol.NavtoRequest>(CommandNames.Navto, args);
var response = this.processResponse<protocol.NavtoResponse>(request);
const request = this.processRequest<protocol.NavtoRequest>(CommandNames.Navto, args);
const response = this.processResponse<protocol.NavtoResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
name: entry.name,
containerName: entry.containerName || "",
@@ -250,9 +263,9 @@ namespace ts.server {
}
getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): ts.TextChange[] {
var startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.FormatRequestArgs = {
const startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const args: protocol.FormatRequestArgs = {
file: fileName,
line: startLineOffset.line,
offset: startLineOffset.offset,
@@ -261,10 +274,10 @@ namespace ts.server {
};
// TODO: handle FormatCodeOptions
var request = this.processRequest<protocol.FormatRequest>(CommandNames.Format, args);
var response = this.processResponse<protocol.FormatResponse>(request);
const request = this.processRequest<protocol.FormatRequest>(CommandNames.Format, args);
const response = this.processResponse<protocol.FormatResponse>(request);
return response.body.map(entry=> this.convertCodeEditsToTextChange(fileName, entry));
return response.body.map(entry => this.convertCodeEditsToTextChange(fileName, entry));
}
getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): ts.TextChange[] {
@@ -272,8 +285,8 @@ namespace ts.server {
}
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): ts.TextChange[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FormatOnKeyRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FormatOnKeyRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -281,27 +294,27 @@ namespace ts.server {
};
// TODO: handle FormatCodeOptions
var request = this.processRequest<protocol.FormatOnKeyRequest>(CommandNames.Formatonkey, args);
var response = this.processResponse<protocol.FormatResponse>(request);
const request = this.processRequest<protocol.FormatOnKeyRequest>(CommandNames.Formatonkey, args);
const response = this.processResponse<protocol.FormatResponse>(request);
return response.body.map(entry=> this.convertCodeEditsToTextChange(fileName, entry));
return response.body.map(entry => this.convertCodeEditsToTextChange(fileName, entry));
}
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.DefinitionRequest>(CommandNames.Definition, args);
var response = this.processResponse<protocol.DefinitionResponse>(request);
const request = this.processRequest<protocol.DefinitionRequest>(CommandNames.Definition, args);
const response = this.processResponse<protocol.DefinitionResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
@@ -314,20 +327,20 @@ namespace ts.server {
}
getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.TypeDefinitionRequest>(CommandNames.TypeDefinition, args);
var response = this.processResponse<protocol.TypeDefinitionResponse>(request);
const request = this.processRequest<protocol.TypeDefinitionRequest>(CommandNames.TypeDefinition, args);
const response = this.processResponse<protocol.TypeDefinitionResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
@@ -339,26 +352,26 @@ namespace ts.server {
});
}
findReferences(fileName: string, position: number): ReferencedSymbol[]{
findReferences(fileName: string, position: number): ReferencedSymbol[] {
// Not yet implemented.
return [];
}
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.ReferencesRequest>(CommandNames.References, args);
var response = this.processResponse<protocol.ReferencesResponse>(request);
const request = this.processRequest<protocol.ReferencesRequest>(CommandNames.References, args);
const response = this.processResponse<protocol.ReferencesResponse>(request);
return response.body.refs.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
@@ -384,8 +397,8 @@ namespace ts.server {
}
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.RenameRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.RenameRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -393,14 +406,14 @@ namespace ts.server {
findInComments
};
var request = this.processRequest<protocol.RenameRequest>(CommandNames.Rename, args);
var response = this.processResponse<protocol.RenameResponse>(request);
var locations: RenameLocation[] = [];
const request = this.processRequest<protocol.RenameRequest>(CommandNames.Rename, args);
const response = this.processResponse<protocol.RenameResponse>(request);
const locations: RenameLocation[] = [];
response.body.locs.map((entry: protocol.SpanGroup) => {
var fileName = entry.file;
const fileName = entry.file;
entry.locs.map((loc: protocol.TextSpan) => {
var start = this.lineOffsetToPosition(fileName, loc.start);
var end = this.lineOffsetToPosition(fileName, loc.end);
const start = this.lineOffsetToPosition(fileName, loc.start);
const end = this.lineOffsetToPosition(fileName, loc.end);
locations.push({
textSpan: ts.createTextSpanFromBounds(start, end),
fileName: fileName
@@ -444,7 +457,7 @@ namespace ts.server {
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers || "",
spans: item.spans.map(span=> createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))),
spans: item.spans.map(span => createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))),
childItems: this.decodeNavigationBarItems(item.childItems, fileName),
indent: 0,
bolded: false,
@@ -453,12 +466,12 @@ namespace ts.server {
}
getNavigationBarItems(fileName: string): NavigationBarItem[] {
var args: protocol.FileRequestArgs = {
const args: protocol.FileRequestArgs = {
file: fileName
};
var request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, args);
var response = this.processResponse<protocol.NavBarResponse>(request);
const request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, args);
const response = this.processResponse<protocol.NavBarResponse>(request);
return this.decodeNavigationBarItems(response.body, fileName);
}
@@ -472,26 +485,26 @@ namespace ts.server {
}
getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.SignatureHelpRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.SignatureHelpRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset
};
var request = this.processRequest<protocol.SignatureHelpRequest>(CommandNames.SignatureHelp, args);
var response = this.processResponse<protocol.SignatureHelpResponse>(request);
const request = this.processRequest<protocol.SignatureHelpRequest>(CommandNames.SignatureHelp, args);
const response = this.processResponse<protocol.SignatureHelpResponse>(request);
if (!response.body) {
return undefined;
}
var helpItems: protocol.SignatureHelpItems = response.body;
var span = helpItems.applicableSpan;
var start = this.lineOffsetToPosition(fileName, span.start);
var end = this.lineOffsetToPosition(fileName, span.end);
var result: SignatureHelpItems = {
const helpItems: protocol.SignatureHelpItems = response.body;
const span = helpItems.applicableSpan;
const start = this.lineOffsetToPosition(fileName, span.start);
const end = this.lineOffsetToPosition(fileName, span.end);
const result: SignatureHelpItems = {
items: helpItems.items,
applicableSpan: {
start: start,
@@ -499,26 +512,26 @@ namespace ts.server {
},
selectedItemIndex: helpItems.selectedItemIndex,
argumentIndex: helpItems.argumentIndex,
argumentCount: helpItems.argumentCount,
}
argumentCount: helpItems.argumentCount,
};
return result;
}
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.OccurrencesRequest>(CommandNames.Occurrences, args);
var response = this.processResponse<protocol.OccurrencesResponse>(request);
const request = this.processRequest<protocol.OccurrencesRequest>(CommandNames.Occurrences, args);
const response = this.processResponse<protocol.OccurrencesResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
@@ -528,17 +541,17 @@ namespace ts.server {
}
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
let { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
let args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
const { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
let request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
let response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
const request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
const response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
let self = this;
const self = this;
return response.body.map(convertToDocumentHighlights);
function convertToDocumentHighlights(item: ts.server.protocol.DocumentHighlightsItem): ts.DocumentHighlights {
let { file, highlightSpans } = item;
const { file, highlightSpans } = item;
return {
fileName: file,
@@ -546,8 +559,8 @@ namespace ts.server {
};
function convertHighlightSpan(span: ts.server.protocol.HighlightSpan): ts.HighlightSpan {
let start = self.lineOffsetToPosition(file, span.start);
let end = self.lineOffsetToPosition(file, span.end);
const start = self.lineOffsetToPosition(file, span.start);
const end = self.lineOffsetToPosition(file, span.end);
return {
textSpan: ts.createTextSpanFromBounds(start, end),
kind: span.kind
@@ -561,31 +574,31 @@ namespace ts.server {
}
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.BraceRequest>(CommandNames.Brace, args);
var response = this.processResponse<protocol.BraceResponse>(request);
const request = this.processRequest<protocol.BraceRequest>(CommandNames.Brace, args);
const response = this.processResponse<protocol.BraceResponse>(request);
return response.body.map(entry => {
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
start: start,
length: end - start,
+33 -26
View File
@@ -32,7 +32,7 @@ namespace ts.server {
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
path: Path;
scriptKind: ScriptKind;
@@ -533,7 +533,7 @@ namespace ts.server {
// number becomes 0 for a watcher, then we should close it.
directoryWatchersRefCount: ts.Map<number> = {};
hostConfiguration: HostConfiguration;
timerForDetectingProjectFileListChanges: Map<NodeJS.Timer> = {};
timerForDetectingProjectFileListChanges: Map<any> = {};
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
@@ -542,7 +542,7 @@ namespace ts.server {
addDefaultHostConfiguration() {
this.hostConfiguration = {
formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions),
formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)),
hostInfo: "Unknown host"
};
}
@@ -593,9 +593,9 @@ namespace ts.server {
startTimerForDetectingProjectFileListChanges(project: Project) {
if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
}
this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(
this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(
() => this.handleProjectFileListChanges(project),
250
);
@@ -1122,8 +1122,13 @@ namespace ts.server {
return { configFileName, configFileErrors: configResult.errors };
}
else {
// even if opening config file was successful, it could still
// contain errors that were tolerated.
this.log("Opened configuration file " + configFileName, "Info");
this.configuredProjects.push(configResult.project);
if (configResult.errors && configResult.errors.length > 0) {
return { configFileName, configFileErrors: configResult.errors };
}
}
}
else {
@@ -1261,14 +1266,14 @@ namespace ts.server {
}
else {
const project = this.createProject(configFilename, projectOptions);
let errors: Diagnostic[];
for (const rootFilename of projectOptions.files) {
if (this.host.fileExists(rootFilename)) {
const info = this.openFile(rootFilename, /*openedByClient*/ clientFileName == rootFilename);
project.addRoot(info);
}
else {
const error = createCompilerDiagnostic(Diagnostics.File_0_not_found, rootFilename);
return { success: false, errors: [error] };
(errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.File_0_not_found, rootFilename));
}
}
project.finishGraph();
@@ -1279,7 +1284,7 @@ namespace ts.server {
path => this.directoryWatchedForSourceFilesChanged(project, path),
/*recursive*/ true
);
return { success: true, project: project };
return { success: true, project: project, errors };
}
}
@@ -1295,7 +1300,7 @@ namespace ts.server {
}
else {
const oldFileNames = project.compilerService.host.roots.map(info => info.fileName);
const newFileNames = projectOptions.files;
const newFileNames = ts.filter(projectOptions.files, f => this.host.fileExists(f));
const fileNamesToRemove = oldFileNames.filter(f => newFileNames.indexOf(f) < 0);
const fileNamesToAdd = newFileNames.filter(f => oldFileNames.indexOf(f) < 0);
@@ -1377,23 +1382,25 @@ namespace ts.server {
return ts.isExternalModule(sourceFile);
}
static defaultFormatCodeOptions: ts.FormatCodeOptions = {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: ts.sys ? ts.sys.newLine : "\n",
ConvertTabsToSpaces: true,
IndentStyle: ts.IndentStyle.Smart,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions {
return ts.clone({
IndentSize: 4,
TabSize: 4,
NewLineCharacter: host.newLine || "\n",
ConvertTabsToSpaces: true,
IndentStyle: ts.IndentStyle.Smart,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
});
}
}
export interface LineCollection {
+8 -3
View File
@@ -266,16 +266,21 @@ namespace ts.server {
}
}
const sys = <ServerHost>ts.sys;
// Override sys.write because fs.writeSync is not reliable on Node 4
ts.sys.write = (s: string) => writeMessage(s);
ts.sys.watchFile = (fileName, callback) => {
sys.write = (s: string) => writeMessage(s);
sys.watchFile = (fileName, callback) => {
const watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
return {
close: () => pollingWatchedFileSet.removeFile(watchedFile)
};
};
const ioSession = new IOSession(ts.sys, logger);
sys.setTimeout = setTimeout;
sys.clearTimeout = clearTimeout;
const ioSession = new IOSession(sys, logger);
process.on("uncaughtException", function(err: Error) {
ioSession.logError(err, "unknown");
});
+2
View File
@@ -133,6 +133,8 @@ namespace ts.server {
}
export interface ServerHost extends ts.System {
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout(timeoutId: any): void;
}
export class Session {
+11 -11
View File
@@ -24,7 +24,7 @@ namespace ts.BreakpointResolver {
// token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
tokenAtLocation = findPrecedingToken(tokenAtLocation.pos, sourceFile);
// Its a blank line
// It's a blank line
if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) {
return undefined;
}
@@ -312,7 +312,7 @@ namespace ts.BreakpointResolver {
case SyntaxKind.BinaryExpression:
if ((<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
// if this is comma expression, the breakpoint is possible in this expression
// If this is a comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
@@ -387,7 +387,7 @@ namespace ts.BreakpointResolver {
return spanInNode(variableDeclaration.parent.parent);
}
// If this is a destructuring pattern set breakpoint in binding pattern
// If this is a destructuring pattern, set breakpoint in binding pattern
if (isBindingPattern(variableDeclaration.name)) {
return spanInBindingPattern(<BindingPattern>variableDeclaration.name);
}
@@ -402,9 +402,9 @@ namespace ts.BreakpointResolver {
let declarations = variableDeclaration.parent.declarations;
if (declarations && declarations[0] !== variableDeclaration) {
// If we cant set breakpoint on this declaration, set it on previous one
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
// we would like to set breakpoint in last binding element if thats the case,
// we would like to set breakpoint in last binding element if that's the case,
// use preceding token instead
return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
}
@@ -418,7 +418,7 @@ namespace ts.BreakpointResolver {
function spanInParameterDeclaration(parameter: ParameterDeclaration): TextSpan {
if (isBindingPattern(parameter.name)) {
// set breakpoint in binding pattern
// Set breakpoint in binding pattern
return spanInBindingPattern(<BindingPattern>parameter.name);
}
else if (canHaveSpanInParameterDeclaration(parameter)) {
@@ -492,7 +492,7 @@ namespace ts.BreakpointResolver {
function spanInInitializerOfForLike(forLikeStatement: ForStatement | ForOfStatement | ForInStatement): TextSpan {
if (forLikeStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
// declaration list, set breakpoint in first declaration
// Declaration list - set breakpoint in first declaration
let variableDeclarationList = <VariableDeclarationList>forLikeStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
@@ -578,7 +578,7 @@ namespace ts.BreakpointResolver {
function spanInCloseBraceToken(node: Node): TextSpan {
switch (node.parent.kind) {
case SyntaxKind.ModuleBlock:
// If this is not instantiated module block no bp span
// If this is not an instantiated module block, no bp span
if (getModuleInstanceState(node.parent.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
@@ -593,7 +593,7 @@ namespace ts.BreakpointResolver {
// Span on close brace token
return textSpan(node);
}
// fall through.
// fall through
case SyntaxKind.CatchClause:
return spanInNode(lastOrUndefined((<Block>node.parent).statements));
@@ -714,7 +714,7 @@ namespace ts.BreakpointResolver {
function spanInOfKeyword(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.ForOfStatement) {
// set using next token
// Set using next token
return spanInNextNode(node);
}
@@ -723,4 +723,4 @@ namespace ts.BreakpointResolver {
}
}
}
}
}
+36 -30
View File
@@ -20,13 +20,13 @@ namespace ts.formatting {
Unknown = -1
}
/*
/*
* Indentation for the scope that can be dynamically recomputed.
* i.e
* i.e
* while(true)
* { let x;
* }
* Normally indentation is applied only to the first token in line so at glance 'var' should not be touched.
* Normally indentation is applied only to the first token in line so at glance 'var' should not be touched.
* However if some format rule adds new line between '}' and 'var' 'var' will become
* the first token in line so it should be indented
*/
@@ -48,15 +48,15 @@ namespace ts.formatting {
* foo(bar({
* $
* }))
* Both 'foo', 'bar' introduce new indentation with delta = 4, but total indentation in $ is not 8.
* Both 'foo', 'bar' introduce new indentation with delta = 4, but total indentation in $ is not 8.
* foo: { indentation: 0, delta: 4 }
* bar: { indentation: foo.indentation + foo.delta = 4, delta: 4} however 'foo' and 'bar' are on the same line
* so bar inherits indentation from foo and bar.delta will be 4
*
*
*/
getDelta(child: TextRangeWithKind): number;
/**
* Formatter calls this function when rule adds or deletes new lines from the text
* Formatter calls this function when rule adds or deletes new lines from the text
* so indentation scope can adjust values of indentation and delta.
*/
recomputeIndentation(lineAddedByFormatting: boolean): void;
@@ -130,9 +130,9 @@ namespace ts.formatting {
function findOutermostParent(position: number, expectedTokenKind: SyntaxKind, sourceFile: SourceFile): Node {
let precedingToken = findPrecedingToken(position, sourceFile);
// when it is claimed that trigger character was typed at given position
// when it is claimed that trigger character was typed at given position
// we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed).
// If this condition is not hold - then trigger character was typed in some other context,
// If this condition is not hold - then trigger character was typed in some other context,
// i.e.in comment and thus should not trigger autoformatting
if (!precedingToken ||
precedingToken.kind !== expectedTokenKind ||
@@ -142,12 +142,12 @@ namespace ts.formatting {
// walk up and search for the parent node that ends at the same position with precedingToken.
// for cases like this
//
//
// let x = 1;
// while (true) {
// }
// }
// after typing close curly in while statement we want to reformat just the while statement.
// However if we just walk upwards searching for the parent that has the same end value -
// However if we just walk upwards searching for the parent that has the same end value -
// we'll end up with the whole source file. isListElement allows to stop on the list element level
let current = precedingToken;
while (current &&
@@ -223,7 +223,7 @@ namespace ts.formatting {
// 'index' tracks the index of the most recent error that was checked.
while (true) {
if (index >= sorted.length) {
// all errors in the range were already checked -> no error in specified range
// all errors in the range were already checked -> no error in specified range
return false;
}
@@ -249,7 +249,7 @@ namespace ts.formatting {
/**
* Start of the original range might fall inside the comment - scanner will not yield appropriate results
* This function will look for token that is located before the start of target range
* This function will look for token that is located before the start of target range
* and return its end as start position for the scanner.
*/
function getScanStartPosition(enclosingNode: Node, originalRange: TextRange, sourceFile: SourceFile): number {
@@ -274,7 +274,7 @@ namespace ts.formatting {
}
/*
* For cases like
* For cases like
* if (a ||
* b ||$
* c) {...}
@@ -284,8 +284,8 @@ namespace ts.formatting {
* Initial indentation for this node will be 0.
* Binary expressions don't introduce new indentation scopes, however it is possible
* that some parent node on the same line does - like if statement in this case.
* Note that we are considering parents only from the same line with initial node -
* if parent is on the different line - its delta was already contributed
* Note that we are considering parents only from the same line with initial node -
* if parent is on the different line - its delta was already contributed
* to the initial indentation.
*/
function getOwnOrInheritedDelta(n: Node, options: FormatCodeOptions, sourceFile: SourceFile): number {
@@ -364,10 +364,10 @@ namespace ts.formatting {
// local functions
/** Tries to compute the indentation for a list element.
* If list element is not in range then
* function will pick its actual indentation
* If list element is not in range then
* function will pick its actual indentation
* so it can be pushed downstream as inherited indentation.
* If list element is in the range - its indentation will be equal
* If list element is in the range - its indentation will be equal
* to inherited indentation from its predecessors.
*/
function tryComputeIndentationForListItem(startPos: number,
@@ -378,7 +378,7 @@ namespace ts.formatting {
if (rangeOverlapsWithStartEnd(range, startPos, endPos) ||
rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
if (inheritedIndentation !== Constants.Unknown) {
return inheritedIndentation;
}
@@ -529,12 +529,12 @@ namespace ts.formatting {
// a useful observations when tracking context node
// /
// [a]
// / | \
// / | \
// [b] [c] [d]
// node 'a' is a context node for nodes 'b', 'c', 'd'
// node 'a' is a context node for nodes 'b', 'c', 'd'
// except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
// this rule can be applied recursively to child nodes of 'a'.
//
//
// context node is set to parent node value after processing every child node
// context node is set to parent of the token after processing every token
@@ -567,7 +567,8 @@ namespace ts.formatting {
parentDynamicIndentation: DynamicIndentation,
parentStartLine: number,
undecoratedParentStartLine: number,
isListItem: boolean): number {
isListItem: boolean,
isFirstListItem?: boolean): number {
let childStartPos = child.getStart(sourceFile);
@@ -626,6 +627,10 @@ namespace ts.formatting {
childContextNode = node;
if (isFirstListItem && parent.kind === SyntaxKind.ArrayLiteralExpression && inheritedIndentation === Constants.Unknown) {
inheritedIndentation = childIndentation.indentation;
}
return inheritedIndentation;
}
@@ -665,8 +670,9 @@ namespace ts.formatting {
}
let inheritedIndentation = Constants.Unknown;
for (let child of nodes) {
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true)
for (let i = 0; i < nodes.length; i++) {
const child = nodes[i];
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true, /*isFirstListItem*/ i === 0);
}
if (listEndToken !== SyntaxKind.Unknown) {
@@ -674,7 +680,7 @@ namespace ts.formatting {
let tokenInfo = formattingScanner.readTokenInfo(parent);
// consume the list end token only if it is still belong to the parent
// there might be the case when current token matches end token but does not considered as one
// function (x: function) <--
// function (x: function) <--
// without this check close paren will be interpreted as list end token for function expression which is wrong
if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) {
// consume list end token
@@ -733,7 +739,7 @@ namespace ts.formatting {
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
for (let triviaItem of currentTokenInfo.leadingTrivia) {
const triviaInRange = rangeContainsRange(originalRange, triviaItem);
const triviaInRange = rangeContainsRange(originalRange, triviaItem);
switch (triviaItem.kind) {
case SyntaxKind.MultiLineCommentTrivia:
if (triviaInRange) {
@@ -826,7 +832,7 @@ namespace ts.formatting {
if (rule.Operation.Action & (RuleAction.Space | RuleAction.Delete) && currentStartLine !== previousStartLine) {
lineAdded = false;
// Handle the case where the next line is moved to be the end of this line.
// Handle the case where the next line is moved to be the end of this line.
// In this case we don't indent the next line in the next pass.
if (currentParent.getStart(sourceFile) === currentItem.pos) {
dynamicIndentation.recomputeIndentation(/*lineAdded*/ false);
@@ -834,7 +840,7 @@ namespace ts.formatting {
}
else if (rule.Operation.Action & RuleAction.NewLine && currentStartLine === previousStartLine) {
lineAdded = true;
// Handle the case where token2 is moved to the new line.
// Handle the case where token2 is moved to the new line.
// In this case we indent token2 in the next pass but we set
// sameLineIndent flag to notify the indenter that the indentation is within the line.
if (currentParent.getStart(sourceFile) === currentItem.pos) {
+14 -1
View File
@@ -2,7 +2,7 @@
namespace ts.NavigateTo {
type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration };
export function getNavigateToItems(program: Program, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[] {
export function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[] {
const patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
@@ -49,6 +49,19 @@ namespace ts.NavigateTo {
}
});
// Remove imports when the imported declaration is already in the list and has the same name.
rawItems = filter(rawItems, item => {
const decl = item.declaration;
if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) {
const importer = checker.getSymbolAtLocation(decl.name);
const imported = checker.getAliasedSymbol(importer);
return importer.name !== imported.name;
}
else {
return true;
}
});
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
rawItems = rawItems.slice(0, maxResultCount);
+49 -36
View File
@@ -46,7 +46,7 @@ namespace ts.NavigationBar {
}
function getChildNodes(nodes: Node[]): Node[] {
let childNodes: Node[] = [];
const childNodes: Node[] = [];
function visit(node: Node) {
switch (node.kind) {
@@ -109,7 +109,7 @@ namespace ts.NavigationBar {
}
}
//for (let i = 0, n = nodes.length; i < n; i++) {
// for (let i = 0, n = nodes.length; i < n; i++) {
// let node = nodes[i];
// if (node.kind === SyntaxKind.ClassDeclaration ||
@@ -123,13 +123,13 @@ namespace ts.NavigationBar {
// else if (node.kind === SyntaxKind.VariableStatement) {
// childNodes.push.apply(childNodes, (<VariableStatement>node).declarations);
// }
//}
// }
forEach(nodes, visit);
return sortNodes(childNodes);
}
function getTopLevelNodes(node: SourceFile): Node[] {
let topLevelNodes: Node[] = [];
const topLevelNodes: Node[] = [];
topLevelNodes.push(node);
addTopLevelNodes(node.statements, topLevelNodes);
@@ -157,7 +157,7 @@ namespace ts.NavigationBar {
function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void {
nodes = sortNodes(nodes);
for (let node of nodes) {
for (const node of nodes) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
topLevelNodes.push(node);
@@ -176,6 +176,7 @@ namespace ts.NavigationBar {
break;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
topLevelNodes.push(node);
break;
@@ -197,7 +198,7 @@ namespace ts.NavigationBar {
}
function hasNamedFunctionDeclarations(nodes: NodeArray<Statement>): boolean {
for (let s of nodes) {
for (const s of nodes) {
if (s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text)) {
return true;
}
@@ -237,17 +238,17 @@ namespace ts.NavigationBar {
}
function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] {
let items: ts.NavigationBarItem[] = [];
const items: ts.NavigationBarItem[] = [];
let keyToItem: Map<NavigationBarItem> = {};
const keyToItem: Map<NavigationBarItem> = {};
for (let child of nodes) {
let item = createItem(child);
for (const child of nodes) {
const item = createItem(child);
if (item !== undefined) {
if (item.text.length > 0) {
let key = item.text + "-" + item.kind + "-" + item.indent;
const key = item.text + "-" + item.kind + "-" + item.indent;
let itemWithSameName = keyToItem[key];
const itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
merge(itemWithSameName, item);
@@ -274,8 +275,8 @@ namespace ts.NavigationBar {
// Next, recursively merge or add any children in the source as appropriate.
outer:
for (let sourceChild of source.childItems) {
for (let targetChild of target.childItems) {
for (const sourceChild of source.childItems) {
for (const targetChild of target.childItems) {
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
merge(targetChild, sourceChild);
@@ -382,7 +383,7 @@ namespace ts.NavigationBar {
return !text || text.trim() === "";
}
function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TextSpan[], childItems: NavigationBarItem[] = [], indent: number = 0): NavigationBarItem {
function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TextSpan[], childItems: NavigationBarItem[] = [], indent = 0): NavigationBarItem {
if (isEmpty(text)) {
return undefined;
}
@@ -422,6 +423,9 @@ namespace ts.NavigationBar {
case SyntaxKind.FunctionDeclaration:
return createFunctionItem(<FunctionDeclaration>node);
case SyntaxKind.TypeAliasDeclaration:
return createTypeAliasItem(<TypeAliasDeclaration>node);
}
return undefined;
@@ -433,7 +437,7 @@ namespace ts.NavigationBar {
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
let result: string[] = [];
const result: string[] = [];
result.push(moduleDeclaration.name.text);
@@ -447,9 +451,9 @@ namespace ts.NavigationBar {
}
function createModuleItem(node: ModuleDeclaration): NavigationBarItem {
let moduleName = getModuleName(node);
const moduleName = getModuleName(node);
let childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
const childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
return getNavigationBarItem(moduleName,
ts.ScriptElementKind.moduleElement,
@@ -461,9 +465,9 @@ namespace ts.NavigationBar {
function createFunctionItem(node: FunctionDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
const childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
return getNavigationBarItem(!node.name ? "default": node.name.text,
return getNavigationBarItem(!node.name ? "default" : node.name.text,
ts.ScriptElementKind.functionElement,
getNodeModifiers(node),
[getNodeSpan(node)],
@@ -474,9 +478,18 @@ namespace ts.NavigationBar {
return undefined;
}
function createTypeAliasItem(node: TypeAliasDeclaration): ts.NavigationBarItem {
return getNavigationBarItem(node.name.text,
ts.ScriptElementKind.typeElement,
getNodeModifiers(node),
[getNodeSpan(node)],
[],
getIndent(node));
}
function createMemberFunctionLikeItem(node: MethodDeclaration | ConstructorDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
const childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
let scriptElementKind: string;
let memberFunctionName: string;
if (node.kind === SyntaxKind.MethodDeclaration) {
@@ -500,16 +513,16 @@ namespace ts.NavigationBar {
}
function createSourceFileItem(node: SourceFile): ts.NavigationBarItem {
let childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
const childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
let rootName = isExternalModule(node)
const rootName = isExternalModule(node)
? "\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(node.fileName)))) + "\""
: "<global>"
: "<global>";
return getNavigationBarItem(rootName,
ts.ScriptElementKind.moduleElement,
@@ -522,14 +535,14 @@ namespace ts.NavigationBar {
let childItems: NavigationBarItem[];
if (node.members) {
let constructor = <ConstructorDeclaration>forEach(node.members, member => {
const constructor = <ConstructorDeclaration>forEach(node.members, member => {
return member.kind === SyntaxKind.Constructor && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
let nodes: Node[] = removeDynamicallyNamedProperties(node);
const nodes: Node[] = removeDynamicallyNamedProperties(node);
if (constructor) {
addRange(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
}
@@ -537,7 +550,7 @@ namespace ts.NavigationBar {
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name ? "default" : node.name.text;
const nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(
nodeName,
@@ -549,7 +562,7 @@ namespace ts.NavigationBar {
}
function createEnumItem(node: EnumDeclaration): ts.NavigationBarItem {
let childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
const childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.enumElement,
@@ -560,7 +573,7 @@ namespace ts.NavigationBar {
}
function createInterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem {
let childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
const childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.interfaceElement,
@@ -578,7 +591,7 @@ namespace ts.NavigationBar {
/**
* Like removeComputedProperties, but retains the properties with well known symbol names
*/
function removeDynamicallyNamedProperties(node: ClassDeclaration | InterfaceDeclaration): Declaration[]{
function removeDynamicallyNamedProperties(node: ClassDeclaration | InterfaceDeclaration): Declaration[] {
return filter<Declaration>(node.members, member => !hasDynamicName(member));
}
@@ -606,11 +619,11 @@ namespace ts.NavigationBar {
const anonClassText = "<class>";
let indent = 0;
let rootName = isExternalModule(sourceFile) ?
const rootName = isExternalModule(sourceFile) ?
"\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName)))) + "\""
: "<global>";
let sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]);
const sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]);
let topItem = sourceFileItem;
// Walk the whole file, because we want to also find function expressions - which may be in variable initializer,
@@ -643,12 +656,12 @@ namespace ts.NavigationBar {
}
}
function createNavBarItem(node: Node) : NavigationBarItem {
function createNavBarItem(node: Node): NavigationBarItem {
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
// Only add to the navbar if at the top-level of the file
// Note: "const" and "let" are also SyntaxKind.VariableDeclarations
if(node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/
if (node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/
.parent/*SourceFile*/.kind !== SyntaxKind.SourceFile) {
return undefined;
}
@@ -711,7 +724,7 @@ namespace ts.NavigationBar {
function getNavBarItem(text: string, kind: string, spans: TextSpan[], kindModifiers = ScriptElementKindModifier.none): NavigationBarItem {
return {
text, kind, kindModifiers, spans, childItems: [], indent, bolded: false, grayed: false
}
};
}
function getDefineModuleItem(node: Node): NavigationBarItem {
@@ -724,7 +737,7 @@ namespace ts.NavigationBar {
return undefined;
}
const callExpr = node.parent as CallExpression;
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== 'define') {
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== "define") {
return undefined;
}
+76 -66
View File
@@ -50,6 +50,7 @@ namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
export interface Signature {
@@ -735,6 +736,9 @@ namespace ts {
? this.checker.getBaseTypes(<InterfaceType><Type>this)
: undefined;
}
getNonNullableType(): Type {
return this.checker.getNonNullableType(this);
}
}
class SignatureObject implements Signature {
@@ -904,6 +908,7 @@ namespace ts {
function visit(node: Node): void {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
const functionDeclaration = <FunctionLikeDeclaration>node;
@@ -930,6 +935,7 @@ namespace ts {
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.EnumDeclaration:
@@ -944,34 +950,25 @@ namespace ts {
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeLiteral:
addDeclaration(<Declaration>node);
// fall through
case SyntaxKind.Constructor:
case SyntaxKind.VariableStatement:
case SyntaxKind.VariableDeclarationList:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ModuleBlock:
forEachChild(node, visit);
break;
case SyntaxKind.Block:
if (isFunctionBlock(node)) {
forEachChild(node, visit);
}
break;
case SyntaxKind.Parameter:
// Only consider properties defined as constructor parameters
if (!(node.flags & NodeFlags.AccessibilityModifier)) {
// Only consider parameter properties
if (!(node.flags & NodeFlags.ParameterPropertyModifier)) {
break;
}
// fall through
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
if (isBindingPattern((<VariableDeclaration>node).name)) {
forEachChild((<VariableDeclaration>node).name, visit);
case SyntaxKind.BindingElement: {
const decl = <VariableDeclaration> node;
if (isBindingPattern(decl.name)) {
forEachChild(decl.name, visit);
break;
}
if (decl.initializer)
visit(decl.initializer);
}
case SyntaxKind.EnumMember:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
@@ -1008,6 +1005,9 @@ namespace ts {
}
}
break;
default:
forEachChild(node, visit);
}
}
}
@@ -1542,68 +1542,74 @@ namespace ts {
export const unknown = "";
export const warning = "warning";
// predefined type (void) or keyword (class)
/** predefined type (void) or keyword (class) */
export const keyword = "keyword";
// top level script node
/** top level script node */
export const scriptElement = "script";
// module foo {}
/** module foo {} */
export const moduleElement = "module";
// class X {}
/** class X {} */
export const classElement = "class";
// var x = class X {}
/** var x = class X {} */
export const localClassElement = "local class";
// interface Y {}
/** interface Y {} */
export const interfaceElement = "interface";
// type T = ...
/** type T = ... */
export const typeElement = "type";
// enum E
/** enum E */
export const enumElement = "enum";
// Inside module and script only
// const v = ..
/**
* Inside module and script only
* const v = ..
*/
export const variableElement = "var";
// Inside function
/** Inside function */
export const localVariableElement = "local var";
// Inside module and script only
// function f() { }
/**
* Inside module and script only
* function f() { }
*/
export const functionElement = "function";
// Inside function
/** Inside function */
export const localFunctionElement = "local function";
// class X { [public|private]* foo() {} }
/** class X { [public|private]* foo() {} } */
export const memberFunctionElement = "method";
// class X { [public|private]* [get|set] foo:number; }
/** class X { [public|private]* [get|set] foo:number; } */
export const memberGetAccessorElement = "getter";
export const memberSetAccessorElement = "setter";
// class X { [public|private]* foo:number; }
// interface Y { foo:number; }
/**
* class X { [public|private]* foo:number; }
* interface Y { foo:number; }
*/
export const memberVariableElement = "property";
// class X { constructor() { } }
/** class X { constructor() { } } */
export const constructorImplementationElement = "constructor";
// interface Y { ():number; }
/** interface Y { ():number; } */
export const callSignatureElement = "call";
// interface Y { []:number; }
/** interface Y { []:number; } */
export const indexSignatureElement = "index";
// interface Y { new():Y; }
/** interface Y { new():Y; } */
export const constructSignatureElement = "construct";
// function foo(*Y*: string)
/** function foo(*Y*: string) */
export const parameterElement = "parameter";
export const typeParameterElement = "type parameter";
@@ -2770,7 +2776,9 @@ namespace ts {
/* @internal */ export function getNodeKind(node: Node): string {
switch (node.kind) {
case SyntaxKind.ModuleDeclaration: return ScriptElementKind.moduleElement;
case SyntaxKind.ClassDeclaration: return ScriptElementKind.classElement;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return ScriptElementKind.classElement;
case SyntaxKind.InterfaceDeclaration: return ScriptElementKind.interfaceElement;
case SyntaxKind.TypeAliasDeclaration: return ScriptElementKind.typeElement;
case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement;
@@ -2780,7 +2788,9 @@ namespace ts {
: isLet(node)
? ScriptElementKind.letElement
: ScriptElementKind.variableElement;
case SyntaxKind.FunctionDeclaration: return ScriptElementKind.functionElement;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
return ScriptElementKind.functionElement;
case SyntaxKind.GetAccessor: return ScriptElementKind.memberGetAccessorElement;
case SyntaxKind.SetAccessor: return ScriptElementKind.memberSetAccessorElement;
case SyntaxKind.MethodDeclaration:
@@ -2795,7 +2805,7 @@ namespace ts {
case SyntaxKind.Constructor: return ScriptElementKind.constructorImplementationElement;
case SyntaxKind.TypeParameter: return ScriptElementKind.typeParameterElement;
case SyntaxKind.EnumMember: return ScriptElementKind.variableElement;
case SyntaxKind.Parameter: return (node.flags & NodeFlags.AccessibilityModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement;
case SyntaxKind.Parameter: return (node.flags & NodeFlags.ParameterPropertyModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement;
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ImportClause:
@@ -4366,7 +4376,7 @@ namespace ts {
(location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration
// get the signature from the declaration and write it
const functionDeclaration = <FunctionLikeDeclaration>location.parent;
const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getConstructSignatures() : type.getCallSignatures();
const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
if (!typeChecker.isImplementationOfOverload(functionDeclaration)) {
signature = typeChecker.getSignatureFromDeclaration(functionDeclaration);
}
@@ -4564,7 +4574,7 @@ namespace ts {
symbolFlags & SymbolFlags.Signature ||
symbolFlags & SymbolFlags.Accessor ||
symbolKind === ScriptElementKind.memberFunctionElement) {
const allSignatures = type.getCallSignatures();
const allSignatures = type.getNonNullableType().getCallSignatures();
addSignatureDisplayParts(allSignatures[0], allSignatures);
}
}
@@ -4645,7 +4655,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -4802,18 +4812,6 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
// Labels
if (isJumpStatementTarget(node)) {
const labelName = (<Identifier>node).text;
const label = getTargetLabel((<BreakOrContinueStatement>node.parent), (<Identifier>node).text);
return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
}
/// Triple slash reference comments
const comment = findReferenceInPosition(sourceFile.referencedFiles, position);
if (comment) {
@@ -4823,6 +4821,7 @@ namespace ts {
}
return undefined;
}
// Type reference directives
const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
@@ -4833,6 +4832,18 @@ namespace ts {
return undefined;
}
const node = getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
return undefined;
}
// Labels
if (isJumpStatementTarget(node)) {
const labelName = (<Identifier>node).text;
const label = getTargetLabel((<BreakOrContinueStatement>node.parent), (<Identifier>node).text);
return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
}
const typeChecker = program.getTypeChecker();
let symbol = typeChecker.getSymbolAtLocation(node);
@@ -4891,7 +4902,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -4941,8 +4952,7 @@ namespace ts {
function getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
synchronizeHostData();
filesToSearch = map(filesToSearch, normalizeSlashes);
const sourceFilesToSearch = filter(program.getSourceFiles(), f => contains(filesToSearch, f.fileName));
const sourceFilesToSearch = map(filesToSearch, f => program.getSourceFile(f));
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingWord(sourceFile, position);
@@ -5628,7 +5638,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -6596,8 +6606,8 @@ namespace ts {
/// NavigateTo
function getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[] {
synchronizeHostData();
return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount);
const checker = getProgram().getTypeChecker();
return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount);
}
function getEmitOutput(fileName: string): EmitOutput {
@@ -6795,7 +6805,7 @@ namespace ts {
// Get node at the location
const node = getTouchingPropertyName(sourceFile, startPos);
if (!node) {
if (node === sourceFile) {
return;
}
+7 -7
View File
@@ -370,7 +370,7 @@ namespace ts {
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
return candidate && findRightmostToken(candidate)
return candidate && findRightmostToken(candidate);
}
else {
// candidate should be in this node
@@ -490,8 +490,8 @@ namespace ts {
return forEach(commentRanges, jsDocPrefix);
function jsDocPrefix(c: CommentRange): boolean {
var text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === '/' && text[c.pos + 1] === '*' && text[c.pos + 2] === '*';
const text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*";
}
}
@@ -546,7 +546,7 @@ namespace ts {
if (flags & NodeFlags.Export) result.push(ScriptElementKindModifier.exportedModifier);
if (isInAmbientContext(node)) result.push(ScriptElementKindModifier.ambientModifier);
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
return result.length > 0 ? result.join(",") : ScriptElementKindModifier.none;
}
export function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node> {
@@ -629,7 +629,7 @@ namespace ts {
// [a,b,c] from:
// [a, b, c] = someExpression;
if (node.parent.kind === SyntaxKind.BinaryExpression &&
(<BinaryExpression>node.parent).left === node &&
(<BinaryExpression>node.parent).left === node &&
(<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.EqualsToken) {
return true;
}
@@ -711,7 +711,7 @@ namespace ts {
}
function resetWriter() {
displayParts = []
displayParts = [];
lineStart = true;
indent = 0;
}
@@ -768,7 +768,7 @@ namespace ts {
}
export function textOrKeywordPart(text: string) {
var kind = stringToToken(text);
const kind = stringToToken(text);
return kind === undefined
? textPart(text)
: keywordPart(kind);
@@ -1,26 +0,0 @@
tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts(4,6): error TS1112: A class member cannot be declared optional.
tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts(5,6): error TS1112: A class member cannot be declared optional.
tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts(9,6): error TS1112: A class member cannot be declared optional.
tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts(10,6): error TS1112: A class member cannot be declared optional.
==== tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts (4 errors) ====
// classes do not permit optional parameters, these are errors
class C {
x?: string;
~
!!! error TS1112: A class member cannot be declared optional.
f?() {}
~
!!! error TS1112: A class member cannot be declared optional.
}
class C2<T> {
x?: T;
~
!!! error TS1112: A class member cannot be declared optional.
f?(x: T) {}
~
!!! error TS1112: A class member cannot be declared optional.
}
@@ -0,0 +1,26 @@
=== tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts ===
// classes do not permit optional parameters, these are errors
class C {
>C : Symbol(C, Decl(classWithOptionalParameter.ts, 0, 0))
x?: string;
>x : Symbol(C.x, Decl(classWithOptionalParameter.ts, 2, 9))
f?() {}
>f : Symbol(C.f, Decl(classWithOptionalParameter.ts, 3, 15))
}
class C2<T> {
>C2 : Symbol(C2, Decl(classWithOptionalParameter.ts, 5, 1))
>T : Symbol(T, Decl(classWithOptionalParameter.ts, 7, 9))
x?: T;
>x : Symbol(C2.x, Decl(classWithOptionalParameter.ts, 7, 13))
>T : Symbol(T, Decl(classWithOptionalParameter.ts, 7, 9))
f?(x: T) {}
>f : Symbol(C2.f, Decl(classWithOptionalParameter.ts, 8, 10))
>x : Symbol(x, Decl(classWithOptionalParameter.ts, 9, 7))
>T : Symbol(T, Decl(classWithOptionalParameter.ts, 7, 9))
}
@@ -0,0 +1,26 @@
=== tests/cases/conformance/types/namedTypes/classWithOptionalParameter.ts ===
// classes do not permit optional parameters, these are errors
class C {
>C : C
x?: string;
>x : string
f?() {}
>f : () => void
}
class C2<T> {
>C2 : C2<T>
>T : T
x?: T;
>x : T
>T : T
f?(x: T) {}
>f : (x: T) => void
>x : T
>T : T
}
@@ -247,7 +247,7 @@ export declare class ConstructorWithPrivateParameterProperty {
constructor(x: string);
}
export declare class ConstructorWithOptionalParameterProperty {
x: string;
x?: string;
constructor(x?: string);
}
export declare class ConstructorWithParameterInitializer {
@@ -281,7 +281,7 @@ declare class GlobalConstructorWithPrivateParameterProperty {
constructor(x: string);
}
declare class GlobalConstructorWithOptionalParameterProperty {
x: string;
x?: string;
constructor(x?: string);
}
declare class GlobalConstructorWithParameterInitializer {
@@ -0,0 +1,59 @@
//// [destructureOptionalParameter.ts]
declare function f1({ a, b }?: { a: number, b: string }): void;
function f2({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) {
a;
b;
}
// Repro from #8681
interface Type { t: void }
interface QueryMetadata { q: void }
interface QueryMetadataFactory {
(selector: Type | string, {descendants, read}?: {
descendants?: boolean;
read?: any;
}): ParameterDecorator;
new (selector: Type | string, {descendants, read}?: {
descendants?: boolean;
read?: any;
}): QueryMetadata;
}
//// [destructureOptionalParameter.js]
function f2(_a) {
var _b = _a === void 0 ? { a: 0, b: 0 } : _a, a = _b.a, b = _b.b;
a;
b;
}
//// [destructureOptionalParameter.d.ts]
declare function f1({a, b}?: {
a: number;
b: string;
}): void;
declare function f2({a, b}?: {
a: number;
b: number;
}): void;
interface Type {
t: void;
}
interface QueryMetadata {
q: void;
}
interface QueryMetadataFactory {
(selector: Type | string, {descendants, read}?: {
descendants?: boolean;
read?: any;
}): ParameterDecorator;
new (selector: Type | string, {descendants, read}?: {
descendants?: boolean;
read?: any;
}): QueryMetadata;
}
@@ -0,0 +1,69 @@
=== tests/cases/compiler/destructureOptionalParameter.ts ===
declare function f1({ a, b }?: { a: number, b: string }): void;
>f1 : Symbol(f1, Decl(destructureOptionalParameter.ts, 0, 0))
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 1, 21))
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 1, 24))
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 1, 32))
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 1, 43))
function f2({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) {
>f2 : Symbol(f2, Decl(destructureOptionalParameter.ts, 1, 63))
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 3, 13))
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 3, 16))
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 3, 23))
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 3, 34))
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 3, 50))
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 3, 56))
a;
>a : Symbol(a, Decl(destructureOptionalParameter.ts, 3, 13))
b;
>b : Symbol(b, Decl(destructureOptionalParameter.ts, 3, 16))
}
// Repro from #8681
interface Type { t: void }
>Type : Symbol(Type, Decl(destructureOptionalParameter.ts, 6, 1))
>t : Symbol(Type.t, Decl(destructureOptionalParameter.ts, 10, 16))
interface QueryMetadata { q: void }
>QueryMetadata : Symbol(QueryMetadata, Decl(destructureOptionalParameter.ts, 10, 26))
>q : Symbol(QueryMetadata.q, Decl(destructureOptionalParameter.ts, 11, 25))
interface QueryMetadataFactory {
>QueryMetadataFactory : Symbol(QueryMetadataFactory, Decl(destructureOptionalParameter.ts, 11, 35))
(selector: Type | string, {descendants, read}?: {
>selector : Symbol(selector, Decl(destructureOptionalParameter.ts, 14, 5))
>Type : Symbol(Type, Decl(destructureOptionalParameter.ts, 6, 1))
>descendants : Symbol(descendants, Decl(destructureOptionalParameter.ts, 14, 31))
>read : Symbol(read, Decl(destructureOptionalParameter.ts, 14, 43))
descendants?: boolean;
>descendants : Symbol(descendants, Decl(destructureOptionalParameter.ts, 14, 53))
read?: any;
>read : Symbol(read, Decl(destructureOptionalParameter.ts, 15, 30))
}): ParameterDecorator;
>ParameterDecorator : Symbol(ParameterDecorator, Decl(lib.d.ts, --, --))
new (selector: Type | string, {descendants, read}?: {
>selector : Symbol(selector, Decl(destructureOptionalParameter.ts, 18, 9))
>Type : Symbol(Type, Decl(destructureOptionalParameter.ts, 6, 1))
>descendants : Symbol(descendants, Decl(destructureOptionalParameter.ts, 18, 35))
>read : Symbol(read, Decl(destructureOptionalParameter.ts, 18, 47))
descendants?: boolean;
>descendants : Symbol(descendants, Decl(destructureOptionalParameter.ts, 18, 57))
read?: any;
>read : Symbol(read, Decl(destructureOptionalParameter.ts, 19, 30))
}): QueryMetadata;
>QueryMetadata : Symbol(QueryMetadata, Decl(destructureOptionalParameter.ts, 10, 26))
}
@@ -0,0 +1,72 @@
=== tests/cases/compiler/destructureOptionalParameter.ts ===
declare function f1({ a, b }?: { a: number, b: string }): void;
>f1 : ({a, b}?: { a: number; b: string; } | undefined) => void
>a : number
>b : string
>a : number
>b : string
function f2({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) {
>f2 : ({a, b}?: { a: number; b: number; }) => void
>a : number
>b : number
>a : number
>b : number
>{ a: 0, b: 0 } : { a: number; b: number; }
>a : number
>0 : number
>b : number
>0 : number
a;
>a : number
b;
>b : number
}
// Repro from #8681
interface Type { t: void }
>Type : Type
>t : void
interface QueryMetadata { q: void }
>QueryMetadata : QueryMetadata
>q : void
interface QueryMetadataFactory {
>QueryMetadataFactory : QueryMetadataFactory
(selector: Type | string, {descendants, read}?: {
>selector : Type | string
>Type : Type
>descendants : boolean | undefined
>read : any
descendants?: boolean;
>descendants : boolean | undefined
read?: any;
>read : any
}): ParameterDecorator;
>ParameterDecorator : (target: Object, propertyKey: string | symbol, parameterIndex: number) => void
new (selector: Type | string, {descendants, read}?: {
>selector : Type | string
>Type : Type
>descendants : boolean | undefined
>read : any
descendants?: boolean;
>descendants : boolean | undefined
read?: any;
>read : any
}): QueryMetadata;
>QueryMetadata : QueryMetadata
}
@@ -0,0 +1,11 @@
tests/cases/compiler/doubleUnderStringLiteralAssignability.ts(2,5): error TS2322: Type '"no_dunder"' is not assignable to type '"__dunder"'.
==== tests/cases/compiler/doubleUnderStringLiteralAssignability.ts (1 errors) ====
var shouldBeOk: '__dunder' = '__dunder';
var bad: '__dunder' = 'no_dunder';
~~~
!!! error TS2322: Type '"no_dunder"' is not assignable to type '"__dunder"'.
var okok: '___thunder' = '___thunder';
var alsoOk: '_sunder' = '_sunder';
@@ -0,0 +1,12 @@
//// [doubleUnderStringLiteralAssignability.ts]
var shouldBeOk: '__dunder' = '__dunder';
var bad: '__dunder' = 'no_dunder';
var okok: '___thunder' = '___thunder';
var alsoOk: '_sunder' = '_sunder';
//// [doubleUnderStringLiteralAssignability.js]
var shouldBeOk = '__dunder';
var bad = 'no_dunder';
var okok = '___thunder';
var alsoOk = '_sunder';
@@ -0,0 +1,12 @@
tests/cases/compiler/excessPropertyErrorForFunctionTypes.ts(4,44): error TS2322: Type '{ a: number; c: number; d: number; }' is not assignable to type '{ a: number; c: number; } | (() => any)'.
Object literal may only specify known properties, and 'd' does not exist in type '{ a: number; c: number; } | (() => any)'.
==== tests/cases/compiler/excessPropertyErrorForFunctionTypes.ts (1 errors) ====
type FunctionType = () => any;
type DoesntWork = { a: number, c: number } | FunctionType;
let doesntWork: DoesntWork = { a: 1, c: 2, d: 3 }
~~~~
!!! error TS2322: Type '{ a: number; c: number; d: number; }' is not assignable to type '{ a: number; c: number; } | (() => any)'.
!!! error TS2322: Object literal may only specify known properties, and 'd' does not exist in type '{ a: number; c: number; } | (() => any)'.
@@ -0,0 +1,8 @@
//// [excessPropertyErrorForFunctionTypes.ts]
type FunctionType = () => any;
type DoesntWork = { a: number, c: number } | FunctionType;
let doesntWork: DoesntWork = { a: 1, c: 2, d: 3 }
//// [excessPropertyErrorForFunctionTypes.js]
var doesntWork = { a: 1, c: 2, d: 3 };
@@ -0,0 +1,30 @@
//// [fallbackToBindingPatternForTypeInference.ts]
declare function trans<T>(f: (x: T) => string): number;
trans(({a}) => a);
trans(([b,c]) => 'foo');
trans(({d: [e,f]}) => 'foo');
trans(([{g},{h}]) => 'foo');
trans(({a, b = 10}) => a);
//// [fallbackToBindingPatternForTypeInference.js]
trans(function (_a) {
var a = _a.a;
return a;
});
trans(function (_a) {
var b = _a[0], c = _a[1];
return 'foo';
});
trans(function (_a) {
var _b = _a.d, e = _b[0], f = _b[1];
return 'foo';
});
trans(function (_a) {
var g = _a[0].g, h = _a[1].h;
return 'foo';
});
trans(function (_a) {
var a = _a.a, _b = _a.b, b = _b === void 0 ? 10 : _b;
return a;
});
@@ -0,0 +1,34 @@
=== tests/cases/compiler/fallbackToBindingPatternForTypeInference.ts ===
declare function trans<T>(f: (x: T) => string): number;
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>T : Symbol(T, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 23))
>f : Symbol(f, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 26))
>x : Symbol(x, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 30))
>T : Symbol(T, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 23))
trans(({a}) => a);
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>a : Symbol(a, Decl(fallbackToBindingPatternForTypeInference.ts, 1, 8))
>a : Symbol(a, Decl(fallbackToBindingPatternForTypeInference.ts, 1, 8))
trans(([b,c]) => 'foo');
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>b : Symbol(b, Decl(fallbackToBindingPatternForTypeInference.ts, 2, 8))
>c : Symbol(c, Decl(fallbackToBindingPatternForTypeInference.ts, 2, 10))
trans(({d: [e,f]}) => 'foo');
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>e : Symbol(e, Decl(fallbackToBindingPatternForTypeInference.ts, 3, 12))
>f : Symbol(f, Decl(fallbackToBindingPatternForTypeInference.ts, 3, 14))
trans(([{g},{h}]) => 'foo');
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>g : Symbol(g, Decl(fallbackToBindingPatternForTypeInference.ts, 4, 9))
>h : Symbol(h, Decl(fallbackToBindingPatternForTypeInference.ts, 4, 13))
trans(({a, b = 10}) => a);
>trans : Symbol(trans, Decl(fallbackToBindingPatternForTypeInference.ts, 0, 0))
>a : Symbol(a, Decl(fallbackToBindingPatternForTypeInference.ts, 5, 8))
>b : Symbol(b, Decl(fallbackToBindingPatternForTypeInference.ts, 5, 10))
>a : Symbol(a, Decl(fallbackToBindingPatternForTypeInference.ts, 5, 8))
@@ -0,0 +1,49 @@
=== tests/cases/compiler/fallbackToBindingPatternForTypeInference.ts ===
declare function trans<T>(f: (x: T) => string): number;
>trans : <T>(f: (x: T) => string) => number
>T : T
>f : (x: T) => string
>x : T
>T : T
trans(({a}) => a);
>trans(({a}) => a) : number
>trans : <T>(f: (x: T) => string) => number
>({a}) => a : ({a}: { a: any; }) => any
>a : any
>a : any
trans(([b,c]) => 'foo');
>trans(([b,c]) => 'foo') : number
>trans : <T>(f: (x: T) => string) => number
>([b,c]) => 'foo' : ([b, c]: [any, any]) => string
>b : any
>c : any
>'foo' : string
trans(({d: [e,f]}) => 'foo');
>trans(({d: [e,f]}) => 'foo') : number
>trans : <T>(f: (x: T) => string) => number
>({d: [e,f]}) => 'foo' : ({d: [e, f]}: { d: [any, any]; }) => string
>d : any
>e : any
>f : any
>'foo' : string
trans(([{g},{h}]) => 'foo');
>trans(([{g},{h}]) => 'foo') : number
>trans : <T>(f: (x: T) => string) => number
>([{g},{h}]) => 'foo' : ([{g}, {h}]: [{ g: any; }, { h: any; }]) => string
>g : any
>h : any
>'foo' : string
trans(({a, b = 10}) => a);
>trans(({a, b = 10}) => a) : number
>trans : <T>(f: (x: T) => string) => number
>({a, b = 10}) => a : ({a, b}: { a: any; b?: number; }) => any
>a : any
>b : number
>10 : number
>a : any
@@ -0,0 +1,31 @@
//// [genericInheritedDefaultConstructors.ts]
// repro from #8166
interface Constructor<T> {
new(...args: any[]): T;
prototype: T;
}
class A<U> { a: U; }
class B<V> extends A<V> { b: V; }
var c:Constructor<B<boolean>> = B; // shouldn't error here
//// [genericInheritedDefaultConstructors.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
}
return A;
}());
var B = (function (_super) {
__extends(B, _super);
function B() {
_super.apply(this, arguments);
}
return B;
}(A));
var c = B; // shouldn't error here
@@ -0,0 +1,35 @@
=== tests/cases/compiler/genericInheritedDefaultConstructors.ts ===
// repro from #8166
interface Constructor<T> {
>Constructor : Symbol(Constructor, Decl(genericInheritedDefaultConstructors.ts, 0, 0))
>T : Symbol(T, Decl(genericInheritedDefaultConstructors.ts, 1, 22))
new(...args: any[]): T;
>args : Symbol(args, Decl(genericInheritedDefaultConstructors.ts, 2, 8))
>T : Symbol(T, Decl(genericInheritedDefaultConstructors.ts, 1, 22))
prototype: T;
>prototype : Symbol(Constructor.prototype, Decl(genericInheritedDefaultConstructors.ts, 2, 27))
>T : Symbol(T, Decl(genericInheritedDefaultConstructors.ts, 1, 22))
}
class A<U> { a: U; }
>A : Symbol(A, Decl(genericInheritedDefaultConstructors.ts, 4, 1))
>U : Symbol(U, Decl(genericInheritedDefaultConstructors.ts, 6, 8))
>a : Symbol(A.a, Decl(genericInheritedDefaultConstructors.ts, 6, 12))
>U : Symbol(U, Decl(genericInheritedDefaultConstructors.ts, 6, 8))
class B<V> extends A<V> { b: V; }
>B : Symbol(B, Decl(genericInheritedDefaultConstructors.ts, 6, 20))
>V : Symbol(V, Decl(genericInheritedDefaultConstructors.ts, 7, 8))
>A : Symbol(A, Decl(genericInheritedDefaultConstructors.ts, 4, 1))
>V : Symbol(V, Decl(genericInheritedDefaultConstructors.ts, 7, 8))
>b : Symbol(B.b, Decl(genericInheritedDefaultConstructors.ts, 7, 25))
>V : Symbol(V, Decl(genericInheritedDefaultConstructors.ts, 7, 8))
var c:Constructor<B<boolean>> = B; // shouldn't error here
>c : Symbol(c, Decl(genericInheritedDefaultConstructors.ts, 8, 3))
>Constructor : Symbol(Constructor, Decl(genericInheritedDefaultConstructors.ts, 0, 0))
>B : Symbol(B, Decl(genericInheritedDefaultConstructors.ts, 6, 20))
>B : Symbol(B, Decl(genericInheritedDefaultConstructors.ts, 6, 20))
@@ -0,0 +1,35 @@
=== tests/cases/compiler/genericInheritedDefaultConstructors.ts ===
// repro from #8166
interface Constructor<T> {
>Constructor : Constructor<T>
>T : T
new(...args: any[]): T;
>args : any[]
>T : T
prototype: T;
>prototype : T
>T : T
}
class A<U> { a: U; }
>A : A<U>
>U : U
>a : U
>U : U
class B<V> extends A<V> { b: V; }
>B : B<V>
>V : V
>A : A<V>
>V : V
>b : V
>V : V
var c:Constructor<B<boolean>> = B; // shouldn't error here
>c : Constructor<B<boolean>>
>Constructor : Constructor<T>
>B : B<V>
>B : typeof B
@@ -133,8 +133,8 @@ function fn5(x: Derived1) {
// 1.5: y: Derived1
// Want: ???
let y = x;
>y : nothing
>x : nothing
>y : never
>x : never
}
}
@@ -0,0 +1,15 @@
//// [tests/cases/compiler/instantiateCrossFileMerge.ts] ////
//// [first.ts]
declare class P<R> {
constructor(callback: (resolve: (value: R) => void) => void);
}
//// [second.ts]
interface P<R> { }
new P<string>(r => { r('foo') });
//// [first.js]
//// [second.js]
new P(function (r) { r('foo'); });
@@ -0,0 +1,22 @@
=== tests/cases/compiler/first.ts ===
declare class P<R> {
>P : Symbol(P, Decl(first.ts, 0, 0), Decl(second.ts, 0, 0))
>R : Symbol(R, Decl(first.ts, 0, 16), Decl(second.ts, 0, 12))
constructor(callback: (resolve: (value: R) => void) => void);
>callback : Symbol(callback, Decl(first.ts, 1, 16))
>resolve : Symbol(resolve, Decl(first.ts, 1, 27))
>value : Symbol(value, Decl(first.ts, 1, 37))
>R : Symbol(R, Decl(first.ts, 0, 16), Decl(second.ts, 0, 12))
}
=== tests/cases/compiler/second.ts ===
interface P<R> { }
>P : Symbol(P, Decl(first.ts, 0, 0), Decl(second.ts, 0, 0))
>R : Symbol(R, Decl(first.ts, 0, 16), Decl(second.ts, 0, 12))
new P<string>(r => { r('foo') });
>P : Symbol(P, Decl(first.ts, 0, 0), Decl(second.ts, 0, 0))
>r : Symbol(r, Decl(second.ts, 1, 14))
>r : Symbol(r, Decl(second.ts, 1, 14))
@@ -0,0 +1,26 @@
=== tests/cases/compiler/first.ts ===
declare class P<R> {
>P : P<R>
>R : R
constructor(callback: (resolve: (value: R) => void) => void);
>callback : (resolve: (value: R) => void) => void
>resolve : (value: R) => void
>value : R
>R : R
}
=== tests/cases/compiler/second.ts ===
interface P<R> { }
>P : P<R>
>R : R
new P<string>(r => { r('foo') });
>new P<string>(r => { r('foo') }) : P<string>
>P : typeof P
>r => { r('foo') } : (r: (value: string) => void) => void
>r : (value: string) => void
>r('foo') : void
>r : (value: string) => void
>'foo' : string
@@ -26,6 +26,23 @@ type F2 = (x: number) => number;
var f: F1 & F2;
var s = f("hello");
var n = f(42);
interface D {
nested: { doublyNested: { d: string; }, different: { e: number } };
}
interface E {
nested: { doublyNested: { f: string; }, other: {g: number } };
}
const de: D & E = {
nested: {
doublyNested: {
d: 'yes',
f: 'no'
},
different: { e: 12 },
other: { g: 101 }
}
}
//// [intersectionTypeMembers.js]
@@ -42,3 +59,13 @@ xyz.x.c = "hello";
var f;
var s = f("hello");
var n = f(42);
var de = {
nested: {
doublyNested: {
d: 'yes',
f: 'no'
},
different: { e: 12 },
other: { g: 101 }
}
};
@@ -98,3 +98,51 @@ var n = f(42);
>n : Symbol(n, Decl(intersectionTypeMembers.ts, 26, 3))
>f : Symbol(f, Decl(intersectionTypeMembers.ts, 24, 3))
interface D {
>D : Symbol(D, Decl(intersectionTypeMembers.ts, 26, 14))
nested: { doublyNested: { d: string; }, different: { e: number } };
>nested : Symbol(D.nested, Decl(intersectionTypeMembers.ts, 28, 13))
>doublyNested : Symbol(doublyNested, Decl(intersectionTypeMembers.ts, 29, 13))
>d : Symbol(d, Decl(intersectionTypeMembers.ts, 29, 29))
>different : Symbol(different, Decl(intersectionTypeMembers.ts, 29, 43))
>e : Symbol(e, Decl(intersectionTypeMembers.ts, 29, 56))
}
interface E {
>E : Symbol(E, Decl(intersectionTypeMembers.ts, 30, 1))
nested: { doublyNested: { f: string; }, other: {g: number } };
>nested : Symbol(E.nested, Decl(intersectionTypeMembers.ts, 31, 13))
>doublyNested : Symbol(doublyNested, Decl(intersectionTypeMembers.ts, 32, 13))
>f : Symbol(f, Decl(intersectionTypeMembers.ts, 32, 29))
>other : Symbol(other, Decl(intersectionTypeMembers.ts, 32, 43))
>g : Symbol(g, Decl(intersectionTypeMembers.ts, 32, 52))
}
const de: D & E = {
>de : Symbol(de, Decl(intersectionTypeMembers.ts, 34, 5))
>D : Symbol(D, Decl(intersectionTypeMembers.ts, 26, 14))
>E : Symbol(E, Decl(intersectionTypeMembers.ts, 30, 1))
nested: {
>nested : Symbol(nested, Decl(intersectionTypeMembers.ts, 34, 19))
doublyNested: {
>doublyNested : Symbol(doublyNested, Decl(intersectionTypeMembers.ts, 35, 13))
d: 'yes',
>d : Symbol(d, Decl(intersectionTypeMembers.ts, 36, 23))
f: 'no'
>f : Symbol(f, Decl(intersectionTypeMembers.ts, 37, 21))
},
different: { e: 12 },
>different : Symbol(different, Decl(intersectionTypeMembers.ts, 39, 10))
>e : Symbol(e, Decl(intersectionTypeMembers.ts, 40, 20))
other: { g: 101 }
>other : Symbol(other, Decl(intersectionTypeMembers.ts, 40, 29))
>g : Symbol(g, Decl(intersectionTypeMembers.ts, 41, 16))
}
}
@@ -114,3 +114,60 @@ var n = f(42);
>f : ((x: string) => string) & ((x: number) => number)
>42 : number
interface D {
>D : D
nested: { doublyNested: { d: string; }, different: { e: number } };
>nested : { doublyNested: { d: string; }; different: { e: number; }; }
>doublyNested : { d: string; }
>d : string
>different : { e: number; }
>e : number
}
interface E {
>E : E
nested: { doublyNested: { f: string; }, other: {g: number } };
>nested : { doublyNested: { f: string; }; other: { g: number; }; }
>doublyNested : { f: string; }
>f : string
>other : { g: number; }
>g : number
}
const de: D & E = {
>de : D & E
>D : D
>E : E
>{ nested: { doublyNested: { d: 'yes', f: 'no' }, different: { e: 12 }, other: { g: 101 } }} : { nested: { doublyNested: { d: string; f: string; }; different: { e: number; }; other: { g: number; }; }; }
nested: {
>nested : { doublyNested: { d: string; f: string; }; different: { e: number; }; other: { g: number; }; }
>{ doublyNested: { d: 'yes', f: 'no' }, different: { e: 12 }, other: { g: 101 } } : { doublyNested: { d: string; f: string; }; different: { e: number; }; other: { g: number; }; }
doublyNested: {
>doublyNested : { d: string; f: string; }
>{ d: 'yes', f: 'no' } : { d: string; f: string; }
d: 'yes',
>d : string
>'yes' : string
f: 'no'
>f : string
>'no' : string
},
different: { e: 12 },
>different : { e: number; }
>{ e: 12 } : { e: number; }
>e : number
>12 : number
other: { g: 101 }
>other : { g: number; }
>{ g: 101 } : { g: number; }
>g : number
>101 : number
}
}
@@ -1,11 +1,14 @@
error TS5053: Option 'out' cannot be specified with option 'isolatedModules'.
tests/cases/compiler/file1.ts(2,1): error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
tests/cases/compiler/file2.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided.
!!! error TS5053: Option 'out' cannot be specified with option 'isolatedModules'.
==== tests/cases/compiler/file1.ts (0 errors) ====
==== tests/cases/compiler/file1.ts (1 errors) ====
export var x;
~~~~~~~~~~~~~
!!! error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
==== tests/cases/compiler/file2.ts (1 errors) ====
var y;
~~~
@@ -0,0 +1,16 @@
//// [json.stringify.ts]
var value = null;
JSON.stringify(value, undefined, 2);
JSON.stringify(value, null, 2);
JSON.stringify(value, ["a", 1], 2);
JSON.stringify(value, (k) => undefined, 2);
JSON.stringify(value, undefined, 2);
//// [json.stringify.js]
var value = null;
JSON.stringify(value, undefined, 2);
JSON.stringify(value, null, 2);
JSON.stringify(value, ["a", 1], 2);
JSON.stringify(value, function (k) { return undefined; }, 2);
JSON.stringify(value, undefined, 2);
@@ -0,0 +1,39 @@
=== tests/cases/compiler/json.stringify.ts ===
var value = null;
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
JSON.stringify(value, undefined, 2);
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
>undefined : Symbol(undefined)
JSON.stringify(value, null, 2);
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
JSON.stringify(value, ["a", 1], 2);
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
JSON.stringify(value, (k) => undefined, 2);
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
>k : Symbol(k, Decl(json.stringify.ts, 5, 23))
>undefined : Symbol(undefined)
JSON.stringify(value, undefined, 2);
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>value : Symbol(value, Decl(json.stringify.ts, 1, 3))
>undefined : Symbol(undefined)
@@ -0,0 +1,55 @@
=== tests/cases/compiler/json.stringify.ts ===
var value = null;
>value : null
>null : null
JSON.stringify(value, undefined, 2);
>JSON.stringify(value, undefined, 2) : string
>JSON.stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>JSON : JSON
>stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>value : null
>undefined : undefined
>2 : number
JSON.stringify(value, null, 2);
>JSON.stringify(value, null, 2) : string
>JSON.stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>JSON : JSON
>stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>value : null
>null : null
>2 : number
JSON.stringify(value, ["a", 1], 2);
>JSON.stringify(value, ["a", 1], 2) : string
>JSON.stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>JSON : JSON
>stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>value : null
>["a", 1] : (string | number)[]
>"a" : string
>1 : number
>2 : number
JSON.stringify(value, (k) => undefined, 2);
>JSON.stringify(value, (k) => undefined, 2) : string
>JSON.stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>JSON : JSON
>stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>value : null
>(k) => undefined : (k: string) => undefined
>k : string
>undefined : undefined
>2 : number
JSON.stringify(value, undefined, 2);
>JSON.stringify(value, undefined, 2) : string
>JSON.stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>JSON : JSON
>stringify : { (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (number | string)[] | null | undefined, space?: string | number | undefined): string; }
>value : null
>undefined : undefined
>2 : number
@@ -1,10 +1,10 @@
tests/cases/compiler/a.ts(1,14): error TS1148: Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
tests/cases/compiler/a.ts(1,14): error TS1148: Cannot use imports, exports, or module augmentations when '--module' is 'none'.
==== tests/cases/compiler/a.ts (1 errors) ====
export class Foo {
~~~
!!! error TS1148: Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.
!!! error TS1148: Cannot use imports, exports, or module augmentations when '--module' is 'none'.
foo: string;
}
+195
View File
@@ -0,0 +1,195 @@
//// [neverType.ts]
function error(message: string): never {
throw new Error(message);
}
function errorVoid(message: string) {
throw new Error(message);
}
function fail() {
return error("Something failed");
}
function failOrThrow(shouldFail: boolean) {
if (shouldFail) {
return fail();
}
throw new Error();
}
function infiniteLoop1() {
while (true) {
}
}
function infiniteLoop2(): never {
while (true) {
}
}
function move1(direction: "up" | "down") {
switch (direction) {
case "up":
return 1;
case "down":
return -1;
}
return error("Should never get here");
}
function move2(direction: "up" | "down") {
return direction === "up" ? 1 :
direction === "down" ? -1 :
error("Should never get here");
}
function check<T>(x: T | undefined) {
return x || error("Undefined value");
}
class C {
void1() {
throw new Error();
}
void2() {
while (true) {}
}
never1(): never {
throw new Error();
}
never2(): never {
while (true) {}
}
}
function f1(x: string | number) {
if (typeof x === "boolean") {
x; // never
}
}
function f2(x: string | number) {
while (true) {
if (typeof x === "boolean") {
return x; // never
}
}
}
function test(cb: () => string) {
let s = cb();
return s;
}
let errorCallback = () => error("Error callback");
test(() => "hello");
test(() => fail());
test(() => { throw new Error(); })
test(errorCallback);
//// [neverType.js]
function error(message) {
throw new Error(message);
}
function errorVoid(message) {
throw new Error(message);
}
function fail() {
return error("Something failed");
}
function failOrThrow(shouldFail) {
if (shouldFail) {
return fail();
}
throw new Error();
}
function infiniteLoop1() {
while (true) {
}
}
function infiniteLoop2() {
while (true) {
}
}
function move1(direction) {
switch (direction) {
case "up":
return 1;
case "down":
return -1;
}
return error("Should never get here");
}
function move2(direction) {
return direction === "up" ? 1 :
direction === "down" ? -1 :
error("Should never get here");
}
function check(x) {
return x || error("Undefined value");
}
var C = (function () {
function C() {
}
C.prototype.void1 = function () {
throw new Error();
};
C.prototype.void2 = function () {
while (true) { }
};
C.prototype.never1 = function () {
throw new Error();
};
C.prototype.never2 = function () {
while (true) { }
};
return C;
}());
function f1(x) {
if (typeof x === "boolean") {
x; // never
}
}
function f2(x) {
while (true) {
if (typeof x === "boolean") {
return x; // never
}
}
}
function test(cb) {
var s = cb();
return s;
}
var errorCallback = function () { return error("Error callback"); };
test(function () { return "hello"; });
test(function () { return fail(); });
test(function () { throw new Error(); });
test(errorCallback);
//// [neverType.d.ts]
declare function error(message: string): never;
declare function errorVoid(message: string): void;
declare function fail(): never;
declare function failOrThrow(shouldFail: boolean): never;
declare function infiniteLoop1(): void;
declare function infiniteLoop2(): never;
declare function move1(direction: "up" | "down"): number;
declare function move2(direction: "up" | "down"): number;
declare function check<T>(x: T | undefined): T;
declare class C {
void1(): void;
void2(): void;
never1(): never;
never2(): never;
}
declare function f1(x: string | number): void;
declare function f2(x: string | number): never;
declare function test(cb: () => string): string;
declare let errorCallback: () => never;
+181
View File
@@ -0,0 +1,181 @@
=== tests/cases/conformance/types/never/neverType.ts ===
function error(message: string): never {
>error : Symbol(error, Decl(neverType.ts, 0, 0))
>message : Symbol(message, Decl(neverType.ts, 2, 15))
throw new Error(message);
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>message : Symbol(message, Decl(neverType.ts, 2, 15))
}
function errorVoid(message: string) {
>errorVoid : Symbol(errorVoid, Decl(neverType.ts, 4, 1))
>message : Symbol(message, Decl(neverType.ts, 6, 19))
throw new Error(message);
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>message : Symbol(message, Decl(neverType.ts, 6, 19))
}
function fail() {
>fail : Symbol(fail, Decl(neverType.ts, 8, 1))
return error("Something failed");
>error : Symbol(error, Decl(neverType.ts, 0, 0))
}
function failOrThrow(shouldFail: boolean) {
>failOrThrow : Symbol(failOrThrow, Decl(neverType.ts, 12, 1))
>shouldFail : Symbol(shouldFail, Decl(neverType.ts, 14, 21))
if (shouldFail) {
>shouldFail : Symbol(shouldFail, Decl(neverType.ts, 14, 21))
return fail();
>fail : Symbol(fail, Decl(neverType.ts, 8, 1))
}
throw new Error();
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
function infiniteLoop1() {
>infiniteLoop1 : Symbol(infiniteLoop1, Decl(neverType.ts, 19, 1))
while (true) {
}
}
function infiniteLoop2(): never {
>infiniteLoop2 : Symbol(infiniteLoop2, Decl(neverType.ts, 24, 1))
while (true) {
}
}
function move1(direction: "up" | "down") {
>move1 : Symbol(move1, Decl(neverType.ts, 29, 1))
>direction : Symbol(direction, Decl(neverType.ts, 31, 15))
switch (direction) {
>direction : Symbol(direction, Decl(neverType.ts, 31, 15))
case "up":
return 1;
case "down":
return -1;
}
return error("Should never get here");
>error : Symbol(error, Decl(neverType.ts, 0, 0))
}
function move2(direction: "up" | "down") {
>move2 : Symbol(move2, Decl(neverType.ts, 39, 1))
>direction : Symbol(direction, Decl(neverType.ts, 41, 15))
return direction === "up" ? 1 :
>direction : Symbol(direction, Decl(neverType.ts, 41, 15))
direction === "down" ? -1 :
>direction : Symbol(direction, Decl(neverType.ts, 41, 15))
error("Should never get here");
>error : Symbol(error, Decl(neverType.ts, 0, 0))
}
function check<T>(x: T | undefined) {
>check : Symbol(check, Decl(neverType.ts, 45, 1))
>T : Symbol(T, Decl(neverType.ts, 47, 15))
>x : Symbol(x, Decl(neverType.ts, 47, 18))
>T : Symbol(T, Decl(neverType.ts, 47, 15))
return x || error("Undefined value");
>x : Symbol(x, Decl(neverType.ts, 47, 18))
>error : Symbol(error, Decl(neverType.ts, 0, 0))
}
class C {
>C : Symbol(C, Decl(neverType.ts, 49, 1))
void1() {
>void1 : Symbol(C.void1, Decl(neverType.ts, 51, 9))
throw new Error();
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
void2() {
>void2 : Symbol(C.void2, Decl(neverType.ts, 54, 5))
while (true) {}
}
never1(): never {
>never1 : Symbol(C.never1, Decl(neverType.ts, 57, 5))
throw new Error();
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}
never2(): never {
>never2 : Symbol(C.never2, Decl(neverType.ts, 60, 5))
while (true) {}
}
}
function f1(x: string | number) {
>f1 : Symbol(f1, Decl(neverType.ts, 64, 1))
>x : Symbol(x, Decl(neverType.ts, 66, 12))
if (typeof x === "boolean") {
>x : Symbol(x, Decl(neverType.ts, 66, 12))
x; // never
>x : Symbol(x, Decl(neverType.ts, 66, 12))
}
}
function f2(x: string | number) {
>f2 : Symbol(f2, Decl(neverType.ts, 70, 1))
>x : Symbol(x, Decl(neverType.ts, 72, 12))
while (true) {
if (typeof x === "boolean") {
>x : Symbol(x, Decl(neverType.ts, 72, 12))
return x; // never
>x : Symbol(x, Decl(neverType.ts, 72, 12))
}
}
}
function test(cb: () => string) {
>test : Symbol(test, Decl(neverType.ts, 78, 1))
>cb : Symbol(cb, Decl(neverType.ts, 80, 14))
let s = cb();
>s : Symbol(s, Decl(neverType.ts, 81, 7))
>cb : Symbol(cb, Decl(neverType.ts, 80, 14))
return s;
>s : Symbol(s, Decl(neverType.ts, 81, 7))
}
let errorCallback = () => error("Error callback");
>errorCallback : Symbol(errorCallback, Decl(neverType.ts, 85, 3))
>error : Symbol(error, Decl(neverType.ts, 0, 0))
test(() => "hello");
>test : Symbol(test, Decl(neverType.ts, 78, 1))
test(() => fail());
>test : Symbol(test, Decl(neverType.ts, 78, 1))
>fail : Symbol(fail, Decl(neverType.ts, 8, 1))
test(() => { throw new Error(); })
>test : Symbol(test, Decl(neverType.ts, 78, 1))
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
test(errorCallback);
>test : Symbol(test, Decl(neverType.ts, 78, 1))
>errorCallback : Symbol(errorCallback, Decl(neverType.ts, 85, 3))
+239
View File
@@ -0,0 +1,239 @@
=== tests/cases/conformance/types/never/neverType.ts ===
function error(message: string): never {
>error : (message: string) => never
>message : string
throw new Error(message);
>new Error(message) : Error
>Error : ErrorConstructor
>message : string
}
function errorVoid(message: string) {
>errorVoid : (message: string) => void
>message : string
throw new Error(message);
>new Error(message) : Error
>Error : ErrorConstructor
>message : string
}
function fail() {
>fail : () => never
return error("Something failed");
>error("Something failed") : never
>error : (message: string) => never
>"Something failed" : string
}
function failOrThrow(shouldFail: boolean) {
>failOrThrow : (shouldFail: boolean) => never
>shouldFail : boolean
if (shouldFail) {
>shouldFail : boolean
return fail();
>fail() : never
>fail : () => never
}
throw new Error();
>new Error() : Error
>Error : ErrorConstructor
}
function infiniteLoop1() {
>infiniteLoop1 : () => void
while (true) {
>true : boolean
}
}
function infiniteLoop2(): never {
>infiniteLoop2 : () => never
while (true) {
>true : boolean
}
}
function move1(direction: "up" | "down") {
>move1 : (direction: "up" | "down") => number
>direction : "up" | "down"
switch (direction) {
>direction : "up" | "down"
case "up":
>"up" : string
return 1;
>1 : number
case "down":
>"down" : string
return -1;
>-1 : number
>1 : number
}
return error("Should never get here");
>error("Should never get here") : never
>error : (message: string) => never
>"Should never get here" : string
}
function move2(direction: "up" | "down") {
>move2 : (direction: "up" | "down") => number
>direction : "up" | "down"
return direction === "up" ? 1 :
>direction === "up" ? 1 : direction === "down" ? -1 : error("Should never get here") : number
>direction === "up" : boolean
>direction : "up" | "down"
>"up" : string
>1 : number
direction === "down" ? -1 :
>direction === "down" ? -1 : error("Should never get here") : number
>direction === "down" : boolean
>direction : "up" | "down"
>"down" : string
>-1 : number
>1 : number
error("Should never get here");
>error("Should never get here") : never
>error : (message: string) => never
>"Should never get here" : string
}
function check<T>(x: T | undefined) {
>check : <T>(x: T | undefined) => T
>T : T
>x : T | undefined
>T : T
return x || error("Undefined value");
>x || error("Undefined value") : T
>x : T | undefined
>error("Undefined value") : never
>error : (message: string) => never
>"Undefined value" : string
}
class C {
>C : C
void1() {
>void1 : () => void
throw new Error();
>new Error() : Error
>Error : ErrorConstructor
}
void2() {
>void2 : () => void
while (true) {}
>true : boolean
}
never1(): never {
>never1 : () => never
throw new Error();
>new Error() : Error
>Error : ErrorConstructor
}
never2(): never {
>never2 : () => never
while (true) {}
>true : boolean
}
}
function f1(x: string | number) {
>f1 : (x: string | number) => void
>x : string | number
if (typeof x === "boolean") {
>typeof x === "boolean" : boolean
>typeof x : string
>x : string | number
>"boolean" : string
x; // never
>x : never
}
}
function f2(x: string | number) {
>f2 : (x: string | number) => never
>x : string | number
while (true) {
>true : boolean
if (typeof x === "boolean") {
>typeof x === "boolean" : boolean
>typeof x : string
>x : string | number
>"boolean" : string
return x; // never
>x : never
}
}
}
function test(cb: () => string) {
>test : (cb: () => string) => string
>cb : () => string
let s = cb();
>s : string
>cb() : string
>cb : () => string
return s;
>s : string
}
let errorCallback = () => error("Error callback");
>errorCallback : () => never
>() => error("Error callback") : () => never
>error("Error callback") : never
>error : (message: string) => never
>"Error callback" : string
test(() => "hello");
>test(() => "hello") : string
>test : (cb: () => string) => string
>() => "hello" : () => string
>"hello" : string
test(() => fail());
>test(() => fail()) : string
>test : (cb: () => string) => string
>() => fail() : () => never
>fail() : never
>fail : () => never
test(() => { throw new Error(); })
>test(() => { throw new Error(); }) : string
>test : (cb: () => string) => string
>() => { throw new Error(); } : () => never
>new Error() : Error
>Error : ErrorConstructor
test(errorCallback);
>test(errorCallback) : string
>test : (cb: () => string) => string
>errorCallback : () => never
@@ -0,0 +1,50 @@
tests/cases/conformance/types/never/neverTypeErrors1.ts(3,5): error TS2322: Type 'number' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(4,5): error TS2322: Type 'string' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(5,5): error TS2322: Type 'boolean' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(6,5): error TS2322: Type 'undefined' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(7,5): error TS2322: Type 'null' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(8,5): error TS2322: Type '{}' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(12,5): error TS2322: Type 'undefined' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(16,12): error TS2322: Type 'number' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors1.ts(19,16): error TS2534: A function returning 'never' cannot have a reachable end point.
==== tests/cases/conformance/types/never/neverTypeErrors1.ts (9 errors) ====
function f1() {
let x: never;
x = 1;
~
!!! error TS2322: Type 'number' is not assignable to type 'never'.
x = "abc";
~
!!! error TS2322: Type 'string' is not assignable to type 'never'.
x = false;
~
!!! error TS2322: Type 'boolean' is not assignable to type 'never'.
x = undefined;
~
!!! error TS2322: Type 'undefined' is not assignable to type 'never'.
x = null;
~
!!! error TS2322: Type 'null' is not assignable to type 'never'.
x = {};
~
!!! error TS2322: Type '{}' is not assignable to type 'never'.
}
function f2(): never {
return;
~~~~~~~
!!! error TS2322: Type 'undefined' is not assignable to type 'never'.
}
function f3(): never {
return 1;
~
!!! error TS2322: Type 'number' is not assignable to type 'never'.
}
function f4(): never {
~~~~~
!!! error TS2534: A function returning 'never' cannot have a reachable end point.
}
@@ -0,0 +1,40 @@
//// [neverTypeErrors1.ts]
function f1() {
let x: never;
x = 1;
x = "abc";
x = false;
x = undefined;
x = null;
x = {};
}
function f2(): never {
return;
}
function f3(): never {
return 1;
}
function f4(): never {
}
//// [neverTypeErrors1.js]
function f1() {
var x;
x = 1;
x = "abc";
x = false;
x = undefined;
x = null;
x = {};
}
function f2() {
return;
}
function f3() {
return 1;
}
function f4() {
}
@@ -0,0 +1,51 @@
tests/cases/conformance/types/never/neverTypeErrors2.ts(4,5): error TS2322: Type 'number' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(5,5): error TS2322: Type 'string' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(6,5): error TS2322: Type 'boolean' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(7,5): error TS2322: Type 'undefined' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(8,5): error TS2322: Type 'null' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(9,5): error TS2322: Type '{}' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(13,5): error TS2322: Type 'undefined' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(17,12): error TS2322: Type 'number' is not assignable to type 'never'.
tests/cases/conformance/types/never/neverTypeErrors2.ts(20,16): error TS2534: A function returning 'never' cannot have a reachable end point.
==== tests/cases/conformance/types/never/neverTypeErrors2.ts (9 errors) ====
function f1() {
let x: never;
x = 1;
~
!!! error TS2322: Type 'number' is not assignable to type 'never'.
x = "abc";
~
!!! error TS2322: Type 'string' is not assignable to type 'never'.
x = false;
~
!!! error TS2322: Type 'boolean' is not assignable to type 'never'.
x = undefined;
~
!!! error TS2322: Type 'undefined' is not assignable to type 'never'.
x = null;
~
!!! error TS2322: Type 'null' is not assignable to type 'never'.
x = {};
~
!!! error TS2322: Type '{}' is not assignable to type 'never'.
}
function f2(): never {
return;
~~~~~~~
!!! error TS2322: Type 'undefined' is not assignable to type 'never'.
}
function f3(): never {
return 1;
~
!!! error TS2322: Type 'number' is not assignable to type 'never'.
}
function f4(): never {
~~~~~
!!! error TS2534: A function returning 'never' cannot have a reachable end point.
}
@@ -0,0 +1,41 @@
//// [neverTypeErrors2.ts]
function f1() {
let x: never;
x = 1;
x = "abc";
x = false;
x = undefined;
x = null;
x = {};
}
function f2(): never {
return;
}
function f3(): never {
return 1;
}
function f4(): never {
}
//// [neverTypeErrors2.js]
function f1() {
var x;
x = 1;
x = "abc";
x = false;
x = undefined;
x = null;
x = {};
}
function f2() {
return;
}
function f3() {
return 1;
}
function f4() {
}
@@ -1,7 +1,7 @@
tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts(1,14): error TS1112: A class member cannot be declared optional.
tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts(1,14): error TS1162: An object member cannot be declared optional.
==== tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts (1 errors) ====
var v = { foo?() { } }
~
!!! error TS1112: A class member cannot be declared optional.
!!! error TS1162: An object member cannot be declared optional.
@@ -1,9 +1,7 @@
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties.ts(12,6): error TS1112: A class member cannot be declared optional.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties.ts(20,6): error TS1112: A class member cannot be declared optional.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties.ts(24,6): error TS1162: An object member cannot be declared optional.
==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties.ts (3 errors) ====
==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties.ts (1 errors) ====
// Basic uses of optional properties
var a: {
@@ -15,9 +13,7 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
}
class C {
x?: number; // error
~
!!! error TS1112: A class member cannot be declared optional.
x?: number; // ok
}
interface I2<T> {
@@ -25,9 +21,7 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
}
class C2<T> {
x?: T; // error
~
!!! error TS1112: A class member cannot be declared optional.
x?: T; // ok
}
var b = {
@@ -10,7 +10,7 @@ interface I {
}
class C {
x?: number; // error
x?: number; // ok
}
interface I2<T> {
@@ -18,7 +18,7 @@ interface I2<T> {
}
class C2<T> {
x?: T; // error
x?: T; // ok
}
var b = {
@@ -0,0 +1,147 @@
//// [optionalMethods.ts]
interface Foo {
a: number;
b?: number;
f(): number;
g?(): number;
}
function test1(x: Foo) {
x.a;
x.b;
x.f;
x.g;
let f1 = x.f();
let g1 = x.g && x.g();
let g2 = x.g ? x.g() : 0;
}
class Bar {
a: number;
b?: number;
c? = 2;
constructor(public d?: number, public e = 10) {}
f() {
return 1;
}
g?(): number; // Body of optional method can be omitted
h?() {
return 2;
}
}
function test2(x: Bar) {
x.a;
x.b;
x.c;
x.d;
x.e;
x.f;
x.g;
let f1 = x.f();
let g1 = x.g && x.g();
let g2 = x.g ? x.g() : 0;
let h1 = x.h && x.h();
let h2 = x.h ? x.h() : 0;
}
class Base {
a?: number;
f?(): number;
}
class Derived extends Base {
a = 1;
f(): number { return 1; }
}
//// [optionalMethods.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function test1(x) {
x.a;
x.b;
x.f;
x.g;
var f1 = x.f();
var g1 = x.g && x.g();
var g2 = x.g ? x.g() : 0;
}
var Bar = (function () {
function Bar(d, e) {
if (e === void 0) { e = 10; }
this.d = d;
this.e = e;
this.c = 2;
}
Bar.prototype.f = function () {
return 1;
};
Bar.prototype.h = function () {
return 2;
};
return Bar;
}());
function test2(x) {
x.a;
x.b;
x.c;
x.d;
x.e;
x.f;
x.g;
var f1 = x.f();
var g1 = x.g && x.g();
var g2 = x.g ? x.g() : 0;
var h1 = x.h && x.h();
var h2 = x.h ? x.h() : 0;
}
var Base = (function () {
function Base() {
}
return Base;
}());
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
_super.apply(this, arguments);
this.a = 1;
}
Derived.prototype.f = function () { return 1; };
return Derived;
}(Base));
//// [optionalMethods.d.ts]
interface Foo {
a: number;
b?: number;
f(): number;
g?(): number;
}
declare function test1(x: Foo): void;
declare class Bar {
d?: number;
e: number;
a: number;
b?: number;
c?: number | undefined;
constructor(d?: number, e?: number);
f(): number;
g?(): number;
h?(): number;
}
declare function test2(x: Bar): void;
declare class Base {
a?: number;
f?(): number;
}
declare class Derived extends Base {
a: number;
f(): number;
}
@@ -0,0 +1,203 @@
=== tests/cases/conformance/types/namedTypes/optionalMethods.ts ===
interface Foo {
>Foo : Symbol(Foo, Decl(optionalMethods.ts, 0, 0))
a: number;
>a : Symbol(Foo.a, Decl(optionalMethods.ts, 1, 15))
b?: number;
>b : Symbol(Foo.b, Decl(optionalMethods.ts, 2, 14))
f(): number;
>f : Symbol(Foo.f, Decl(optionalMethods.ts, 3, 15))
g?(): number;
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
}
function test1(x: Foo) {
>test1 : Symbol(test1, Decl(optionalMethods.ts, 6, 1))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>Foo : Symbol(Foo, Decl(optionalMethods.ts, 0, 0))
x.a;
>x.a : Symbol(Foo.a, Decl(optionalMethods.ts, 1, 15))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>a : Symbol(Foo.a, Decl(optionalMethods.ts, 1, 15))
x.b;
>x.b : Symbol(Foo.b, Decl(optionalMethods.ts, 2, 14))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>b : Symbol(Foo.b, Decl(optionalMethods.ts, 2, 14))
x.f;
>x.f : Symbol(Foo.f, Decl(optionalMethods.ts, 3, 15))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>f : Symbol(Foo.f, Decl(optionalMethods.ts, 3, 15))
x.g;
>x.g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
let f1 = x.f();
>f1 : Symbol(f1, Decl(optionalMethods.ts, 13, 7))
>x.f : Symbol(Foo.f, Decl(optionalMethods.ts, 3, 15))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>f : Symbol(Foo.f, Decl(optionalMethods.ts, 3, 15))
let g1 = x.g && x.g();
>g1 : Symbol(g1, Decl(optionalMethods.ts, 14, 7))
>x.g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x.g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
let g2 = x.g ? x.g() : 0;
>g2 : Symbol(g2, Decl(optionalMethods.ts, 15, 7))
>x.g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x.g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 8, 15))
>g : Symbol(Foo.g, Decl(optionalMethods.ts, 4, 16))
}
class Bar {
>Bar : Symbol(Bar, Decl(optionalMethods.ts, 16, 1))
a: number;
>a : Symbol(Bar.a, Decl(optionalMethods.ts, 18, 11))
b?: number;
>b : Symbol(Bar.b, Decl(optionalMethods.ts, 19, 14))
c? = 2;
>c : Symbol(Bar.c, Decl(optionalMethods.ts, 20, 15))
constructor(public d?: number, public e = 10) {}
>d : Symbol(Bar.d, Decl(optionalMethods.ts, 22, 16))
>e : Symbol(Bar.e, Decl(optionalMethods.ts, 22, 34))
f() {
>f : Symbol(Bar.f, Decl(optionalMethods.ts, 22, 52))
return 1;
}
g?(): number; // Body of optional method can be omitted
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
h?() {
>h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
return 2;
}
}
function test2(x: Bar) {
>test2 : Symbol(test2, Decl(optionalMethods.ts, 30, 1))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>Bar : Symbol(Bar, Decl(optionalMethods.ts, 16, 1))
x.a;
>x.a : Symbol(Bar.a, Decl(optionalMethods.ts, 18, 11))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>a : Symbol(Bar.a, Decl(optionalMethods.ts, 18, 11))
x.b;
>x.b : Symbol(Bar.b, Decl(optionalMethods.ts, 19, 14))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>b : Symbol(Bar.b, Decl(optionalMethods.ts, 19, 14))
x.c;
>x.c : Symbol(Bar.c, Decl(optionalMethods.ts, 20, 15))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>c : Symbol(Bar.c, Decl(optionalMethods.ts, 20, 15))
x.d;
>x.d : Symbol(Bar.d, Decl(optionalMethods.ts, 22, 16))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>d : Symbol(Bar.d, Decl(optionalMethods.ts, 22, 16))
x.e;
>x.e : Symbol(Bar.e, Decl(optionalMethods.ts, 22, 34))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>e : Symbol(Bar.e, Decl(optionalMethods.ts, 22, 34))
x.f;
>x.f : Symbol(Bar.f, Decl(optionalMethods.ts, 22, 52))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>f : Symbol(Bar.f, Decl(optionalMethods.ts, 22, 52))
x.g;
>x.g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
let f1 = x.f();
>f1 : Symbol(f1, Decl(optionalMethods.ts, 40, 7))
>x.f : Symbol(Bar.f, Decl(optionalMethods.ts, 22, 52))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>f : Symbol(Bar.f, Decl(optionalMethods.ts, 22, 52))
let g1 = x.g && x.g();
>g1 : Symbol(g1, Decl(optionalMethods.ts, 41, 7))
>x.g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x.g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
let g2 = x.g ? x.g() : 0;
>g2 : Symbol(g2, Decl(optionalMethods.ts, 42, 7))
>x.g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x.g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>g : Symbol(Bar.g, Decl(optionalMethods.ts, 25, 5))
let h1 = x.h && x.h();
>h1 : Symbol(h1, Decl(optionalMethods.ts, 43, 7))
>x.h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x.h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
let h2 = x.h ? x.h() : 0;
>h2 : Symbol(h2, Decl(optionalMethods.ts, 44, 7))
>x.h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x.h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
>x : Symbol(x, Decl(optionalMethods.ts, 32, 15))
>h : Symbol(Bar.h, Decl(optionalMethods.ts, 26, 17))
}
class Base {
>Base : Symbol(Base, Decl(optionalMethods.ts, 45, 1))
a?: number;
>a : Symbol(Base.a, Decl(optionalMethods.ts, 47, 12))
f?(): number;
>f : Symbol(Base.f, Decl(optionalMethods.ts, 48, 15))
}
class Derived extends Base {
>Derived : Symbol(Derived, Decl(optionalMethods.ts, 50, 1))
>Base : Symbol(Base, Decl(optionalMethods.ts, 45, 1))
a = 1;
>a : Symbol(Derived.a, Decl(optionalMethods.ts, 52, 28))
f(): number { return 1; }
>f : Symbol(Derived.f, Decl(optionalMethods.ts, 53, 10))
}
@@ -0,0 +1,226 @@
=== tests/cases/conformance/types/namedTypes/optionalMethods.ts ===
interface Foo {
>Foo : Foo
a: number;
>a : number
b?: number;
>b : number | undefined
f(): number;
>f : () => number
g?(): number;
>g : (() => number) | undefined
}
function test1(x: Foo) {
>test1 : (x: Foo) => void
>x : Foo
>Foo : Foo
x.a;
>x.a : number
>x : Foo
>a : number
x.b;
>x.b : number | undefined
>x : Foo
>b : number | undefined
x.f;
>x.f : () => number
>x : Foo
>f : () => number
x.g;
>x.g : (() => number) | undefined
>x : Foo
>g : (() => number) | undefined
let f1 = x.f();
>f1 : number
>x.f() : number
>x.f : () => number
>x : Foo
>f : () => number
let g1 = x.g && x.g();
>g1 : number | undefined
>x.g && x.g() : number | undefined
>x.g : (() => number) | undefined
>x : Foo
>g : (() => number) | undefined
>x.g() : number
>x.g : () => number
>x : Foo
>g : () => number
let g2 = x.g ? x.g() : 0;
>g2 : number
>x.g ? x.g() : 0 : number
>x.g : (() => number) | undefined
>x : Foo
>g : (() => number) | undefined
>x.g() : number
>x.g : () => number
>x : Foo
>g : () => number
>0 : number
}
class Bar {
>Bar : Bar
a: number;
>a : number
b?: number;
>b : number | undefined
c? = 2;
>c : number | undefined
>2 : number
constructor(public d?: number, public e = 10) {}
>d : number | undefined
>e : number
>10 : number
f() {
>f : () => number
return 1;
>1 : number
}
g?(): number; // Body of optional method can be omitted
>g : (() => number) | undefined
h?() {
>h : (() => number) | undefined
return 2;
>2 : number
}
}
function test2(x: Bar) {
>test2 : (x: Bar) => void
>x : Bar
>Bar : Bar
x.a;
>x.a : number
>x : Bar
>a : number
x.b;
>x.b : number | undefined
>x : Bar
>b : number | undefined
x.c;
>x.c : number | undefined
>x : Bar
>c : number | undefined
x.d;
>x.d : number | undefined
>x : Bar
>d : number | undefined
x.e;
>x.e : number
>x : Bar
>e : number
x.f;
>x.f : () => number
>x : Bar
>f : () => number
x.g;
>x.g : (() => number) | undefined
>x : Bar
>g : (() => number) | undefined
let f1 = x.f();
>f1 : number
>x.f() : number
>x.f : () => number
>x : Bar
>f : () => number
let g1 = x.g && x.g();
>g1 : number | undefined
>x.g && x.g() : number | undefined
>x.g : (() => number) | undefined
>x : Bar
>g : (() => number) | undefined
>x.g() : number
>x.g : () => number
>x : Bar
>g : () => number
let g2 = x.g ? x.g() : 0;
>g2 : number
>x.g ? x.g() : 0 : number
>x.g : (() => number) | undefined
>x : Bar
>g : (() => number) | undefined
>x.g() : number
>x.g : () => number
>x : Bar
>g : () => number
>0 : number
let h1 = x.h && x.h();
>h1 : number | undefined
>x.h && x.h() : number | undefined
>x.h : (() => number) | undefined
>x : Bar
>h : (() => number) | undefined
>x.h() : number
>x.h : () => number
>x : Bar
>h : () => number
let h2 = x.h ? x.h() : 0;
>h2 : number
>x.h ? x.h() : 0 : number
>x.h : (() => number) | undefined
>x : Bar
>h : (() => number) | undefined
>x.h() : number
>x.h : () => number
>x : Bar
>h : () => number
>0 : number
}
class Base {
>Base : Base
a?: number;
>a : number | undefined
f?(): number;
>f : (() => number) | undefined
}
class Derived extends Base {
>Derived : Derived
>Base : Base
a = 1;
>a : number
>1 : number
f(): number { return 1; }
>f : () => number
>1 : number
}
@@ -0,0 +1,11 @@
tests/cases/compiler/a.ts(2,14): error TS6131: Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'.
==== tests/cases/compiler/a.ts (1 errors) ====
export class A { } // module
~
!!! error TS6131: Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'.
==== tests/cases/compiler/b.ts (0 errors) ====
var x = 0; // global
@@ -0,0 +1,11 @@
//// [tests/cases/compiler/outModuleConcatUnspecifiedModuleKind.ts] ////
//// [a.ts]
export class A { } // module
//// [b.ts]
var x = 0; // global
//// [out.js]
var x = 0; // global
@@ -1,6 +1,6 @@
error TS5063: Substututions for pattern '*' should be an array.
error TS5063: Substitutions for pattern '*' should be an array.
!!! error TS5063: Substututions for pattern '*' should be an array.
!!! error TS5063: Substitutions for pattern '*' should be an array.
==== tests/cases/compiler/a.ts (0 errors) ====
let x = 1;
@@ -63,7 +63,7 @@ var x3 = f1()
.then(f2, (e: Error) => {
>then : { <TResult>(onfulfilled?: (value: T1) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>; <TResult>(onfulfilled?: (value: T1) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>; }
>f2 : (x: T1) => T2
>(e: Error) => { throw e;} : (e: Error) => void
>(e: Error) => { throw e;} : (e: Error) => never
>e : Error
>Error : Error
@@ -0,0 +1,50 @@
tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts(13,9): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts(33,7): error TS2415: Class 'E' incorrectly extends base class 'D'.
Property 'x' is private in type 'D' but not in type 'E'.
==== tests/cases/conformance/classes/constructorDeclarations/constructorParameters/readonlyConstructorAssignment.ts (2 errors) ====
// Tests that readonly parameter properties behave like regular readonly properties
class A {
constructor(readonly x: number) {
this.x = 0;
}
}
class B extends A {
constructor(x: number) {
super(x);
// Fails, x is readonly
this.x = 1;
~~~~~~
!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
}
}
class C extends A {
// This is the usual behavior of readonly properties:
// if one is redeclared in a base class, then it can be assigned to.
constructor(readonly x: number) {
super(x);
this.x = 1;
}
}
class D {
constructor(private readonly x: number) {
this.x = 0;
}
}
// Fails, can't redeclare readonly property
class E extends D {
~
!!! error TS2415: Class 'E' incorrectly extends base class 'D'.
!!! error TS2415: Property 'x' is private in type 'D' but not in type 'E'.
constructor(readonly x: number) {
super(x);
this.x = 1;
}
}
@@ -0,0 +1,92 @@
//// [readonlyConstructorAssignment.ts]
// Tests that readonly parameter properties behave like regular readonly properties
class A {
constructor(readonly x: number) {
this.x = 0;
}
}
class B extends A {
constructor(x: number) {
super(x);
// Fails, x is readonly
this.x = 1;
}
}
class C extends A {
// This is the usual behavior of readonly properties:
// if one is redeclared in a base class, then it can be assigned to.
constructor(readonly x: number) {
super(x);
this.x = 1;
}
}
class D {
constructor(private readonly x: number) {
this.x = 0;
}
}
// Fails, can't redeclare readonly property
class E extends D {
constructor(readonly x: number) {
super(x);
this.x = 1;
}
}
//// [readonlyConstructorAssignment.js]
// Tests that readonly parameter properties behave like regular readonly properties
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A(x) {
this.x = x;
this.x = 0;
}
return A;
}());
var B = (function (_super) {
__extends(B, _super);
function B(x) {
_super.call(this, x);
// Fails, x is readonly
this.x = 1;
}
return B;
}(A));
var C = (function (_super) {
__extends(C, _super);
// This is the usual behavior of readonly properties:
// if one is redeclared in a base class, then it can be assigned to.
function C(x) {
_super.call(this, x);
this.x = x;
this.x = 1;
}
return C;
}(A));
var D = (function () {
function D(x) {
this.x = x;
this.x = 0;
}
return D;
}());
// Fails, can't redeclare readonly property
var E = (function (_super) {
__extends(E, _super);
function E(x) {
_super.call(this, x);
this.x = x;
this.x = 1;
}
return E;
}(D));
@@ -562,9 +562,9 @@ class ListWrapper {
>ListWrapper : Symbol(ListWrapper, Decl(staticAnonymousTypeNotReferencingTypeParameter.ts, 38, 1))
>l : Symbol(l, Decl(staticAnonymousTypeNotReferencingTypeParameter.ts, 113, 43))
>T : Symbol(T, Decl(staticAnonymousTypeNotReferencingTypeParameter.ts, 113, 16))
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>l : Symbol(l, Decl(staticAnonymousTypeNotReferencingTypeParameter.ts, 113, 43))
static maximum<T>(dit: typeof ListWrapper, list: T[], predicate: (t: T) => number): T {
@@ -662,9 +662,9 @@ class ListWrapper {
>l : T[]
>T : T
>JSON.stringify(l) : string
>JSON.stringify : { (value: any): string; (value: any, replacer: (key: string, value: any) => any): string; (value: any, replacer: any[]): string; (value: any, replacer: (key: string, value: any) => any, space: string | number): string; (value: any, replacer: any[], space: string | number): string; }
>JSON.stringify : { (value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; (value: any, replacer?: (number | string)[], space?: string | number): string; }
>JSON : JSON
>stringify : { (value: any): string; (value: any, replacer: (key: string, value: any) => any): string; (value: any, replacer: any[]): string; (value: any, replacer: (key: string, value: any) => any, space: string | number): string; (value: any, replacer: any[], space: string | number): string; }
>stringify : { (value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; (value: any, replacer?: (number | string)[], space?: string | number): string; }
>l : T[]
static maximum<T>(dit: typeof ListWrapper, list: T[], predicate: (t: T) => number): T {
@@ -116,6 +116,6 @@ if (!hasKind(x, "B")) {
}
else {
let d = x;
>d : nothing
>x : nothing
>d : never
>x : never
}
@@ -110,6 +110,6 @@ if (!hasKind(x, "B")) {
}
else {
let d = x;
>d : nothing
>x : nothing
>d : never
>x : never
}
@@ -113,6 +113,6 @@ if (!hasKind(x, "B")) {
}
else {
let d = x;
>d : nothing
>x : nothing
>d : never
>x : never
}

Some files were not shown because too many files have changed in this diff Show More