Merge branch 'master' into tsbuild

This commit is contained in:
Ryan Cavanaugh
2018-05-24 13:01:58 -07:00
855 changed files with 46295 additions and 36570 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ Please fill in the *entire* template below.
-->
<!-- Please try to reproduce the issue with `typescript@next`. It may have already been fixed. -->
**TypeScript Version:** 2.9.0-dev.201xxxxx
**TypeScript Version:** 3.0.0-dev.201xxxxx
<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**
+4 -4
View File
@@ -32,8 +32,8 @@ What shortcomings exist with current approaches?
## Checklist
My suggestion meets these guidelines:
[ ] This wouldn't be a breaking change in existing TypeScript / JavaScript code
[ ] This wouldn't change the runtime behavior of existing JavaScript code
[ ] This could be implemented without emitting different JS based on the types of the expressions
[ ] This isn't a runtime feature (e.g. new expression-level syntax)
* [ ] This wouldn't be a breaking change in existing TypeScript / JavaScript code
* [ ] This wouldn't change the runtime behavior of existing JavaScript code
* [ ] This could be implemented without emitting different JS based on the types of the expressions
* [ ] This isn't a runtime feature (e.g. new expression-level syntax)
+1 -1
View File
@@ -24,7 +24,7 @@ Please help us by doing the following steps before logging an issue:
-->
<!-- Please try to reproduce the issue with `typescript@next`. It may have already been fixed. -->
**TypeScript Version:** 2.9.0-dev.201xxxxx
**TypeScript Version:** 3.0.0-dev.201xxxxx
<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**
+6 -5
View File
@@ -2,15 +2,16 @@
Thank you for submitting a pull request!
Here's a checklist you might find useful.
[ ] There is an associated issue that is labeled
* [ ] There is an associated issue that is labeled
'Bug' or 'help wanted' or is in the Community milestone
[ ] Code is up-to-date with the `master` branch
[ ] You've successfully run `jake runtests` locally
[ ] You've signed the CLA
[ ] There are new or updated unit tests validating the change
* [ ] Code is up-to-date with the `master` branch
* [ ] You've successfully run `jake runtests` locally
* [ ] You've signed the CLA
* [ ] There are new or updated unit tests validating the change
Refer to CONTRIBUTING.MD for more details.
https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md
-->
Fixes #
+1
View File
@@ -1,4 +1,5 @@
node_modules/
.node_modules/
built/*
tests/cases/rwc/*
tests/cases/test262/*
+21 -2
View File
@@ -308,7 +308,7 @@ Remo H. Jansen <remo.jansen@wolksoftware.com>
Sean Barag <sjbarag@gmail.com>
Sharon Rolel <sharonrolel@gmail.com>
Stanislav Iliev <gigobest2@gmail.com>
Wenlu Wang <805037171@163.com> wenlu.wang <805037171@163.com> kingwl <805037171@163.com>
Wenlu Wang <805037171@163.com> wenlu.wang <805037171@163.com> kingwl <805037171@163.com> 王文璐 <kingwenlu@gmail.com> 王文璐 <wenlu.wang@chaitin.com>
Wilson Hobbs <wilsonhobbs1@gmail.com>
Yuval Greenfield <ubershmekel@gmail.com>
Daniel <nieltg@users.noreply.github.com> # @nieltg
@@ -321,4 +321,23 @@ AdityaDaflapurkar <adaflapurkar@gmail.com> # Aditya Daflapurkar
Eric Grube <grubee79@gmail.com>
Martyn Janes <martyn@obany.com>
Ricardo N Feliciano <FelicianoTech@gmail.com>
Sergii Bezliudnyi <serg.bezludny@gmail.com>
Sergii Bezliudnyi <serg.bezludny@gmail.com>
Adrien Gibrat <adrien.gibrat@gmail.com>
Alex Ryan <ialexryan@users.noreply.github.com>
Alexader <alexander.v.tarasyuk@gmail.com> Alexander T <alexander.v.tarasyuk@gmail.com> # Alexander Tarasyuk
Andrew Faulkner <andfaulkner@gmail.com>
Artem Tyurin <artem.tyurin@uber.com>
Brandon Slade <brandonyoyoslade@gmail.com>
Derek P Sifford <dereksifford@gmail.com>
Dhruv Rajvanshi <dhruvrajvanshi@outlook.com>
Holger Jeromin <mailgithub@katur.de>
Jordi Oliveras Rovira <jordi.oliveras.rovira@gmail.com>
Joscha Feth <joscha@canva.com> Joscha Feth <joscha@feth.com>
Ken703 <bowden.kenny@gmail.com> # Bowden Kenny
Kevin Donnelly <kpdonn@users.noreply.github.com>
Maarten Sijm <M.P.Sijm@student.tudelft.nl>
Paul Koerbitz <paul.koerbitz@gmail.com>
EcoleKeine <Ecole_k@qq.com> # Ecole Keine
Khải <hvksmr1996@gmail.com>
rhysd <lin90162@yahoo.co.jp> # @rhysd
Zen <843968788@qq.com> Zzzen <843968788@qq.com> # @Zzzen
+2 -1
View File
@@ -1,6 +1,6 @@
built
doc
Gulpfile.ts
Gulpfile.js
internal
jenkins.sh
lib/README.md
@@ -23,3 +23,4 @@ test.config
package-lock.json
yarn.lock
.github/
CONTRIBUTING.md
+20 -1
View File
@@ -6,14 +6,17 @@ TypeScript is authored by:
* Aditya Daflapurkar
* Adnan Chowdhury
* Adrian Leonhard
* Adrien Gibrat
* Ahmad Farid
* Akshar Patel
* Alan Agius
* Alex Chugaev
* Alex Eagle
* Alex Khomchenko
* Alex Ryan
* Alexander Kuvaev
* Alexander Rusakov
* Alexander Tarasyuk
* Ali Sabzevari
* Aliaksandr Radzivanovich
* Aluan Haddad
@@ -22,6 +25,7 @@ TypeScript is authored by:
* Andreas Martin
* Andrej Baran
* Andrew Casey
* Andrew Faulkner
* Andrew Ochsner
* Andrew Stegmaier
* Andrew Z Allen
@@ -34,6 +38,7 @@ TypeScript is authored by:
* Armando Aguirre
* Arnaud Tournier
* Arnav Singh
* Artem Tyurin
* Arthur Ozga
* Asad Saeeduddin
* Avery Morin
@@ -49,6 +54,8 @@ TypeScript is authored by:
* Blake Embrey
* @bootstraponline
* Bowden Kelly
* Bowden Kenny
* Brandon Slade
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
@@ -76,6 +83,8 @@ TypeScript is authored by:
* David Sheldrick
* David Souther
* Denis Nedelyaev
* Derek P Sifford
* Dhruv Rajvanshi
* Dick van den Brink
* Diogo Franco (Kovensky)
* Dirk Bäumer
@@ -84,6 +93,7 @@ TypeScript is authored by:
* Donald Pipowitch
* Doug Ilijev
* @e-cloud
* Ecole Keine
* Elisée Maurer
* Emilio García-Pumarino
* Eric Grube
@@ -118,6 +128,7 @@ TypeScript is authored by:
* Hendrik Liebau
* Henry Mercer
* Herrington Darkholme
* Holger Jeromin
* Homa Wong
* Iain Monro
* @IdeaHunter
@@ -155,6 +166,8 @@ TypeScript is authored by:
* Jonathan Toland
* Jonathan Turner
* Jonathon Smith
* Jordi Oliveras Rovira
* Joscha Feth
* Josh Abernathy
* Josh Goldberg
* Josh Kalderimis
@@ -170,7 +183,9 @@ TypeScript is authored by:
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Kevin Donnelly
* Kevin Lang
* Khải
* Kitson Kelly
* Klaus Meinhardt
* Kris Zyp
@@ -179,6 +194,7 @@ TypeScript is authored by:
* Lorant Pinter
* Lucien Greathouse
* Lukas Elmer
* Maarten Sijm
* Magnus Hiie
* Magnus Kulke
* Manish Giri
@@ -223,6 +239,7 @@ TypeScript is authored by:
* Oussama Ben Brahim
* Patrick Zhong
* Paul Jolly
* Paul Koerbitz
* Paul van Brenk
* @pcbro
* Pedro Maltez
@@ -240,6 +257,7 @@ TypeScript is authored by:
* Raj Dosanjh
* Reiner Dolp
* Remo H. Jansen
* @rhysd
* Ricardo N Feliciano
* Richard Karmazín
* Richard Knoll
@@ -309,4 +327,5 @@ TypeScript is authored by:
* Yuval Greenfield
* Zeeshan Ahmed
* Zev Spitz
* Zhengbo Li
* Zhengbo Li
* @Zzzen
+5 -2
View File
@@ -36,7 +36,7 @@ const constEnumCaptureRegexp = /^(\s*)(export )?const enum (\S+) {(\s*)$/gm;
const constEnumReplacement = "$1$2enum $3 {$4";
const cmdLineOptions = minimist(process.argv.slice(2), {
boolean: ["debug", "inspect", "light", "colors", "lint", "soft"],
boolean: ["debug", "inspect", "light", "colors", "lint", "soft", "fix"],
string: ["browser", "tests", "host", "reporter", "stackTraceLimit", "timeout"],
alias: {
"b": "browser",
@@ -47,6 +47,7 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
"r": "reporter",
"c": "colors", "color": "colors",
"w": "workers",
"f": "fix",
},
default: {
soft: false,
@@ -61,6 +62,7 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
light: process.env.light === undefined || process.env.light !== "false",
reporter: process.env.reporter || process.env.r,
lint: process.env.lint || true,
fix: process.env.fix || process.env.f,
workers: process.env.workerCount || os.cpus().length,
}
});
@@ -260,6 +262,7 @@ function getCompilerSettings(base, useBuiltCompiler) {
for (const key in base) {
copy[key] = base[key];
}
copy.strictNullChecks = true;
if (!useDebugMode) {
if (copy.removeComments === undefined) copy.removeComments = true;
}
@@ -1069,7 +1072,7 @@ gulp.task("build-rules", "Compiles tslint rules to js", () => {
gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => {
if (fold.isTravis()) console.log(fold.start("lint"));
for (const project of ["scripts/tslint/tsconfig.json", "src/tsconfig-base.json"]) {
const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`;
const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish${cmdLineOptions.fix ? " --fix" : ""}`;
console.log("Linting: " + cmd);
child_process.execSync(cmd, { stdio: [0, 1, 2] });
}
+7 -55
View File
@@ -251,7 +251,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
else {
options += " --lib es5";
}
options += " --noUnusedLocals --noUnusedParameters";
options += " --noUnusedLocals --noUnusedParameters --strictNullChecks";
var cmd = host + " " + compilerPath + " " + options + " ";
cmd = cmd + sources.join(" ");
@@ -1114,65 +1114,17 @@ task("build-rules-end", [], function () {
if (fold.isTravis()) console.log(fold.end("build-rules"));
});
var lintTargets = compilerSources
.concat(harnessSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function (f) { return path.join(harnessDirectory, f); }))
.concat(serverSources)
.concat(tslintRulesFiles)
.concat(servicesSources)
.concat(typingsInstallerSources)
.concat(cancellationTokenSources)
.concat(["Gulpfile.ts"])
.concat([nodeServerInFile, perftscPath, "tests/perfsys.ts", webhostPath])
.map(function (p) { return path.resolve(p); });
// keep only unique items
lintTargets = Array.from(new Set(lintTargets));
function sendNextFile(files, child, callback, failures) {
var file = files.pop();
if (file) {
console.log("Linting '" + file + "'.");
child.send({ kind: "file", name: file });
}
else {
child.send({ kind: "close" });
callback(failures);
}
}
function spawnLintWorker(files, callback) {
var child = child_process.fork("./scripts/parallel-lint");
var failures = 0;
child.on("message", function (data) {
switch (data.kind) {
case "result":
if (data.failures > 0) {
failures += data.failures;
console.log(data.output);
}
sendNextFile(files, child, callback, failures);
break;
case "error":
console.error(data.error);
failures++;
sendNextFile(files, child, callback, failures);
break;
}
});
sendNextFile(files, child, callback, failures);
}
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
task("lint", ["build-rules"], () => {
if (fold.isTravis()) console.log(fold.start("lint"));
function lint(project, cb) {
const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`;
function lint(project, cb) {
const fix = process.env.fix || process.env.f;
const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish${fix ? " --fix" : ""}`;
console.log("Linting: " + cmd);
jake.exec([cmd], cb, /** @type {jake.ExecOptions} */({ interactive: true, windowsVerbatimArguments: true }));
}
lint("scripts/tslint/tsconfig.json", () => lint("src/tsconfig-base.json", () => {
}
lint("scripts/tslint/tsconfig.json", () => lint("src/tsconfig-base.json", () => {
if (fold.isTravis()) console.log(fold.end("lint"));
complete();
}));
}));
});
+76 -15
View File
@@ -1,35 +1,96 @@
/*!----------------- TypeScript ThirdPartyNotices -------------------------------------------------------
The TypeScript software is based on or incorporates material and code from the projects listed below
(collectively "Third Party Code"). Microsoft is not the original author of the
Third Party Code. The original copyright notice and the license, under which
Microsoft received such Third Party Code, are set forth below. Such license and
notices are provided for informational purposes only. Microsoft licenses the Third
The TypeScript software is based on or incorporates material and code from the projects listed below
(collectively "Third Party Code"). Microsoft is not the original author of the
Third Party Code. The original copyright notice and the license, under which
Microsoft received such Third Party Code, are set forth below. Such license and
notices are provided for informational purposes only. Microsoft licenses the Third
Party Code to you under the terms of the Apache 2.0 License.
All Third Party Code licensed by Microsoft 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
All Third Party Code licensed by Microsoft 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.
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
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
---------------------------------------------
Third Party Code Components
--------------------------------------------
------------------- DefinitelyTyped --------------------
This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise.
This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise.
DefinitelyTyped
This project is licensed under the MIT license.
Copyrights are respective of each contributor listed at the beginning of each definition file.
Provided for Informational Purposes Only
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------------
------------------- Unicode --------------------
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and
http://www.unicode.org/utility/trac/browser/.
Unicode Data Files do not include PDF online code charts under the
directory http://www.unicode.org/Public/.
Software includes any source code published in the Unicode Standard
or under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and
http://www.unicode.org/utility/trac/browser/.
NOTICE TO USER: Carefully read the following legal agreement.
BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT.
IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1991-2017 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated
Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
--------------------------------------------------------------------------------------
------------- End of ThirdPartyNotices --------------------------------------------------- */
-2
View File
@@ -69,5 +69,3 @@ function createCancellationToken(args) {
}
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"sources":["cancellationToken.ts"],"names":[],"mappings":";AAEA,uBAA0B;AAQ1B,oBAAoB,IAAY;IAC5B,IAAI;QACA,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;KACf;IACD,OAAO,CAAC,EAAE;QACN,OAAO,KAAK,CAAC;KAChB;AACL,CAAC;AAED,iCAAiC,IAAc;IAC3C,IAAI,oBAA4B,CAAC;IACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACtC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,wBAAwB,EAAE;YACtC,oBAAoB,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACnC,MAAM;SACT;KACJ;IACD,IAAI,CAAC,oBAAoB,EAAE;QACvB,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,KAAK,EAAL,CAAK;YACpC,UAAU,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;YAChD,YAAY,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;SACrD,CAAC;KACL;IAMD,IAAI,oBAAoB,CAAC,MAAM,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;QACtE,IAAM,YAAU,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACrD,IAAI,YAAU,CAAC,MAAM,KAAK,CAAC,IAAI,YAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YACzD,MAAM,IAAI,KAAK,CAAC,wHAAwH,CAAC,CAAC;SAC7I;QACD,IAAI,oBAA0B,CAAC;QAC/B,IAAI,kBAAwB,CAAC;QAC7B,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,oBAAkB,KAAK,SAAS,IAAI,UAAU,CAAC,oBAAkB,CAAC,EAAlE,CAAkE;YACjG,UAAU,YAAC,SAAiB;gBACxB,kBAAgB,GAAG,SAAS,CAAC;gBAC7B,oBAAkB,GAAG,YAAU,GAAG,SAAS,CAAC;YAChD,CAAC;YACD,YAAY,YAAC,SAAiB;gBAC1B,IAAI,kBAAgB,KAAK,SAAS,EAAE;oBAChC,MAAM,IAAI,KAAK,CAAC,qCAAmC,kBAAgB,iBAAY,SAAW,CAAC,CAAC;iBAC/F;gBACD,oBAAkB,GAAG,SAAS,CAAC;YACnC,CAAC;SACJ,CAAC;KACL;SACI;QACD,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,UAAU,CAAC,oBAAoB,CAAC,EAAhC,CAAgC;YAC/D,UAAU,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;YAChD,YAAY,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;SACrD,CAAC;KACL;AACL,CAAC;AACD,iBAAS,uBAAuB,CAAC","file":"cancellationToken.js","sourcesContent":["/// <reference types=\"node\"/>\r\n\r\nimport fs = require(\"fs\");\r\n\r\ninterface ServerCancellationToken {\r\n isCancellationRequested(): boolean;\r\n setRequest(requestId: number): void;\r\n resetRequest(requestId: number): void;\r\n}\r\n\r\nfunction pipeExists(name: string): boolean {\r\n try {\r\n fs.statSync(name);\r\n return true;\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n\r\nfunction createCancellationToken(args: string[]): ServerCancellationToken {\r\n let cancellationPipeName: string;\r\n for (let i = 0; i < args.length - 1; i++) {\r\n if (args[i] === \"--cancellationPipeName\") {\r\n cancellationPipeName = args[i + 1];\r\n break;\r\n }\r\n }\r\n if (!cancellationPipeName) {\r\n return {\r\n isCancellationRequested: () => false,\r\n setRequest: (_requestId: number): void => void 0,\r\n resetRequest: (_requestId: number): void => void 0\r\n };\r\n }\r\n // cancellationPipeName is a string without '*' inside that can optionally end with '*'\r\n // when client wants to signal cancellation it should create a named pipe with name=<cancellationPipeName>\r\n // server will synchronously check the presence of the pipe and treat its existance as indicator that current request should be canceled.\r\n // in case if client prefers to use more fine-grained schema than one name for all request it can add '*' to the end of cancelellationPipeName.\r\n // in this case pipe name will be build dynamically as <cancellationPipeName><request_seq>.\r\n if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === \"*\") {\r\n const namePrefix = cancellationPipeName.slice(0, -1);\r\n if (namePrefix.length === 0 || namePrefix.indexOf(\"*\") >= 0) {\r\n throw new Error(\"Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.\");\r\n }\r\n let perRequestPipeName: string;\r\n let currentRequestId: number;\r\n return {\r\n isCancellationRequested: () => perRequestPipeName !== undefined && pipeExists(perRequestPipeName),\r\n setRequest(requestId: number) {\r\n currentRequestId = requestId;\r\n perRequestPipeName = namePrefix + requestId;\r\n },\r\n resetRequest(requestId: number) {\r\n if (currentRequestId !== requestId) {\r\n throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`);\r\n }\r\n perRequestPipeName = undefined;\r\n }\r\n };\r\n }\r\n else {\r\n return {\r\n isCancellationRequested: () => pipeExists(cancellationPipeName),\r\n setRequest: (_requestId: number): void => void 0,\r\n resetRequest: (_requestId: number): void => void 0\r\n };\r\n }\r\n}\r\nexport = createCancellationToken;\r\n"]}
+21 -1
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Všechny deklarace {0} musí mít stejné parametry typu.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Všechny deklarace abstraktní metody musí jít po sobě.",
"All_destructured_elements_are_unused_6198": "Žádný z destrukturovaných elementů se nepoužívá.",
"All_imports_in_import_declaration_are_unused_6192": "Žádné importy z deklarace importu se nepoužívají.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Povolte výchozí importy z modulů bez výchozího exportu. Nebude to mít vliv na generování kódu, jenom na kontrolu typů.",
"Allow_javascript_files_to_be_compiled_6102": "Povolí kompilaci souborů javascript.",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Projekt {0} se nedá předřadit, protože nemá nastavenou hodnotu outFile.",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.",
"Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}",
"Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.",
"Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Ve výčtu, jehož členy mají hodnoty typu string, se nepovolují vypočítané hodnoty.",
"Concatenate_and_emit_output_to_single_file_6001": "Zřetězit a generovat výstup do jednoho souboru",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory odvozených tříd musí obsahovat volání příkazu super.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář přeskakuje se vyhledávání ve složce node_modules.",
"Convert_all_constructor_functions_to_classes_95045": "Převést všechny funkce konstruktoru na třídy",
"Convert_all_require_to_import_95048": "Převést všechna volání require na import",
"Convert_all_to_default_imports_95035": "Převést vše na výchozí importy",
"Convert_function_0_to_class_95002": "Převést funkci {0} na třídu",
"Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015",
"Convert_require_to_import_95047": "Převést require na import",
"Convert_to_ES6_module_95017": "Převést na modul ES6",
"Convert_to_default_import_95013": "Převést na výchozí import",
"Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "Duplicitní popisek {0}",
"Duplicate_number_index_signature_2375": "Duplicitní podpis číselného indexu",
"Duplicate_string_index_signature_2374": "Duplicitní signatury řetězcového indexu",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Když se cílí na moduly ECMAScript 2015, nejde dynamický import použít.",
"Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dynamický import se podporuje jenom tehdy, když je příznak --module nastavený na commonjs nebo esNext.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamický import musí mít jako argument jeden specifikátor.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element má implicitně typ any, protože indexový výraz není typu number.",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.",
"Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.",
"Enable_project_compilation_6302": "Povolit kompilování projektu",
"Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.",
"Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "Soubor {0} má nepodporovanou příponu, a proto se přeskočí.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Soubor {0} má nepodporovanou příponu. Jediné podporované přípony jsou {1}.",
"File_0_is_not_a_module_2306": "Soubor {0} není modul.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Soubor {0} se nenachází v seznamu souborů projektu. Projekty musí uvádět všechny soubory nebo používat vzor include.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Soubor {0} není pod kořenovým adresářem rootDir {1}. Očekává se, že rootDir bude obsahovat všechny zdrojové soubory.",
"File_0_not_found_6053": "Soubor {0} se nenašel.",
"File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Inicializátor členu v deklaracích ambientního výčtu musí být konstantní výraz.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Ve výčtu s víc deklaracemi může být jenom u jedné deklarace vynechaný inicializátor u prvního elementu výčtu.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "V inicializátoru člena deklarací výčtu const musí být konstantní výraz.",
"Include_modules_imported_with_json_extension_6197": "Zahrnout moduly importované s příponou .json",
"Index_signature_in_type_0_only_permits_reading_2542": "Signatura indexu v typu {0} povoluje jen čtení.",
"Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.",
"Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.",
"Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.",
"Move_to_a_new_file_95049": "Přesunout do nového souboru",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.",
"NEWLINE_6061": "NOVÝ ŘÁDEK",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Možnost isolatedModules jde použít jenom v případě, že je poskytnutá možnost --module nebo že možnost target je ES2015 nebo vyšší verze.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Možnost paths se nedá použít bez zadání možnosti --baseUrl.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Možnost project se na příkazovém řádku nedá kombinovat se zdrojovým souborem.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Možnost --resolveJsonModule se nedá zadat bez strategie překladu modulu node.",
"Options_Colon_6027": "Možnosti:",
"Output_directory_for_generated_declaration_files_6166": "Výstupní adresář pro vygenerované soubory deklarace",
"Output_file_0_from_project_1_does_not_exist_6309": "Výstupní soubor {0} z projektu {1} neexistuje.",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Výstupní soubor {0} se nesestavil ze zdrojového souboru {1}.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "Signatura přetížení není kompatibilní s implementací funkce.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Signatury přetížení musí být všechny abstraktní nebo neabstraktní.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Signatury přetížení musí být všechny ambientní nebo neambientní.",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Část kompilace, při které se vypisují názvy generovaných souborů",
"Print_the_compiler_s_version_6019": "Vytisknout verzi kompilátoru",
"Print_this_message_6017": "Vytisknout tuto zprávu",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}",
"Projects_to_reference_6300": "Projekty, které se mají odkazovat",
"Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.",
"Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Vlastnost {0} v typu {1} neexistuje. Nezapomněli jste použít await?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.",
"Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.",
"Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód",
"Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}",
"Remove_destructuring_90009": "Odebrat destrukci",
"Remove_import_from_0_90005": "Odebrat import z {0}",
"Remove_unreachable_code_95050": "Odebrat nedosažitelný kód",
"Replace_import_with_0_95015": "Nahradí import použitím: {0}.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "Seznam files v konfiguračním souboru {0} je prázdný.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metavlastnost import.meta je povolená, jenom když se pro možnosti kompilátoru target a module použije ESNext.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Levá strana příkazu for...in nemůže používat anotaci typu.",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modifikátory parametrů se dají použít jenom v souboru .ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modifikátor readonly se může objevit jenom v deklaraci vlastnosti nebo signatuře indexu.",
"require_call_may_be_converted_to_an_import_80005": "Volání require se dá převést na import.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Je nastavená možnost rootDirs, použije se k překladu relativního názvu modulu {0}.",
"super_can_only_be_referenced_in_a_derived_class_2335": "Na vlastnost super se dá odkazovat jenom v odvozené třídě.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Na možnost super je možné odkazovat jenom ve členech odvozených tříd nebo výrazů literálu objektu.",
+21 -5
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Alle Deklarationen von \"{0}\" müssen identische Typparameter aufweisen.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Alle Deklarationen einer abstrakten Methode müssen aufeinanderfolgend sein.",
"All_destructured_elements_are_unused_6198": "Alle destrukturierten Elemente werden nicht verwendet.",
"All_imports_in_import_declaration_are_unused_6192": "Keiner der Importe in der Importdeklaration wird verwendet.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Standardimporte von Modulen ohne Standardexport zulassen. Dies wirkt sich nicht auf die Codeausgabe aus, lediglich auf die Typprüfung.",
"Allow_javascript_files_to_be_compiled_6102": "Kompilierung von JavaScript-Dateien zulassen.",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Ein Objekt, das möglicherweise NULL ist, kann nicht aufgerufen werden.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Ein Objekt, das möglicherweise NULL oder nicht definiert ist, kann nicht aufgerufen werden.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Ein Objekt, das möglicherweise nicht definiert ist, kann nicht aufgerufen werden.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Das Projekt \"{0}\" kann nicht vorgestellt werden, weil \"outFile\" nicht festgelegt wurde.",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Ein Typ kann nicht erneut exportiert werden, wenn das Flag \"--isolatedModules\" angegeben ist.",
"Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}",
"Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".",
"Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".",
"Composite_projects_may_not_disable_declaration_emit_6304": "In zusammengesetzten Projekten kann die Deklarationsausgabe nicht deaktiviert werden.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Enumeration mit Membern mit Zeichenfolgenwerten nicht zulässig.",
"Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.",
@@ -271,11 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktoren für abgeleitete Klassen müssen einen Aufruf \"super\" enthalten.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.",
"Convert_all_constructor_functions_to_classes_95045": "Alle Konstruktorfunktionen in Klassen konvertieren",
"Convert_all_require_to_import_95048": "Convert all 'require' to 'import'",
"Convert_all_require_to_import_95048": "Alle Aufrufe von \"require\" in \"import\" konvertieren",
"Convert_all_to_default_imports_95035": "Alle in Standardimporte konvertieren",
"Convert_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren",
"Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren",
"Convert_require_to_import_95047": "Convert 'require' to 'import'",
"Convert_require_to_import_95047": "\"require\" in \"import\" konvertieren",
"Convert_to_ES6_module_95017": "In ES6-Modul konvertieren",
"Convert_to_default_import_95013": "In Standardimport konvertieren",
"Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.",
@@ -328,8 +331,8 @@
"Duplicate_label_0_1114": "Doppelte Bezeichnung \"{0}\".",
"Duplicate_number_index_signature_2375": "Doppelte Zahlenindexsignatur.",
"Duplicate_string_index_signature_2374": "Doppelte Zeichenfolgen-Indexsignatur.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Der dynamische Import kann nicht verwendet werden, wenn ECMAScript 2015-Module das Ziel sind.",
"Dynamic_import_cannot_have_type_arguments_1326": "Der dynamische Import kann nicht über Typargumente verfügen.",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Der dynamische Import wird nur unterstützt, wenn das Flag \"--module\" auf \"commonjs\" oder \"esNext\" festgelegt ist.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Der dynamische Import benötigt einen Spezifizierer als Argument.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Der Spezifizierer des dynamischen Imports muss den Typ \"string\" aufweisen, hier ist er jedoch vom Typ \"{0}\".",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Das Element weist implizit einen Typ \"any\" auf, weil der Indexausdruck nicht vom Typ \"number\" ist.",
@@ -338,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.",
"Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.",
"Enable_project_compilation_6302": "Projektkompilierung aktivieren",
"Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.",
"Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.",
@@ -399,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "Die Datei \"{0}\" hat eine nicht unterstützte Erweiterung und wird übersprungen.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Die Datei \"{0}\" weist eine nicht unterstützte Erweiterung auf. Die einzigen unterstützten Erweiterungen sind \"{1}\".",
"File_0_is_not_a_module_2306": "Die Datei \"{0}\" ist kein Modul.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Die Datei \"{0}\" befindet sich nicht in der Liste der Projektdateien. Projekte müssen alle Dateien auflisten oder ein include-Muster verwenden.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Datei \"{0}\" befindet sich nicht unter \"rootDir\" \"{1}\". \"rootDir\" muss alle Quelldateien enthalten.",
"File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.",
"File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...",
@@ -463,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "In Umgebungsenumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In einer Enumeration mit mehreren Deklarationen kann nur eine Deklaration einen Initialisierer für das erste Enumerationselement ausgeben.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "In const-Enumerationsdeklarationen muss der Memberinitialisierer ein konstanter Ausdruck sein.",
"Include_modules_imported_with_json_extension_6197": "Importierte Module mit der Erweiterung \"JSON\" einschließen",
"Index_signature_in_type_0_only_permits_reading_2542": "Die Indexsignatur in Typ \"{0}\" lässt nur Lesevorgänge zu.",
"Index_signature_is_missing_in_type_0_2329": "Die Indexsignatur fehlt im Typ \"{0}\".",
"Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.",
@@ -561,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.",
"Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".",
"Move_to_a_new_file_95049": "In neue Datei verschieben",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Mehrere aufeinander folgende numerische Trennzeichen sind nicht zulässig.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.",
"NEWLINE_6061": "NEUE ZEILE",
@@ -602,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Die Option \"isolatedModules\" kann nur verwendet werden, wenn entweder die Option \"--module\" angegeben ist oder die Option \"target\" den Wert \"ES2015\" oder höher aufweist.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Die \"path\"-Option kann nicht ohne Angabe der \"-baseUrl\"-Option angegeben werden.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Die Option \"project\" darf nicht mit Quelldateien in einer Befehlszeile kombiniert werden.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Die Option \"--resolveJsonModule\" kann nicht ohne die Modulauflösungsstrategie \"node\" angegeben werden.",
"Options_Colon_6027": "Optionen:",
"Output_directory_for_generated_declaration_files_6166": "Ausgabeverzeichnis für erstellte Deklarationsdateien.",
"Output_file_0_from_project_1_does_not_exist_6309": "Die Ausgabedatei \"{0}\" aus dem Projekt \"{1}\" ist nicht vorhanden.",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Die Ausgabedatei \"{0}\" wurde nicht aus der Quelldatei \"{1}\" erstellt.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "Die Überladungssignatur ist nicht mit der Funktionsimplementierung kompatibel.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Überladungssignaturen müssen alle abstrakt oder nicht abstrakt sein.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Überladungssignaturen müssen alle umgebend oder nicht umgebend sein.",
@@ -647,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.",
"Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.",
"Print_this_message_6017": "Diese Nachricht ausgeben.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}",
"Projects_to_reference_6300": "Zu referenzierende Projekte",
"Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.",
"Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Die Eigenschaft \"{0}\" ist im Typ \"{1}\" nicht vorhanden. Haben Sie \"await\" nicht verwendet?",
@@ -694,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Fehler für Ausdrücke und Deklarationen mit einem impliziten any-Typ auslösen.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.",
"Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.",
"Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen",
"Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}",
"Remove_destructuring_90009": "Destrukturierung entfernen",
"Remove_import_from_0_90005": "Import aus \"{0}\" entfernen",
"Remove_unreachable_code_95050": "Nicht erreichbaren Code entfernen",
"Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.",
@@ -803,7 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Die Metaeigenschaft \"import.meta\" ist nur bei Verwendung von \"ESNext\" für die Compileroptionen \"target\" und \"module\" zulässig.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Die linke Seite einer for...in-Anweisung darf keine Typanmerkung verwenden.",
@@ -1016,7 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" kann nur in einer TS-Datei verwendet werden.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Die Option \"paths\" wurde angegeben. Es wird nach einem Muster gesucht, das mit dem Modulnamen \"{0}\" übereinstimmt.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Der Modifizierer \"readonly\" darf nur für eine Eigenschaftendeklaration oder Indexsignatur verwendet werden.",
"require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.",
"require_call_may_be_converted_to_an_import_80005": "Der Aufruf von \"require\" kann in einen Aufruf von \"import\" konvertiert werden.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Die Option \"rootDirs\" wurde festgelegt. Sie wird zum Auflösen des relativen Modulnamens \"{0}\" verwendet.",
"super_can_only_be_referenced_in_a_derived_class_2335": "Auf \"super\" kann nur in einer abgeleiteten Klasse verwiesen werden.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Auf \"super\" kann nur in Membern abgeleiteter Klassen oder Objektliteralausdrücken verwiesen werden.",
+120 -6
View File
@@ -651,6 +651,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_missing_typeof_95052" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add missing 'typeof']]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add qualifier to all unresolved variables matching a member name]]></Val>
@@ -717,6 +723,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";All_destructured_elements_are_unused_6198" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[All destructured elements are unused.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";All_imports_in_import_declaration_are_unused_6192" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[All imports in import declaration are unused.]]></Val>
@@ -1335,6 +1347,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Cannot prepend project '{0}' because it does not have 'outFile' set]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Cannot re-export a type when the '--isolatedModules' flag is provided.]]></Val>
@@ -1575,6 +1593,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Composite_projects_may_not_disable_declaration_emit_6304" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Composite projects may not disable declaration emit.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Computed_property_names_are_not_allowed_in_enums_1164" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Computed property names are not allowed in enums.]]></Val>
@@ -1983,18 +2007,18 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Dynamic import cannot be used when targeting ECMAScript 2015 modules.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Dynamic_import_cannot_have_type_arguments_1326" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Dynamic import cannot have type arguments]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Dynamic_import_must_have_one_specifier_as_an_argument_1324" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Dynamic import must have one specifier as an argument.]]></Val>
@@ -2043,6 +2067,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Enable_project_compilation_6302" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Enable project compilation]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Enable_strict_checking_of_function_types_6186" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Enable strict checking of function types.]]></Val>
@@ -2409,6 +2439,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files.]]></Val>
@@ -2793,6 +2829,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Include_modules_imported_with_json_extension_6197" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Include modules imported with '.json' extension]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Index_signature_in_type_0_only_permits_reading_2542" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Index signature in type '{0}' only permits reading.]]></Val>
@@ -3381,6 +3423,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Move_to_a_new_file_95049" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Move to a new file]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Multiple_consecutive_numeric_separators_are_not_permitted_6189" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Multiple consecutive numeric separators are not permitted.]]></Val>
@@ -3627,6 +3675,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Options_Colon_6027" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Options:]]></Val>
@@ -3639,6 +3693,18 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Output_file_0_from_project_1_does_not_exist_6309" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Output file '{0}' from project '{1}' does not exist]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Output_file_0_has_not_been_built_from_source_file_1_6305" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Output file '{0}' has not been built from source file '{1}'.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Overload_signature_is_not_compatible_with_function_implementation_2394" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Overload signature is not compatible with function implementation.]]></Val>
@@ -3897,6 +3963,18 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Project references may not form a circular graph. Cycle detected: {0}]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Projects_to_reference_6300" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Projects to reference]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Property_0_does_not_exist_on_const_enum_1_2479" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Property '{0}' does not exist on 'const' enum '{1}'.]]></Val>
@@ -4179,18 +4257,54 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Referenced_project_0_must_have_setting_composite_Colon_true_6306" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Referenced project '{0}' must have setting "composite": true.]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_all_unreachable_code_95051" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove all unreachable code]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_all_unused_labels_95054" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove all unused labels]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_declaration_for_Colon_0_90004" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove declaration for: '{0}']]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_destructuring_90009" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove destructuring]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_import_from_0_90005" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove import from '{0}']]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_unreachable_code_95050" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove unreachable code]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_unused_label_95053" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove unused label]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Replace_import_with_0_95015" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Replace import with '{0}'.]]></Val>
+24 -2
View File
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"",
"Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar",
"Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta",
"Add_missing_typeof_95052": "Agregar el objeto typeof que falta",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro",
"Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama",
"Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error",
@@ -117,6 +118,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas las declaraciones de '{0}' deben tener parámetros de tipo idénticos.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas las declaraciones de un método abstracto deben ser consecutivas.",
"All_destructured_elements_are_unused_6198": "Todos los elementos desestructurados están sin utilizar.",
"All_imports_in_import_declaration_are_unused_6192": "Todas las importaciones de la declaración de importación están sin utilizar.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permitir las importaciones predeterminadas de los módulos sin exportación predeterminada. Esto no afecta a la emisión de código, solo a la comprobación de tipos.",
"Allow_javascript_files_to_be_compiled_6102": "Permitir que se compilen los archivos de JavaScript.",
@@ -220,6 +222,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "No se puede anteponer el proyecto \"{0}\" porque no se ha establecido \"outFile\".",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".",
"Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.",
@@ -260,6 +263,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".",
"Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.",
"Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "No se permiten valores calculados en una enumeración que tiene miembros con valores de cadena.",
"Concatenate_and_emit_output_to_single_file_6001": "Concatenar y emitir la salida en un único archivo.",
@@ -271,9 +275,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Los constructores de las clases derivadas deben contener una llamada a \"super\".",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.",
"Convert_all_constructor_functions_to_classes_95045": "Convertir todas las funciones de constructor en clases",
"Convert_all_require_to_import_95048": "Convertir todas las repeticiones de \"require\" en \"import\"",
"Convert_all_to_default_imports_95035": "Convertir todo en importaciones predeterminadas",
"Convert_function_0_to_class_95002": "Convertir la función \"{0}\" en una clase",
"Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015",
"Convert_require_to_import_95047": "Convertir \"require\" en \"import\"",
"Convert_to_ES6_module_95017": "Convertir en módulo ES6",
"Convert_to_default_import_95013": "Convertir en importación predeterminada",
"Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.",
@@ -326,8 +332,8 @@
"Duplicate_label_0_1114": "Etiqueta \"{0}\" duplicada.",
"Duplicate_number_index_signature_2375": "Signatura de índice de número duplicada.",
"Duplicate_string_index_signature_2374": "Signatura de índice de cadena duplicada.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "No se puede utilizar la importación dinámica cuando se destina a módulos ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "La importación dinámica solo se admite cuando la marca \"--module\" es \"commonjs\" o \"esNext\".",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "La importación dinámica debe tener un especificador como argumento.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "El elemento tiene un tipo 'any' implícito porque la expresión de índice no es de tipo 'number'.",
@@ -336,6 +342,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir un solo archivo con mapas de origen en lugar de tener un archivo aparte.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir el origen junto a los mapas de origen en un solo archivo; requiere que se establezca \"--inlineSourceMap\" o \"--sourceMap\".",
"Enable_all_strict_type_checking_options_6180": "Habilitar todas las opciones de comprobación de tipos estricta.",
"Enable_project_compilation_6302": "Habilitar la compilación de proyecto",
"Enable_strict_checking_of_function_types_6186": "Habilite la comprobación estricta de los tipos de función.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.",
"Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.",
@@ -397,6 +404,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "El archivo \"{0}\" tiene una extensión no admitida, así que se omitirá.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "La extensión del archivo '{0}' no es compatible. Las únicas extensiones compatibles son {1}.",
"File_0_is_not_a_module_2306": "El archivo '{0}' no es un módulo.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "El archivo \"{0}\" no está en la lista de archivos del proyecto. Los proyectos deben enumerar todos los archivos o usar un patrón \"include\".",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "El archivo '{0}' no está en \"rootDir\" '{1}'. Se espera que \"rootDir\" contenga todos los archivos de origen.",
"File_0_not_found_6053": "Archivo '{0}' no encontrado.",
"File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...",
@@ -461,6 +469,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.",
"Include_modules_imported_with_json_extension_6197": "Incluir módulos importados con la extensión \".json\"",
"Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.",
"Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.",
"Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.",
@@ -559,6 +568,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.",
"Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".",
"Move_to_a_new_file_95049": "Mover a un nuevo archivo",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "No se permiten varios separadores numéricos consecutivos.",
"Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.",
"NEWLINE_6061": "NUEVA LÍNEA",
@@ -600,8 +610,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "La opción \"isolatedModules\" solo se puede usar cuando se proporciona la opción \"--module\" o si la opción \"target\" es \"ES2015\" o una versión posterior.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "La opción 'paths' no se puede usar sin especificar la opción '--baseUrl'.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "La opción \"project\" no se puede combinar con archivos de origen en una línea de comandos.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "No se puede especificar la opción \"--resolveJsonModule\" sin la estrategia de resolución de módulos \"node\".",
"Options_Colon_6027": "Opciones:",
"Output_directory_for_generated_declaration_files_6166": "Directorio de salida para los archivos de declaración generados.",
"Output_file_0_from_project_1_does_not_exist_6309": "El archivo de salida \"{0}\" del proyecto \"{1}\" no existe.",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "El archivo de salida \"{0}\" no se compiló desde el archivo de origen \"{1}\".",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "La signatura de sobrecarga no es compatible con la implementación de función.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Las signaturas de sobrecarga deben ser todas abstractas o no abstractas.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Las signaturas de sobrecarga deben ser todas de ambiente o de no ambiente.",
@@ -645,6 +658,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.",
"Print_the_compiler_s_version_6019": "Imprima la versión del compilador.",
"Print_this_message_6017": "Imprima este mensaje.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}",
"Projects_to_reference_6300": "Proyectos a los que se hará referencia",
"Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.",
"Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Olvidó usar \"await\"?",
@@ -692,8 +707,14 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.",
"Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.",
"Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible",
"Remove_all_unused_labels_95054": "Remove all unused labels",
"Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"",
"Remove_destructuring_90009": "Quitar la desestructuración",
"Remove_import_from_0_90005": "Quitar importación de \"{0}\"",
"Remove_unreachable_code_95050": "Quitar el código inaccesible",
"Remove_unused_label_95053": "Remove unused label",
"Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.",
@@ -801,7 +822,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "La lista de archivos del archivo de configuración '{0}' está vacía.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La propiedad Meta \"import.meta\" solo se admite si se usa \"ESNext\" para las opciones del compilador \"target\" y \"module\".",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La parte izquierda de una instrucción \"for...in\" no puede usar una anotación de tipo.",
@@ -1014,6 +1035,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" solo se puede usar en un archivo .ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Se ha especificado la opción 'paths'. Se buscará un patrón que coincida con el nombre de módulo '{0}'.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "El modificador 'readonly' solo puede aparecer en una declaración de propiedad o una signatura de índice.",
"require_call_may_be_converted_to_an_import_80005": "La llamada a \"require\" puede convertirse en una importación.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Se ha establecido la opción \"rootDirs\". Se usará para resolver el nombre de módulo relativo \"{0}\".",
"super_can_only_be_referenced_in_a_derived_class_2335": "Solo se puede hacer referencia a \"super\" en una clase derivada.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Solo se puede hacer referencia a 'super' en miembros de clases derivadas o expresiones de literal de objeto.",
+22 -2
View File
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'",
"Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées",
"Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'",
"Add_missing_typeof_95052": "Ajouter un typeof manquant",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre",
"Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés",
"Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur",
@@ -117,6 +118,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Toutes les déclarations de '{0}' doivent avoir des paramètres de type identiques.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Toutes les déclarations d'une méthode abstraite doivent être consécutives.",
"All_destructured_elements_are_unused_6198": "Tous les éléments déstructurés sont inutilisés.",
"All_imports_in_import_declaration_are_unused_6192": "Les importations de la déclaration d'importation ne sont pas toutes utilisées.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Autorisez les importations par défaut à partir des modules sans exportation par défaut. Cela n'affecte pas l'émission du code, juste le contrôle de type.",
"Allow_javascript_files_to_be_compiled_6102": "Autorisez la compilation des fichiers JavaScript.",
@@ -220,6 +222,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Impossible de préfixer le projet '{0}', car 'outFile' n'est pas défini",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.",
"Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.",
@@ -260,6 +263,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.",
"Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Les valeurs calculées ne sont pas autorisées dans un enum avec des membres ayant une valeur de chaîne.",
"Concatenate_and_emit_output_to_single_file_6001": "Concaténer la sortie et l'émettre vers un seul fichier.",
@@ -271,9 +275,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Les constructeurs pour les classes dérivées doivent contenir un appel de 'super'.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.",
"Convert_all_constructor_functions_to_classes_95045": "Convertir toutes les fonctions de constructeur en classes",
"Convert_all_require_to_import_95048": "Convertir tous les 'require' en 'import'",
"Convert_all_to_default_imports_95035": "Convertir tout en importations par défaut",
"Convert_function_0_to_class_95002": "Convertir la fonction '{0}' en classe",
"Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015",
"Convert_require_to_import_95047": "Convertir 'require' en 'import'",
"Convert_to_ES6_module_95017": "Convertir en module ES6",
"Convert_to_default_import_95013": "Convertir en importation par défaut",
"Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.",
@@ -326,8 +332,8 @@
"Duplicate_label_0_1114": "Étiquette '{0}' en double.",
"Duplicate_number_index_signature_2375": "Signature d'index de nombre dupliquée.",
"Duplicate_string_index_signature_2374": "Signature d'index de chaîne dupliquée.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "L'importation dynamique ne peut pas être utilisée pour cibler des modules ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importation dynamique est prise en charge uniquement quand l'indicateur '--module' a la valeur 'commonjs' ou 'esNext'.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "L'importation dynamique doit avoir un seul spécificateur comme argument.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'élément possède implicitement un type 'any', car l'expression d'index n'est pas de type 'number'.",
@@ -336,6 +342,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Émettez un seul fichier avec des mappages de sources au lieu d'avoir un fichier distinct.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Émettez la source aux côtés des mappages de sources dans un fichier unique. Nécessite la définition de '--inlineSourceMap' ou '--sourceMap'.",
"Enable_all_strict_type_checking_options_6180": "Activez toutes les options de contrôle de type strict.",
"Enable_project_compilation_6302": "Activer la compilation du projet",
"Enable_strict_checking_of_function_types_6186": "Activez la vérification stricte des types de fonction.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.",
"Enable_strict_null_checks_6113": "Activez strict null checks.",
@@ -397,6 +404,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "Le fichier '{0}' a une extension non prise en charge. Il est ignoré.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Le fichier '{0}' possède une extension non prise en charge. Les seules extensions prises en charge sont {1}.",
"File_0_is_not_a_module_2306": "Le fichier '{0}' n'est pas un module.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Le fichier '{0}' ne figure pas dans la liste de fichiers projet. Les projets doivent lister tous les fichiers ou utiliser un modèle 'include'.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Le fichier '{0}' ne se trouve pas sous 'rootDir' '{1}'. 'rootDir' est supposé contenir tous les fichiers sources.",
"File_0_not_found_6053": "Fichier '{0}' introuvable.",
"File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...",
@@ -461,6 +469,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Dans les déclarations d'enums ambiants, l'initialiseur de membre doit être une expression constante.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Dans un enum avec plusieurs déclarations, seule une déclaration peut omettre un initialiseur pour son premier élément d'enum.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Dans les déclarations d'enum 'const', l'initialiseur de membre doit être une expression constante.",
"Include_modules_imported_with_json_extension_6197": "Inclure les modules importés avec l'extension '.json'",
"Index_signature_in_type_0_only_permits_reading_2542": "La signature d'index du type '{0}' autorise uniquement la lecture.",
"Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.",
"Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.",
@@ -559,6 +568,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.",
"Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.",
"Move_to_a_new_file_95049": "Déplacer vers un nouveau fichier",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.",
"NEWLINE_6061": "NOUVELLE LIGNE",
@@ -600,8 +610,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'option 'isolatedModules' peut être utilisée seulement quand l'option '--module' est spécifiée, ou quand l'option 'target' a la valeur 'ES2015' ou une version supérieure.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Impossible d'utiliser l'option 'paths' sans spécifier l'option '--baseUrl'.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Impossible d'associer l'option 'project' à des fichiers sources sur une ligne de commande.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Impossible de spécifier l'option '--resolveJsonModule' sans la stratégie de résolution de module 'node'.",
"Options_Colon_6027": "Options :",
"Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.",
"Output_file_0_from_project_1_does_not_exist_6309": "Le fichier de sortie '{0}' du projet '{1}' n'existe pas",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "La signature de surcharge n'est pas compatible avec l'implémentation de fonction.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.",
@@ -645,6 +658,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.",
"Print_the_compiler_s_version_6019": "Affichez la version du compilateur.",
"Print_this_message_6017": "Imprimez ce message.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}",
"Projects_to_reference_6300": "Projets à référencer",
"Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.",
"Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La propriété '{0}' n'existe pas sur le type '{1}'. Avez-vous oublié d'utiliser 'await' ?",
@@ -692,8 +707,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.",
"Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.",
"Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible",
"Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'",
"Remove_destructuring_90009": "Supprimer la déstructuration",
"Remove_import_from_0_90005": "Supprimer l'importation de '{0}'",
"Remove_unreachable_code_95050": "Supprimer le code inaccessible",
"Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.",
@@ -801,7 +820,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "La liste 'files' du fichier config '{0}' est vide.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Le premier paramètre de la méthode 'then' d'une promesse doit être un rappel.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La métapropriété 'import.meta' est uniquement autorisée avec 'ESNext' pour les options de compilateur 'target' et 'module'.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "La partie gauche d'une instruction 'for...in' ne peut pas utiliser d'annotation de type.",
@@ -1014,6 +1033,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Les 'modificateurs de paramètre' peuvent uniquement être utilisés dans un fichier .ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "L'option 'paths' est spécifiée. Recherche d'un modèle correspondant au nom de module '{0}'.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Le modificateur 'readonly' peut apparaître uniquement dans une déclaration de propriété ou une signature d'index.",
"require_call_may_be_converted_to_an_import_80005": "L'appel de 'require' peut être converti en import.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'option 'rootDirs' est définie. Utilisation de celle-ci pour la résolution du nom de module relatif '{0}'.",
"super_can_only_be_referenced_in_a_derived_class_2335": "'super' ne peut être référencé que dans une classe dérivée.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' ne peut être référencé que dans les membres des classes dérivées ou les expressions littérales d'objet.",
+21 -1
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Tutte le dichiarazioni di '{0}' devono contenere parametri di tipo identici.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Tutte le dichiarazioni di un metodo astratto devono essere consecutive.",
"All_destructured_elements_are_unused_6198": "Tutti gli elementi destrutturati sono inutilizzati.",
"All_imports_in_import_declaration_are_unused_6192": "Tutte le importazioni nella dichiarazione di importazione sono inutilizzate.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Consente di eseguire importazioni predefinite da moduli senza esportazione predefinita. Non influisce sulla creazione del codice ma solo sul controllo dei tipi.",
"Allow_javascript_files_to_be_compiled_6102": "Consente la compilazione di file JavaScript.",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Non è possibile richiamare un oggetto che è probabilmente 'null'.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Non è possibile richiamare un oggetto che è probabilmente 'null' o 'undefined'.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Non è possibile richiamare un oggetto che è probabilmente 'undefined'.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Non è possibile anteporre il progetto '{0}' perché 'outFile' non è impostato",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Non è possibile riesportare un tipo quando è stato specificato il flag '--isolatedModules'.",
"Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.",
"Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "I progetti compositi non possono disabilitare la creazione di dichiarazioni.",
"Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "In un'enumerazione con membri con valore stringa non sono consentiti valori calcolati.",
"Concatenate_and_emit_output_to_single_file_6001": "Concatena e crea l'output in un singolo file.",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "I costruttori di classi derivate devono contenere una chiamata 'super'.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.",
"Convert_all_constructor_functions_to_classes_95045": "Convertire tutte le funzioni di costruttore in classi",
"Convert_all_require_to_import_95048": "Convertire tutte le occorrenze di 'require' in 'import'",
"Convert_all_to_default_imports_95035": "Convertire tutte le impostazioni predefinite",
"Convert_function_0_to_class_95002": "Converti la funzione '{0}' in classe",
"Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015",
"Convert_require_to_import_95047": "Convertire 'require' in 'import'",
"Convert_to_ES6_module_95017": "Converti in modulo ES6",
"Convert_to_default_import_95013": "Converti nell'importazione predefinita",
"Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "Etichetta '{0}' duplicata.",
"Duplicate_number_index_signature_2375": "La firma dell'indice di tipo number è duplicata.",
"Duplicate_string_index_signature_2374": "La firma dell'indice di tipo string è duplicata.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Non è possibile usare l'importazione dinamica quando come destinazione si impostano moduli ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "Nell'importazione dinamica non possono essere presenti argomenti tipo",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "L'importazione dinamica è supportata solo quando il valore del flag '--module' è 'commonjs' o 'esNext'.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Come argomento dell'importazione dinamica si può indicare un solo identificatore.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "L'identificatore dell'importazione dinamica deve essere di tipo 'string', ma il tipo specificato qui è '{0}'.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.",
"Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.",
"Enable_project_compilation_6302": "Abilitare la compilazione dei progetti",
"Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilita il controllo tassativo dell'inizializzazione delle proprietà nelle classi.",
"Enable_strict_null_checks_6113": "Abilita i controlli strict Null.",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "L'estensione del file '{0}' non è supportata. Il file verrà ignorato.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "L'estensione del file '{0}' non è supportata. Le uniche estensioni supportate sono {1}.",
"File_0_is_not_a_module_2306": "Il file '{0}' non è un modulo.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Il file '{0}' non è presente nell'elenco dei file di progetto. I progetti devono elencare tutti i file o usare un criterio 'include'.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Il file '{0}' non si trova in 'rootDir' '{1}'. 'rootDir' deve contenere tutti i file di origine.",
"File_0_not_found_6053": "Il file '{0}' non è stato trovato.",
"File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni di enumerazione dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento dell'enumerazione.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni di enumerazione 'const' l'inizializzatore di membro deve essere un'espressione costante.",
"Include_modules_imported_with_json_extension_6197": "Includere i moduli importati con estensione '.json'",
"Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.",
"Index_signature_is_missing_in_type_0_2329": "Nel tipo '{0}' manca la firma dell'indice.",
"Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.",
"Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.",
"Move_to_a_new_file_95049": "Passare a un nuovo file",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Non sono consentiti più separatori numerici consecutivi.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.",
"NEWLINE_6061": "NUOVA RIGA",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "L'opzione 'isolatedModules' può essere usata solo quando si specifica l'opzione '--module' oppure il valore dell'opzione 'target' è 'ES2015' o maggiore.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Non è possibile usare l'opzione 'paths' senza specificare l'opzione '--baseUrl'.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Non è possibile combinare l'opzione 'project' con file di origine in una riga di comando.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Non è possibile specificare l'opzione '--resolveJsonModule' senza la strategia di risoluzione del modulo 'node'.",
"Options_Colon_6027": "Opzioni:",
"Output_directory_for_generated_declaration_files_6166": "Directory di output per i file di dichiarazione generati.",
"Output_file_0_from_project_1_does_not_exist_6309": "Il file di output '{0}' del progetto '{1}' non esiste",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Il file di output '{0}' non è stato compilato dal file di origine '{1}'.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "La firma di overload non è compatibile con l'implementazione di funzione.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Le firme di overload devono essere tutte astratte o tutte non astratte.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Le firme di overload devono essere tutte di ambiente o non di ambiente.",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.",
"Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.",
"Print_this_message_6017": "Stampa questo messaggio.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}",
"Projects_to_reference_6300": "Progetti cui fare riferimento",
"Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.",
"Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "La proprietà '{0}' non esiste nel tipo '{1}'. Si è dimenticato di usare 'await'?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.",
"Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.",
"Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile",
"Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'",
"Remove_destructuring_90009": "Rimuovere la destrutturazione",
"Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'",
"Remove_unreachable_code_95050": "Rimuovere il codice non eseguibile",
"Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "L'elenco 'files' nel file config '{0}' è vuoto.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "La metaproprietà 'import.meta' è consentita solo se si usa 'ESNext' per le opzioni 'target' e 'module' del compilatore.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Nella parte sinistra di un'espressione 'for...in' non è possibile usare un'annotazione di tipo.",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' può essere usato solo in un file con estensione ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "È specificata l'opzione 'paths'. Verrà cercato un criterio per la corrispondenza con il nome del modulo '{0}'.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Il modificatore 'readonly' può essere incluso solo in una dichiarazione di proprietà o una firma dell'indice.",
"require_call_may_be_converted_to_an_import_80005": "La chiamata a 'require' può essere convertita in un'importazione.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "L'opzione 'rootDirs' è impostata e verrà usata per risolvere il nome del modulo relativo '{0}'.",
"super_can_only_be_referenced_in_a_derived_class_2335": "È possibile fare riferimento a 'super' solo in una classe derivata.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "È possibile fare riferimento a 'super' solo in membri di classi derivate o espressioni letterali di oggetto.",
+24 -2
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' のすべての宣言には、同一の型パラメーターがある必要があります。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象メソッドの宣言はすべて連続している必要があります。",
"All_destructured_elements_are_unused_6198": "非構造化要素はいずれも使用されていません。",
"All_imports_in_import_declaration_are_unused_6192": "インポート宣言内のインポートはすべて未使用です。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "既定のエクスポートがないモジュールからの既定のインポートを許可します。これは、型チェックのみのため、コード生成には影響を与えません。",
"Allow_javascript_files_to_be_compiled_6102": "javascript ファイルのコンパイルを許可します。",
@@ -133,6 +134,7 @@
"An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同期関数または非同期メソッドには、有効で待機可能な戻り値の型を指定する必要があります。",
"An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることを確認してください。",
"An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。",
"An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。",
"An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。",
"An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。",
@@ -219,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' が設定されていないため、プロジェクト '{0}' を先頭に追加することはできません",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。",
"Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。",
@@ -259,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。",
"Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。",
"Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。",
"Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。",
"Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。",
@@ -270,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生クラスのコンストラクターには 'super' の呼び出しを含める必要があります。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。",
"Convert_all_constructor_functions_to_classes_95045": "すべてのコンストラクター関数をクラスに変換します",
"Convert_all_require_to_import_95048": "'require' をすべて 'import' に変換",
"Convert_all_to_default_imports_95035": "すべてを既定のインポートに変換します",
"Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します",
"Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します",
"Convert_require_to_import_95047": "'require' を 'import' に変換",
"Convert_to_ES6_module_95017": "ES6 モジュールに変換します",
"Convert_to_default_import_95013": "既定のインポートに変換する",
"Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。",
@@ -325,8 +331,8 @@
"Duplicate_label_0_1114": "ラベル '{0}' が重複しています。",
"Duplicate_number_index_signature_2375": "number インデックス シグネチャが重複しています。",
"Duplicate_string_index_signature_2374": "string インデックス シグネチャが重複しています。",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 モジュールを対象とする場合、動的インポートを使用することはできません。",
"Dynamic_import_cannot_have_type_arguments_1326": "動的インポートには型引数を指定することはできません",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "動的インポートがサポートされるのは、'--module' フラグが 'commonjs' または 'esNext' の場合のみです。",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動的インポートには、引数として 1 つの指定子を指定する必要があります。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動的インポートの指定子の型は 'string' である必要がありますが、ここでは型 '{0}' が指定されています。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "インデックス式が型 'number' ではないため、要素に 'any' 型が暗黙的に指定されます。",
@@ -335,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。",
"Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。",
"Enable_project_compilation_6302": "プロジェクトのコンパイルを有効にします",
"Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。",
"Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。",
@@ -396,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "ファイル '{0}' にはサポートされていない拡張機能があるため、スキップしています。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "ファイル '{0}' はサポートされていない拡張子を含んでいます。サポートされている拡張子は {1} のみです。",
"File_0_is_not_a_module_2306": "ファイル '{0}' はモジュールではありません。",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "ファイル '{0}' がプロジェクト ファイル リストに含まれていません。プロジェクトではすべてのファイルをリストするか、'include' パターンを使用する必要があります。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "ファイル '{0}' が 'rootDir' '{1}' の下にありません。'rootDir' にすべてにソース ファイルが含まれている必要があります。",
"File_0_not_found_6053": "ファイル '{0}' が見つかりません。",
"File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...",
@@ -460,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。",
"Include_modules_imported_with_json_extension_6197": "'.json' 拡張子付きのインポートされたモジュールを含める",
"Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。",
"Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。",
"Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。",
@@ -558,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========",
"Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。",
"Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。",
"Move_to_a_new_file_95049": "新しいファイルへ移動します",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。",
"Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。",
"NEWLINE_6061": "改行",
@@ -599,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "オプション 'isolatedModules' は、オプション '--module' が指定されているか、オプション 'target' が 'ES2015' 以上であるかのいずれかの場合でのみ使用できます。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "オプション 'paths' は、'--baseUrl' オプションを指定せずに使用できません。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "オプション 'project' をコマンド ライン上でソース ファイルと一緒に指定することはできません。",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' モジュールの解決方法を使用せずにオプション '--resolveJsonModule' を指定することはできません。",
"Options_Colon_6027": "オプション:",
"Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。",
"Output_file_0_from_project_1_does_not_exist_6309": "プロジェクト '{1}' からの出力ファイル '{0}' がありません",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "オーバーロード シグネチャは関数の実装に対応していません。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。",
@@ -644,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。",
"Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。",
"Print_this_message_6017": "このメッセージを表示します。",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "プロジェクト参照が円グラフを形成できません。循環が検出されました: {0}",
"Projects_to_reference_6300": "参照するプロジェクト",
"Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。",
"Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "型 '{1}' にプロパティ '{0}' は存在しません。'await' を使用していない可能性があります。",
@@ -691,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。",
"Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。",
"Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します",
"Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'",
"Remove_destructuring_90009": "非構造化を削除します",
"Remove_import_from_0_90005": "'{0}' からのインポートを削除",
"Remove_unreachable_code_95050": "到達できないコードを削除します",
"Replace_import_with_0_95015": "インポートを '{0}' に置換します。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。",
@@ -701,7 +720,7 @@
"Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。",
"Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。",
"Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。",
"Resolving_from_node_modules_folder_6118": "node_modules フォルダーから解決しています...",
"Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========",
"Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。",
@@ -800,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'Import.meta' メタ プロパティでは、'target' および 'module' コンパイラ オプションに対して 'ESNext' のみが許可されています。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' ステートメントの左側で型の注釈を使用することはできません。",
@@ -947,6 +967,7 @@
"_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}' には型の注釈がなく、直接または間接的に初期化子で参照されているため、暗黙的に 'any' 型が含まれています。",
"_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' はプリミティブですが、'{1}' はラッパー オブジェクトです。できれば '{0}' をご使用ください。",
"_0_is_declared_but_its_value_is_never_read_6133": "'{0}' が宣言されていますが、その値が読み取られることはありません。",
"_0_is_declared_but_never_used_6196": "'{0}' は宣言されましたが使用されませんでした。",
"_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。",
"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。",
"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。",
@@ -1011,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'パラメーター修飾子' を使用できるのは .ts ファイル内のみです。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' オプションが指定され、モジュール名 '{0}' と一致するパターンを検索します。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾子はプロパティ宣言またはインデックス シグネチャのみに使用できます。",
"require_call_may_be_converted_to_an_import_80005": "'require' の呼び出しはインポートに変換される可能性があります。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' オプションが設定され、このオプションを使用して相対モジュール名 '{0}' を解決します。",
"super_can_only_be_referenced_in_a_derived_class_2335": "'super' は、派生クラスでのみ参照できます。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' は、派生クラスのメンバーまたはオブジェクトのリテラル式のメンバーでのみ参照されます。",
+24 -2
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}'의 모든 선언에는 동일한 형식 매개 변수가 있어야 합니다.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "추상 메서드의 모든 선언은 연속적이어야 합니다.",
"All_destructured_elements_are_unused_6198": "구조 파괴된 요소가 모두 사용되지 않습니다.",
"All_imports_in_import_declaration_are_unused_6192": "가져오기 선언의 모든 가져오기가 사용되지 않습니다.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "기본 내보내기가 없는 모듈에서 기본 가져오기를 허용합니다. 여기서는 코드 내보내기에는 영향을 주지 않고 형식 검사만 합니다.",
"Allow_javascript_files_to_be_compiled_6102": "Javascript 파일을 컴파일하도록 허용합니다.",
@@ -133,6 +134,7 @@
"An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "비동기 함수 또는 메서드에는 유효한 대기 가능 반환 형식이 있어야 합니다.",
"An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "비동기 함수 또는 메서드는 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.",
"An_async_iterator_must_have_a_next_method_2519": "비동기 반복기에는 'next()' 메서드가 있어야 합니다.",
"An_element_access_expression_should_take_an_argument_1011": "요소 액세스 식은 인수를 사용해야 합니다.",
"An_enum_member_cannot_have_a_numeric_name_2452": "열거형 멤버는 숫자 이름을 가질 수 없습니다.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "내보내기 할당은 모듈에서만 사용할 수 있습니다.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "내보내기 할당은 다른 내보낸 요소가 있는 모듈에서 사용될 수 없습니다.",
@@ -219,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.",
"Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.",
@@ -259,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.",
"Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.",
"Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.",
"Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.",
"Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.",
@@ -270,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "파생 클래스의 생성자는 'super' 호출을 포함해야 합니다.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.",
"Convert_all_constructor_functions_to_classes_95045": "모든 생성자 함수를 클래스로 변환",
"Convert_all_require_to_import_95048": "모든 'require'를 'import'로 변환",
"Convert_all_to_default_imports_95035": "모든 항목을 기본 가져오기로 변환",
"Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환",
"Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환",
"Convert_require_to_import_95047": "'require'를 'import'로 변환",
"Convert_to_ES6_module_95017": "ES6 모듈로 변환",
"Convert_to_default_import_95013": "기본 가져오기로 변환",
"Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.",
@@ -325,8 +331,8 @@
"Duplicate_label_0_1114": "중복된 레이블 '{0}'입니다.",
"Duplicate_number_index_signature_2375": "중복 숫자 인덱스 시그니처입니다.",
"Duplicate_string_index_signature_2374": "중복 문자열 인덱스 시그니처입니다.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 모듈을 대상을 지정할 때에는 동적 가져오기를 사용할 수 없습니다.",
"Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "동적 가져오기는 '--module' 플래그가 'commonjs' 또는 'esNext'인 경우에만 지원됩니다.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.",
@@ -335,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "별도의 파일을 사용하는 대신 소스 맵과 함께 단일 파일을 내보냅니다.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.",
"Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.",
"Enable_project_compilation_6302": "프로젝트 컴파일을 사용하도록 설정",
"Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.",
"Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.",
@@ -396,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' 파일은 확장명이 지원되지 않으므로 건너뜁니다.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' 파일의 확장명이 지원되지 않습니다. 지원되는 확장명은 {1}뿐입니다.",
"File_0_is_not_a_module_2306": "'{0}' 파일은 모듈이 아닙니다.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' 파일이 프로젝트 파일 목록에 없습니다. 프로젝트는 모든 파일을 나열하거나 'include' 패턴을 사용해야 합니다.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' 파일이 'rootDir' '{1}' 아래에 있지 않습니다. 'rootDir'에는 모든 소스 파일이 포함되어 있어야 합니다.",
"File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.",
"File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...",
@@ -460,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "앰비언트 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "다중 선언이 포함된 열거형에서는 하나의 선언만 첫 번째 열거형 요소에 대한 이니셜라이저를 생략할 수 있습니다.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 열거형 선언에서 멤버 이니셜라이저는 상수 식이어야 합니다.",
"Include_modules_imported_with_json_extension_6197": "'.json' 확장을 사용하여 가져온 모듈을 포함합니다.",
"Index_signature_in_type_0_only_permits_reading_2542": "'{0}' 형식의 인덱스 시그니처는 읽기만 허용됩니다.",
"Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.",
"Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.",
@@ -558,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.",
"Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.",
"Move_to_a_new_file_95049": "새 파일로 이동",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.",
"Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.",
"NEWLINE_6061": "줄 바꿈",
@@ -599,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' 옵션은 '--module' 옵션을 지정하거나 'target' 옵션이 'ES2015' 이상인 경우에만 사용할 수 있습니다.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'paths' 옵션은 '--baseUrl' 옵션을 지정하지 않고 사용할 수 없습니다.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "명령줄에서 'project' 옵션을 원본 파일과 혼합하여 사용할 수 없습니다.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' 모듈 확인 전략 없이 '--resolveJsonModule' 옵션을 지정할 수 없습니다.",
"Options_Colon_6027": "옵션:",
"Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.",
"Output_file_0_from_project_1_does_not_exist_6309": "프로젝트 '{1}'의 출력 파일 '{0}'이(가) 존재하지 않습니다.",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "오버로드 시그니처가 함수 구현과 호환되지 않습니다.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.",
@@ -644,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.",
"Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.",
"Print_this_message_6017": "이 메시지를 출력합니다.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}",
"Projects_to_reference_6300": "참조할 프로젝트",
"Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.",
"Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "속성 '{0}'이(가) '{1}' 형식에 없습니다. 'await' 사용을 잊으셨나요?",
@@ -691,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.",
"Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.",
"Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거",
"Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거",
"Remove_destructuring_90009": "구조 파괴 제거",
"Remove_import_from_0_90005": "'{0}'에서 가져오기 제거",
"Remove_unreachable_code_95050": "접근할 수 없는 코드 제거",
"Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.",
@@ -701,7 +720,7 @@
"Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.",
"Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.",
"Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).",
"Resolving_from_node_modules_folder_6118": "node_modules 폴더에서 확인하는 중...",
"Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========",
"Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.",
@@ -800,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "'{0}' 구성 파일의 '파일' 목록이 비어 있습니다.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' 메타 속성은 'target' 및 'module' 컴파일러 옵션에 'ESNext'를 사용해야만 허용됩니다.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 문의 왼쪽에는 형식 주석을 사용할 수 없습니다.",
@@ -947,6 +967,7 @@
"_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "'{0}'은(는) 형식 주석이 없고 자체 이니셜라이저에서 직간접적으로 참조되므로 암시적으로 'any' 형식입니다.",
"_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "{0}'은(는) 기본 개체이지만 '{1}'은(는) 래퍼 개체입니다. 가능한 경우 '{0}'을(를) 사용하세요.",
"_0_is_declared_but_its_value_is_never_read_6133": "'{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.",
"_0_is_declared_but_never_used_6196": "'{0}'이(가) 선언되었지만 사용되지 않았습니다.",
"_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?",
"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.",
"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.",
@@ -1011,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.",
"require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 옵션이 설정되어 있습니다. 상대 모듈 이름 '{0}'을(를) 확인하려면 이 옵션을 사용합니다.",
"super_can_only_be_referenced_in_a_derived_class_2335": "파생 클래스에서만 'super'를 참조할 수 있습니다.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "파생 클래스 또는 개체 리터럴 식의 멤버에서만 'super'를 참조할 수 있습니다.",
+13
View File
@@ -94,6 +94,14 @@ declare function escape(string: string): string;
*/
declare function unescape(string: string): string;
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
declare type PropertyKey = string | number | symbol;
interface PropertyDescriptor {
@@ -20446,6 +20454,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
-8
View File
@@ -18,14 +18,6 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
+5
View File
@@ -16302,6 +16302,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+5
View File
@@ -16307,6 +16307,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+5
View File
@@ -16305,6 +16305,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+8
View File
@@ -28,4 +28,12 @@ interface RegExpExecArray {
groups?: {
[key: string]: string
}
}
interface RegExp {
/**
* Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression.
* Default is false. Read-only.
*/
readonly dotAll: boolean;
}
+8
View File
@@ -94,6 +94,14 @@ declare function escape(string: string): string;
*/
declare function unescape(string: string): string;
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
declare type PropertyKey = string | number | symbol;
interface PropertyDescriptor {
+13 -8
View File
@@ -94,6 +94,14 @@ declare function escape(string: string): string;
*/
declare function unescape(string: string): string;
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
declare type PropertyKey = string | number | symbol;
interface PropertyDescriptor {
@@ -5498,14 +5506,6 @@ declare namespace Reflect {
}
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): symbol;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
@@ -22115,6 +22115,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+5
View File
@@ -16304,6 +16304,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+5
View File
@@ -221,6 +221,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+21 -1
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Wszystkie deklaracje „{0}” muszą mieć identyczne parametry typu.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Wszystkie deklaracje metody abstrakcyjnej muszą występować obok siebie.",
"All_destructured_elements_are_unused_6198": "Wszystkie elementy, których strukturę usunięto, są nieużywane.",
"All_imports_in_import_declaration_are_unused_6192": "Wszystkie importy w deklaracji importu są nieużywane.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Zezwalaj na domyślne importy z modułów bez domyślnego eksportu. To nie wpływa na emitowanie kodu, a tylko na sprawdzanie typów.",
"Allow_javascript_files_to_be_compiled_6102": "Zezwalaj na kompilowanie plików JavaScript.",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null”.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null” lub „undefined”.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „undefined”.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Nie można poprzedzić projektu „{0}”, ponieważ nie ma on ustawionej właściwości „outFile”",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”",
"Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.",
"Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Projekty kompozytowe nie mogą wyłączyć emitowania deklaracji.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.",
"Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Konstruktory klas pochodnych muszą zawierać wywołanie „super”.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.",
"Convert_all_constructor_functions_to_classes_95045": "Przekonwertuj wszystkie funkcje konstruktora na klasy",
"Convert_all_require_to_import_95048": "Konwertuj wszystkie wywołania „require” na wywołania „import”",
"Convert_all_to_default_imports_95035": "Przekonwertuj wszystko na domyślne importowanie",
"Convert_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę",
"Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015",
"Convert_require_to_import_95047": "Konwertuj wywołanie „require” na wywołanie „import”",
"Convert_to_ES6_module_95017": "Konwertuj na moduł ES6",
"Convert_to_default_import_95013": "Konwertuj na import domyślny",
"Corrupted_locale_file_0_6051": "Uszkodzony plik ustawień regionalnych {0}.",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "Zduplikowana etykieta „{0}”.",
"Duplicate_number_index_signature_2375": "Zduplikowana sygnatura indeksu liczbowego.",
"Duplicate_string_index_signature_2374": "Zduplikowana sygnatura indeksu ciągu.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Nie można użyć dynamicznego importowania, gdy celem są moduły ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczne importowanie nie może mieć argumentów typu",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Import dynamiczny jest obsługiwany tylko wtedy, gdy flaga „--module” to „commonjs” lub „esNext”.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dynamiczne importowanie musi mieć jeden specyfikator jako argument.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Element niejawnie przyjmuje typ „any”, ponieważ wyrażenie indeksu ma typ inny niż „number”.",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emituj pojedynczy plik z mapami źródeł zamiast oddzielnego pliku.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emituj źródło razem z mapami źródłowymi w pojedynczym pliku; wymaga ustawienia opcji „--inlineSourceMap” lub „--sourceMap”.",
"Enable_all_strict_type_checking_options_6180": "Włącz wszystkie opcje ścisłego sprawdzania typów.",
"Enable_project_compilation_6302": "Włącz kompilację projektu",
"Enable_strict_checking_of_function_types_6186": "Włącz dokładne sprawdzanie typów funkcji.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.",
"Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "Plik „{0}” ma nieobsługiwane rozszerzenie, dlatego zostanie pominięty.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Plik „{0}” ma nieobsługiwane rozszerzenie. Obsługiwane są tylko rozszerzenia {1}.",
"File_0_is_not_a_module_2306": "Plik „{0}” nie jest modułem.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Plik „{0}” nie znajduje się na liście plików projektu. Projekty muszą zawierać listę wszystkich plików lub używać wzorca „include”.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Plik „{0}” nie znajduje się w katalogu „rootDir” „{1}”. Katalog „rootDir” powinien zawierać wszystkie pliki źródłowe.",
"File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.",
"File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "W deklaracjach wyliczenia otoczenia inicjator składowej musi być wyrażeniem stałym.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "W przypadku wyliczenia z wieloma deklaracjami tylko jedna deklaracja może pominąć inicjator dla pierwszego elementu wyliczenia.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "W deklaracjach wyliczeń ze specyfikatorem „const” inicjator składowej musi być wyrażeniem stałym.",
"Include_modules_imported_with_json_extension_6197": "Uwzględnij moduły zaimportowane z rozszerzeniem „json”",
"Index_signature_in_type_0_only_permits_reading_2542": "Sygnatura indeksu w typie „{0}” zezwala tylko na odczytywanie.",
"Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.",
"Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Nazwa modułu „{0}” została pomyślnie rozpoznana jako „{1}”. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Rodzaj rozpoznawania modułów nie został podany. Zostanie użyty rodzaj „{0}”.",
"Module_resolution_using_rootDirs_has_failed_6111": "Nie można rozpoznać modułów przy użyciu opcji „rootDirs”.",
"Move_to_a_new_file_95049": "Przenieś do nowego pliku",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Kolejne następujące po sobie separatory liczbowe nie są dozwolone.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Konstruktor nie może mieć wielu implementacji.",
"NEWLINE_6061": "NOWY WIERSZ",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Opcji „isolatedModules” można użyć tylko wtedy, gdy podano opcję „--module” lub opcja „target” określa cel „ES2015” lub wyższy.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Opcji „paths” nie można użyć bez podawania opcji „--baseUrl”.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Nie można mieszać opcji „project” z plikami źródłowymi w wierszu polecenia.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Nie można określić opcji „--resolveJsonModule” bez strategii rozpoznawania modułów „node”.",
"Options_Colon_6027": "Opcje:",
"Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.",
"Output_file_0_from_project_1_does_not_exist_6309": "Plik wyjściowy „{0}” z projektu „{1}” nie istnieje",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Plik wyjściowy „{0}” nie został utworzony na podstawie pliku źródłowego „{1}”.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "Sygnatura przeciążenia nie jest zgodna z implementacją funkcji.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.",
"Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.",
"Print_this_message_6017": "Wypisz ten komunikat.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}",
"Projects_to_reference_6300": "Projekty do przywołania",
"Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.",
"Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy zapomniano użyć elementu „await”?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.",
"Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.",
"Remove_all_unreachable_code_95051": "Usuń cały nieosiągalny kod",
"Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”",
"Remove_destructuring_90009": "Usuń usuwanie struktury",
"Remove_import_from_0_90005": "Usuń import z „{0}”",
"Remove_unreachable_code_95050": "Usuń nieosiągalny kod",
"Replace_import_with_0_95015": "Zamień import na element „{0}”.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "Lista „files” w pliku konfiguracji „{0}” jest pusta.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Pierwszym parametrem metody „then” obietnicy musi być wywołanie zwrotne.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Metawłaściwość „import.meta” jest dozwolona tylko w przypadku podania wartości „ESNext” dla opcji kompilatora „target” i „module”.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Lewa strona instrukcji „for...in” nie może być wzorcem usuwającym strukturę.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Lewa strona instrukcji „for...in” nie może używać adnotacji typu.",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modyfikatorów parametrów można używać tylko w pliku ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Opcja „paths” została określona. Wyszukiwanie wzorca zgodnego z nazwą modułu „{0}”.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Modyfikator „readonly” może występować jedynie w deklaracji właściwości lub sygnaturze indeksu.",
"require_call_may_be_converted_to_an_import_80005": "Wywołanie „require” może zostać przekonwertowane na wywołanie import.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Opcja „rootDirs” została ustawiona. Zostanie ona użyta do rozpoznania względnej nazwy modułu „{0}”.",
"super_can_only_be_referenced_in_a_derived_class_2335": "Element „super” może być przywoływany tylko w klasie pochodnej.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "Element „super” może być przywoływany jedynie w składowych klas pochodnych lub wyrażeń literałów obiektów.",
+2386
View File
File diff suppressed because it is too large Load Diff
+22 -2
View File
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'",
"Add_initializers_to_all_uninitialized_properties_95027": "Adicionar inicializadores a todas as propriedades não inicializadas",
"Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente",
"Add_missing_typeof_95052": "Adicionar typeof ausente",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Adicionar um qualificador a todas as variáveis não resolvidas correspondentes a um nome de membro",
"Add_to_all_uncalled_decorators_95044": "Adicionar '()' a todos os decoradores não chamados",
"Add_ts_ignore_to_all_error_messages_95042": "Adicionar '@ts-ignore' a todas as mensagens de erro",
@@ -117,6 +118,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Todas as declarações de '{0}' devem ter parâmetros de tipo idênticos.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Todas as declarações de um método abstrato devem ser consecutivas.",
"All_destructured_elements_are_unused_6198": "Todos os elementos desestruturados são inutilizados.",
"All_imports_in_import_declaration_are_unused_6192": "Nenhuma das importações na declaração de importação está sendo utilizada.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Permita importações padrão de módulos sem exportação padrão. Isso não afeta a emissão do código, apenas a verificação de digitação.",
"Allow_javascript_files_to_be_compiled_6102": "Permita que arquivos javascript sejam compilados.",
@@ -220,6 +222,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Não é possível invocar um objeto que é possivelmente 'nulo'.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Não é possível invocar um objeto que é possivelmente 'nulo' ou 'indefinido'.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Não é possível invocar um objeto que é possivelmente 'indefinido'.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Não é possível preceder o projeto '{0}' porque ele não tem o conjunto 'outFile'",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.",
"Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.",
@@ -260,6 +263,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.",
"Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Projetos compostos não podem desabilitar a emissão de declaração.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em uma enumeração com membros de valor de cadeia de caracteres.",
"Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.",
@@ -271,9 +275,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Construtores para classes derivadas devem conter uma chamada 'super'.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.",
"Convert_all_constructor_functions_to_classes_95045": "Converter todas as funções de construtor em classes",
"Convert_all_require_to_import_95048": "Converter todos os 'require' em 'import'",
"Convert_all_to_default_imports_95035": "Converter tudo para importações padrão",
"Convert_function_0_to_class_95002": "Converter função '{0}' em classe",
"Convert_function_to_an_ES2015_class_95001": "Converter função em uma classe ES2015",
"Convert_require_to_import_95047": "Converter 'require' em 'import'",
"Convert_to_ES6_module_95017": "Converter em módulo ES6",
"Convert_to_default_import_95013": "Converter para importação padrão",
"Corrupted_locale_file_0_6051": "Arquivo de localidade {0} corrompido.",
@@ -326,8 +332,8 @@
"Duplicate_label_0_1114": "Rótulo '{0}' duplicado.",
"Duplicate_number_index_signature_2375": "Assinatura de índice de número duplicado.",
"Duplicate_string_index_signature_2374": "Assinatura de índice de cadeia de caracteres duplicada.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "A importação dinâmica não pode ser usada ao destinar módulos de ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "A importação dinâmica não pode ter argumentos de tipo",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Só há suporte para importação dinâmica quando o sinalizador '--module' é 'commonjs' ou 'esNext'.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "A importação dinâmica deve ter um especificador como um argumento.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "O especificador da importação dinâmica deve ser do tipo 'string', mas aqui tem o tipo '{0}'.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "O elemento implicitamente tem um tipo 'any' porque a expressão de índice não é do tipo 'number'.",
@@ -336,6 +342,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Emitir um arquivo único com os mapas de origem em vez de arquivos separados.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Emitir a origem ao lado dos sourcemaps em um arquivo único; a definição requer '--inlineSourceMap' ou '--sourceMap'.",
"Enable_all_strict_type_checking_options_6180": "Habilitar todas as opções estritas de verificação de tipo.",
"Enable_project_compilation_6302": "Habilitar a compilação do projeto",
"Enable_strict_checking_of_function_types_6186": "Habilitar verificação estrita de tipos de função.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.",
"Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.",
@@ -397,6 +404,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "O arquivo '{0}' tem uma extensão sem suporte, portanto ele será ignorado.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "O arquivo '{0}' tem extensão sem suporte. As únicas extensões com suporte são {1}.",
"File_0_is_not_a_module_2306": "O arquivo '{0}' não é um módulo.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "O arquivo '{0}' não está na lista de arquivos de projeto. Os projetos devem listar todos os arquivos ou usar um padrão 'include'.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "O arquivo '{0}' não está em 'rootDir' '{1}'. Espera-se que 'rootDir' contenha todos os arquivos de origem.",
"File_0_not_found_6053": "Arquivo '{0}' não encontrado.",
"File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...",
@@ -461,6 +469,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações de enumeração de ambiente, o inicializador de membro deve ser uma expressão de constante.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em uma enumeração com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento de enumeração.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações de enumeração 'const', o inicializador de membro deve ser uma expressão de constante.",
"Include_modules_imported_with_json_extension_6197": "Incluir módulos importados com a extensão '.json'",
"Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.",
"Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.",
"Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.",
@@ -559,6 +568,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Nome do módulo '{0}' foi resolvido com sucesso '{1}'. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Resolução de tipo não foi especificado, usando '{0}'.",
"Module_resolution_using_rootDirs_has_failed_6111": "Falha na resolução de módulo usando 'rootDirs'.",
"Move_to_a_new_file_95049": "Mover para um novo arquivo",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Não são permitidos vários separadores numéricos consecutivos.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Não são permitidas várias implementações de construtor.",
"NEWLINE_6061": "NEWLINE",
@@ -600,8 +610,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "A opção 'paths' não pode ser usada sem se especificar a opção '--baseUrl'.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "A opção 'project' não pode ser mesclada com arquivos de origem em uma linha de comando.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "A opção '--resolveJsonModule' não pode ser especificada sem a estratégia de resolução de módulo de 'nó'.",
"Options_Colon_6027": "Opções:",
"Output_directory_for_generated_declaration_files_6166": "Diretório de saída para os arquivos de declaração gerados.",
"Output_file_0_from_project_1_does_not_exist_6309": "O arquivo de saída '{0}' do projeto '{1}' não existe",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "O arquivo de saída '{0}' não foi compilado do arquivo de origem '{1}'.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "A assinatura de sobrecarga não é compatível com a implementação da função.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Assinaturas de sobrecarga devem todas ser abstratas ou não abstratas.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Todas as assinaturas de sobrecarga devem ser ambiente ou não ambiente.",
@@ -645,6 +658,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.",
"Print_the_compiler_s_version_6019": "Imprima a versão do compilador.",
"Print_this_message_6017": "Imprima esta mensagem.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}",
"Projects_to_reference_6300": "Projetos para referência",
"Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.",
"Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?",
@@ -692,8 +707,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.",
"Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.",
"Remove_all_unreachable_code_95051": "Remover todo o código inacessível",
"Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'",
"Remove_destructuring_90009": "Remover desestruturação",
"Remove_import_from_0_90005": "Remover importação do '{0}'",
"Remove_unreachable_code_95050": "Remover código inacessível",
"Replace_import_with_0_95015": "Substitua a importação com '{0}'.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.",
@@ -801,7 +820,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "A lista de 'arquivos' no arquivo de configuração '{0}' está vazia.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "O primeiro parâmetro do método 'then' de uma promessa deve ser um retorno de chamada.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "O tipo global 'JSX.{0}' não pode ter mais de uma propriedade.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "A metapropriedade 'import.meta' é permitida apenas usando 'ESNext' para as opções de compilador 'target' e 'module'.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "O lado esquerdo de uma instrução 'for...in' não pode ser um padrão de desestruturação.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "O lado esquerdo de uma instrução 'for...in' não pode usar uma anotação de tipo.",
@@ -1014,6 +1033,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' só podem ser usados em um arquivo .ts.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "A opção 'paths' é especificada, procurando por um padrão para corresponder ao nome do módulo '{0}'.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "O modificador 'readonly' pode aparecer somente em uma declaração de propriedade ou assinatura de índice.",
"require_call_may_be_converted_to_an_import_80005": "A chamada 'require' pode ser convertida em uma importação.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "A opção 'rootDirs' está configurada, usando-a para resolver o nome de módulo relativo '{0}'.",
"super_can_only_be_referenced_in_a_derived_class_2335": "'super' só pode ser referenciado em uma classe derivada.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' pode ser referido somente em membros de classes derivadas ou expressões literais de objeto.",
+21 -1
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Все объявления \"{0}\" должны иметь одинаковые параметры типа.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Все объявления абстрактных методов должны быть последовательными.",
"All_destructured_elements_are_unused_6198": "Все деструктурированные элементы не используются.",
"All_imports_in_import_declaration_are_unused_6192": "Ни один из импортов в объявлении импорта не используется.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Разрешить импорт по умолчанию из модулей без экспорта по умолчанию. Это не повлияет на выведение кода — только на проверку типов.",
"Allow_javascript_files_to_be_compiled_6102": "Разрешить компиляцию файлов javascript.",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Не удается вызвать объект, который может иметь значение \"NULL\".",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Не удается вызвать объект, который может иметь значение \"NULL\" или \"undefined\".",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Не удается вызвать объект, который может иметь значение \"undefined\".",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Невозможно добавить проект \"{0}\" в начало, так как для него не задан outFile",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".",
"Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Компиляция проекта по заданному пути к файлу конфигурации или папке с файлом tsconfig.json.",
"Compiler_option_0_expects_an_argument_6044": "Параметр компилятора \"{0}\" ожидает аргумент.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "Параметр \"{0}\" компилятора требует значение типа {1}.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Составные проекты не могут отключать выпуск объявления.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Имена вычисляемых свойств запрещены в перечислениях.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Вычисленные значения запрещены в перечислении с членами, имеющими строковые значения.",
"Concatenate_and_emit_output_to_single_file_6001": "Связать и вывести результаты в один файл.",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Конструкторы производных классов должны содержать вызов super.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.",
"Convert_all_constructor_functions_to_classes_95045": "Преобразовать все функции конструктора в классы",
"Convert_all_require_to_import_95048": "Преобразовать все \"require\" в \"import\"",
"Convert_all_to_default_imports_95035": "Преобразовать все в импорт по умолчанию",
"Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс",
"Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015",
"Convert_require_to_import_95047": "Преобразовать \"require\" в \"import\"",
"Convert_to_ES6_module_95017": "Преобразовать в модуль ES6",
"Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию",
"Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "Повторяющаяся метка \"{0}\".",
"Duplicate_number_index_signature_2375": "Повторяющаяся сигнатура числового индекса.",
"Duplicate_string_index_signature_2374": "Повторяющаяся сигнатура строкового индекса.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "Динамический импорт не может использоваться с модулями ECMAScript 2015.",
"Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Динамический импорт поддерживается, только если флаг \"--module\" имеет значение \"commonjs\" или \"esNext\".",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "При динамическом импорте необходимо указать один описатель в качестве аргумента.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Элемент неявно содержит тип any, так как выражение индекса не имеет тип number.",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Порождать один файл с сопоставлениями источников, а не создавать отдельный файл.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Порождать источник вместе с sourcemap в одном файле (нужно задать параметр --inlineSourceMap или --sourceMap).",
"Enable_all_strict_type_checking_options_6180": "Включить все параметры строгой проверки типов.",
"Enable_project_compilation_6302": "Включить компиляцию проекта",
"Enable_strict_checking_of_function_types_6186": "Включение строгой проверки типов функций.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.",
"Enable_strict_null_checks_6113": "Включить строгие проверки NULL.",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "Файл \"{0}\" имеет неподдерживаемое разрешение, поэтому будет пропущен.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "Файл \"{0}\" имеет неподдерживаемое расширение. Поддерживаются только следующие расширения: {1}.",
"File_0_is_not_a_module_2306": "Файл \"{0}\" не является модулем.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "Файл \"{0}\" отсутствует в списке файлов проекта. Проекты должны перечислять все файлы или использовать шаблон включения.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "Файл \"{0}\" отсутствует в \"rootDir\" \"{1}\". Все исходные файлы должны находиться в каталоге \"rootDir\".",
"File_0_not_found_6053": "Файл \"{0}\" не найден.",
"File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Во внешних объявлениях перечислений инициализатор элемента должен быть константным выражением.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "В перечислении с несколькими объявлениями только одно объявление может опустить инициализатор для своего первого элемента перечисления.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "В инициализаторе элементов объявлений перечисления const должно быть константным выражением.",
"Include_modules_imported_with_json_extension_6197": "Включать модули, импортированные с расширением .json",
"Index_signature_in_type_0_only_permits_reading_2542": "Сигнатура индекса в типе \"{0}\" разрешает только чтение.",
"Index_signature_is_missing_in_type_0_2329": "В типе \"{0}\" отсутствует сигнатура индекса.",
"Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".",
"Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".",
"Move_to_a_new_file_95049": "Переместить в новый файл",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Использовать несколько последовательных числовых разделителей запрещено.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.",
"NEWLINE_6061": "НОВАЯ СТРОКА",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "Параметр isolatedModules можно использовать, только если указан параметр --module или если параметр target — ES2015 или выше.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "Параметр paths невозможно использовать без указания параметра \"--baseUrl\".",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "Параметр project не может быть указан вместе с исходными файлами в командной строке.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "Параметр \"--resolveJsonModule\" нельзя указать без стратегии разрешения модуля node.",
"Options_Colon_6027": "Параметры:",
"Output_directory_for_generated_declaration_files_6166": "Выходной каталог для создаваемых файлов объявления.",
"Output_file_0_from_project_1_does_not_exist_6309": "Выходной файл \"{0}\" из проекта \"{1}\" не существует",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Выходной файл \"{0}\" не создан из исходного файла \"{1}\".",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "Сигнатура перегрузки несовместима с реализацией функции.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Сигнатуры перегрузки должны быть абстрактными или неабстрактными.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Все сигнатуры перегрузки должны быть либо внешними, либо не внешними.",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.",
"Print_the_compiler_s_version_6019": "Печать версии компилятора.",
"Print_this_message_6017": "Напечатайте это сообщение.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Ссылки на проект не могут формировать циклический граф. Обнаружен цикл: {0}",
"Projects_to_reference_6300": "Проекты для ссылки",
"Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".",
"Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "Свойство \"{0}\" не существует в типе \"{1}\". Возможно, пропущено \"await\"?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.",
"Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Указанный в ссылке проект \"{0}\" должен иметь следующее значение параметра composite: true.",
"Remove_all_unreachable_code_95051": "Удалить весь недостижимый код",
"Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"",
"Remove_destructuring_90009": "Удалить деструктурирование",
"Remove_import_from_0_90005": "Удалить импорт из \"{0}\"",
"Remove_unreachable_code_95050": "Удалить недостижимый код",
"Replace_import_with_0_95015": "Замена импорта на \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "Метасвойство \"import.meta\" разрешено только при использовании \"ESNext\" для параметров компилятора \"target\" и \"module\".",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Левый операнд оператора for...in не может быть шаблоном деструктурирования.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "Левый операнд оператора for...in не может использовать аннотацию типа.",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Модификаторы параметров могут использоваться только в TS-файле.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Параметр paths указан, идет поиск шаблона, соответствующего имени модуля \"{0}\".",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "Модификатор readonly может отображаться только в объявлении свойства или сигнатуре индекса.",
"require_call_may_be_converted_to_an_import_80005": "Вызов \"require\" можно преобразовать в \"import\".",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "Параметр \"rootDirs\" задан; он используется для разрешения относительного имени модуля \"{0}\".",
"super_can_only_be_referenced_in_a_derived_class_2335": "Ссылка на super может указываться только в производном классе.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "На super можно ссылаться только в элементах производных классов или литеральных выражениях объекта.",
+24 -3
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.",
"All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.",
"All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.",
"Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.",
@@ -133,6 +134,7 @@
"An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Zaman uyumsuz bir işlev veya metot, geçerli bir beklenebilir dönüş türüne sahip olmalıdır.",
"An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Zaman uyumsuz bir işlevin veya metodun 'Promise' döndürmesi gerekir. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ifadesini ekleyin.",
"An_async_iterator_must_have_a_next_method_2519": "Zaman uyumsuz yineleyicinin bir 'next()' metodu olmalıdır.",
"An_element_access_expression_should_take_an_argument_1011": "Bir öğe erişimi ifadesi bir bağımsız değişken almalıdır.",
"An_enum_member_cannot_have_a_numeric_name_2452": "Sabit listesi üyesi, sayısal bir ada sahip olamaz.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Dışarı aktarma ataması yalnızca bir modülde kullanılabilir.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Dışarı aktarma ataması, dışarı aktarılmış diğer öğelere sahip bir modülde kullanılamaz.",
@@ -219,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.",
"Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.",
"Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.",
@@ -259,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Yapılandırma dosyasının yolu veya 'tsconfig.json' dosyasını içeren klasörün yolu belirtilen projeyi derleyin.",
"Compiler_option_0_expects_an_argument_6044": "'{0}' derleyici seçeneği, bağımsız değişken bekliyor.",
"Compiler_option_0_requires_a_value_of_type_1_5024": "'{0}' derleyici seçeneği, {1} türünde bir değer gerektiriyor.",
"Composite_projects_may_not_disable_declaration_emit_6304": "Bileşik projeler, bildirim gösterimini devre dışı bırakamaz.",
"Computed_property_names_are_not_allowed_in_enums_1164": "Sabit listelerinde hesaplanan özellik adına izin verilmiyor.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Dize değeri içeren üyelerin bulunduğu bir sabit listesinde hesaplanan değerlere izin verilmez.",
"Concatenate_and_emit_output_to_single_file_6001": "Çıktıyı tek dosyaya birleştirin ve yayın.",
@@ -270,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "Türetilmiş sınıflara ilişkin oluşturucular bir 'super' çağrısı içermelidir.",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.",
"Convert_all_constructor_functions_to_classes_95045": "Tüm oluşturucu işlevleri sınıflara dönüştür",
"Convert_all_require_to_import_95048": "Tüm 'require' öğelerini 'import' olarak dönüştür",
"Convert_all_to_default_imports_95035": "Tümünü varsayılan içeri aktarmalara dönüştür",
"Convert_function_0_to_class_95002": "'{0}' işlevini sınıfa dönüştür",
"Convert_function_to_an_ES2015_class_95001": "İşlevi bir ES2015 sınıfına dönüştür",
"Convert_require_to_import_95047": "'require' öğesini 'import' olarak dönüştür",
"Convert_to_ES6_module_95017": "ES6 modülüne dönüştür",
"Convert_to_default_import_95013": "Varsayılan içeri aktarmaya dönüştür",
"Corrupted_locale_file_0_6051": "{0} yerel ayar dosyası bozuk.",
@@ -325,8 +331,8 @@
"Duplicate_label_0_1114": "'{0}' etiketi yineleniyor.",
"Duplicate_number_index_signature_2375": "Dizin imzasında yinelenen numara.",
"Duplicate_string_index_signature_2374": "Dizin imzasında yinelenen dize.",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 modülleri hedeflenirken dinamik içeri aktarma kullanılamaz.",
"Dynamic_import_cannot_have_type_arguments_1326": "Dinamik içeri aktarma, tür bağımsız değişkenleri içeremez",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dinamik içeri aktarma yalnızca '--module' bayrağı 'commonjs' veya 'esNext' olduğunda desteklenir.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "Dinamik içeri aktarma, bağımsız değişken olarak bir tanımlayıcı içermelidir.",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Dinamik içeri aktarmanın tanımlayıcısı 'string' türünde olmalıdır, ancak buradaki tür: '{0}'.",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "Dizin ifadesi 'number' türünde olmadığından, öğe örtük olarak 'any' türü içeriyor.",
@@ -335,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Ayrı bir dosya oluşturmak yerine, kaynak eşlemeleri içeren tek bir dosya gösterin.",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Kaynağı, kaynak eşlemeleri ile birlikte tek bir dosya içinde gösterin; '--inlineSourceMap' veya '--sourceMap' öğesinin ayarlanmasını gerektirir.",
"Enable_all_strict_type_checking_options_6180": "Tüm katı tür denetleme seçeneklerini etkinleştirin.",
"Enable_project_compilation_6302": "Proje derlemeyi etkinleştir",
"Enable_strict_checking_of_function_types_6186": "İşlev türleri üzerinde katı denetimi etkinleştirin.",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.",
"Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.",
@@ -396,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "'{0}' dosyasının desteklenmeyen bir uzantısı olduğundan dosya atlanıyor.",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "'{0}' dosyası desteklenmeyen uzantıya sahip. Yalnızca {1} uzantıları desteklenir.",
"File_0_is_not_a_module_2306": "'{0}' dosyası bir modül değil.",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "'{0}' dosyası, proje dosyası listesinde değil. Projelerin tüm dosyaları listelemesi veya bir 'include' düzeni kullanması gerekir.",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "'{0}' dosyası, 'rootDir' '{1}' dizininde değil. 'rootDir' dizininin tüm kaynak dosyalarını içermesi bekleniyor.",
"File_0_not_found_6053": "'{0}' dosyası bulunamadı.",
"File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...",
@@ -460,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip sabit listesinde yalnızca bir bildirim ilk sabit listesi öğesine ait başlatıcıyı atlayabilir.",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.",
"Include_modules_imported_with_json_extension_6197": "'.json' uzantısıyla içeri aktarılan modülleri dahil et",
"Index_signature_in_type_0_only_permits_reading_2542": "'{0}' türündeki dizin imzası yalnızca okumaya izin veriyor.",
"Index_signature_is_missing_in_type_0_2329": "'{0}' türündeki dizin imzası yok.",
"Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.",
@@ -558,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== '{0}' modül adı '{1}' öğesine başarıyla çözümlendi. ========",
"Module_resolution_kind_is_not_specified_using_0_6088": "Modül çözümleme türü belirtilmedi, '{0}' kullanılıyor.",
"Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' kullanarak modül çözümleme başarısız oldu.",
"Move_to_a_new_file_95049": "Yeni bir dosyaya taşı",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Birbirini izleyen birden çok sayısal ayırıcıya izin verilmez.",
"Multiple_constructor_implementations_are_not_allowed_2392": "Birden çok oluşturucu uygulamasına izin verilmez.",
"NEWLINE_6061": "YENİ SATIR",
@@ -599,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "'isolatedModules' seçeneği, yalnızca '--module' sağlandığında veya 'target' seçeneği 'ES2015' veya daha yüksek bir sürüm değerine sahip olduğunda kullanılabilir.",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "'Paths' seçeneği, '--baseUrl' seçeneği belirtilmeden kullanılamaz.",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "'project' seçeneği, komut satırındaki kaynak dosyalarıyla karıştırılamaz.",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "'node' modül çözümleme stratejisi olmadan '--resolveJsonModule' seçeneği belirtilemez.",
"Options_Colon_6027": "Seçenekler:",
"Output_directory_for_generated_declaration_files_6166": "Oluşturulan bildirim dosyaları için çıkış dizini.",
"Output_file_0_from_project_1_does_not_exist_6309": "'{1}' projesinden '{0}' çıkış dosyası yok",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "Çıkış dosyası '{0}' '{1}' kaynak dosyasından oluşturulmamış.",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "Aşırı yükleme imzası işlev uygulamasıyla uyumlu değil.",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Aşırı yükleme imzalarının hepsi soyut veya soyut olmayan olmalıdır.",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Aşırı yükleme imzalarının tümü çevresel veya çevresel olmayan türde olmalıdır.",
@@ -644,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "Oluşturulan dosyalardan, derlemenin parçası olanların adlarını yazdırın.",
"Print_the_compiler_s_version_6019": "Derleyici sürümünü yazdır.",
"Print_this_message_6017": "Bu iletiyi yazdır.",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Proje başvuruları döngüsel bir grafik formu oluşturamaz. Döngü tespit edildi: {0}",
"Projects_to_reference_6300": "Başvurulacak projeler",
"Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.",
"Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "'{0}' özelliği '{1}' türü üzerinde yok. 'await' kullanmayı mı unuttunuz?",
@@ -691,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Belirtilen 'any' türüne sahip ifade ve bildirimlerde hata oluştur.",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.",
"Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.",
"Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır",
"Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır",
"Remove_destructuring_90009": "Yıkmayı kaldır",
"Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır",
"Remove_unreachable_code_95050": "Erişilemeyen kodları kaldır",
"Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.",
@@ -701,7 +720,7 @@
"Report_errors_on_unused_parameters_6135": "Kullanılmayan parametrelerdeki hataları bildirin.",
"Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.",
"Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki önbellekte bulundu.",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolve 'keyof' to string valued property names only (no numbers or symbols).",
"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'Keyof' değerini yalnızca dize değerli özellik adlarına (sayılar veya simgeler olmadan) çözümleyin.",
"Resolving_from_node_modules_folder_6118": "Node_modules klasöründen çözümleniyor...",
"Resolving_module_0_from_1_6086": "======== '{0}' modülü '{1}' öğesinden çözümleniyor. ========",
"Resolving_module_name_0_relative_to_base_url_1_2_6094": "'{0}' modül adı, '{1}' - '{2}' temel url'sine göre çözümleniyor.",
@@ -800,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "'{0}' yapılandırma dosyasındaki 'dosyalar' listesi boş.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise'in 'then' metodunun ilk parametresi, bir geri arama parametresi olmalıdır.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "'JSX.{0}' genel türü birden fazla özelliğe sahip olamaz.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "'import.meta' meta özelliğine yalnızca 'target' ve 'module' derleyici seçenekleri için 'ESNext' kullanıldığında izin verilir.",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' deyiminin sol tarafı yok etme deseni olamaz.",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' deyiminin sol tarafında tür ek açıklaması kullanılamaz.",
@@ -947,7 +967,7 @@
"_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022": "Bir tür ek açıklamasına sahip olmadığından ve kendi başlatıcısında doğrudan veya dolaylı olarak başvurulduğundan, '{0}' öğesi örtük olarak 'any' türüne sahip.",
"_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692": "'{0}' temel elemandır ancak '{1}' sarmalayıcı nesnedir. Mümkün olduğunda '{0}' kullanmayı tercih edin.",
"_0_is_declared_but_its_value_is_never_read_6133": "'{0}' bildirildi ancak değeri hiç okunmadı.",
"_0_is_declared_but_never_used_6196": "'{0}' is declared but never used.",
"_0_is_declared_but_never_used_6196": "'{0}' bildirildi ancak hiç kullanılmadı.",
"_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}', '{1}' anahtar sözcüğü için geçerli bir meta özellik değil. Bunu mu demek istediniz: '{2}'?",
"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' öğesine kendi temel ifadesinde doğrudan veya dolaylı olarak başvuruluyor.",
"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' öğesine kendi tür ek açıklamasında doğrudan veya dolaylı olarak başvuruluyor.",
@@ -1012,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' yalnızca bir .ts dosyasında kullanılabilir.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' seçeneği belirtildi, '{0}' modül adıyla eşleşen bir desen aranıyor.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' değiştiricisi yalnızca özellik bildiriminde ya da dizin imzasında görünebilir.",
"require_call_may_be_converted_to_an_import_80005": "'require' çağrısı bir import olarak dönüştürülebilir.",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' seçeneği ayarlandı, '{0}' göreli modül adını çözümlemek için bu değer kullanılıyor.",
"super_can_only_be_referenced_in_a_derived_class_2335": "'super' öğesine yalnızca bir türetilmiş sınıfta başvurulabilir.",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "'super' değerine yalnızca türetilen sınıfların üyelerinde ya da nesne değişmez ifadelerinde başvurulabilir.",
-3436
View File
File diff suppressed because it is too large Load Diff
+3081 -3343
View File
File diff suppressed because it is too large Load Diff
-1
View File
File diff suppressed because one or more lines are too long
+4977 -2409
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+231 -70
View File
@@ -337,32 +337,36 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
JSDocTypeExpression = 275,
JSDocAllType = 276,
JSDocUnknownType = 277,
JSDocNullableType = 278,
JSDocNonNullableType = 279,
JSDocOptionalType = 280,
JSDocFunctionType = 281,
JSDocVariadicType = 282,
JSDocComment = 283,
JSDocTypeLiteral = 284,
JSDocTag = 285,
JSDocAugmentsTag = 286,
JSDocClassTag = 287,
JSDocParameterTag = 288,
JSDocReturnTag = 289,
JSDocTypeTag = 290,
JSDocTemplateTag = 291,
JSDocTypedefTag = 292,
JSDocPropertyTag = 293,
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
UnparsedSource = 275,
InputFiles = 276,
JSDocTypeExpression = 277,
JSDocAllType = 278,
JSDocUnknownType = 279,
JSDocNullableType = 280,
JSDocNonNullableType = 281,
JSDocOptionalType = 282,
JSDocFunctionType = 283,
JSDocVariadicType = 284,
JSDocComment = 285,
JSDocTypeLiteral = 286,
JSDocSignature = 287,
JSDocTag = 288,
JSDocAugmentsTag = 289,
JSDocClassTag = 290,
JSDocCallbackTag = 291,
JSDocParameterTag = 292,
JSDocReturnTag = 293,
JSDocTypeTag = 294,
JSDocTemplateTag = 295,
JSDocTypedefTag = 296,
JSDocPropertyTag = 297,
SyntaxList = 298,
NotEmittedStatement = 299,
PartiallyEmittedExpression = 300,
CommaListExpression = 301,
MergeDeclarationMarker = 302,
EndOfDeclarationMarker = 303,
Count = 304,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +392,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
FirstJSDocNode = 275,
LastJSDocNode = 293,
FirstJSDocTagNode = 285,
LastJSDocTagNode = 293
FirstJSDocNode = 277,
LastJSDocNode = 297,
FirstJSDocTagNode = 288,
LastJSDocTagNode = 297
}
enum NodeFlags {
None = 0,
@@ -415,6 +419,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1154,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
* A list of comma-seperated expressions. This node is only created by transformations.
* A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1277,7 +1282,7 @@ declare namespace ts {
block: Block;
}
type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature;
interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
name?: Identifier;
@@ -1534,6 +1539,19 @@ declare namespace ts {
name?: Identifier;
typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
parent: JSDoc;
kind: SyntaxKind.JSDocCallbackTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression: JSDocSignature;
}
interface JSDocSignature extends JSDocType, Declaration {
kind: SyntaxKind.JSDocSignature;
typeParameters?: ReadonlyArray<JSDocTemplateTag>;
parameters: ReadonlyArray<JSDocParameterTag>;
type: JSDocReturnTag | undefined;
}
interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
parent: JSDoc;
name: EntityName;
@@ -1644,12 +1662,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
prepends: ReadonlyArray<InputFiles | UnparsedSource>;
sourceFiles: ReadonlyArray<SourceFile>;
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptText: string;
declarationText: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
text: string;
}
interface JsonSourceFile extends SourceFile {
jsonObject?: ObjectLiteralExpression;
statements: NodeArray<JsonObjectExpressionStatement>;
}
interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
kind: SyntaxKind.PrefixUnaryExpression;
operator: SyntaxKind.MinusToken;
operand: NumericLiteral;
}
interface JsonObjectExpressionStatement extends ExpressionStatement {
expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
}
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1743,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
}
interface ResolvedProjectReference {
commandLine: ParsedCommandLine;
sourceFile: SourceFile;
}
interface CustomTransformers {
/** Custom transformers to evaluate before built-in transformations. */
/** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in transformations. */
/** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in .d.ts transformations. */
afterDeclarations?: TransformerFactory<Bundle | SourceFile>[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,7 +1898,9 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
@@ -2217,6 +2264,7 @@ declare namespace ts {
objectType: Type;
indexType: Type;
constraint?: Type;
simplified?: Type;
}
type TypeVariable = TypeParameter | IndexedAccessType;
interface IndexType extends InstantiableType {
@@ -2251,7 +2299,7 @@ declare namespace ts {
Construct = 1
}
interface Signature {
declaration?: SignatureDeclaration;
declaration?: SignatureDeclaration | JSDocSignature;
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
@@ -2274,7 +2322,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
interface JsFileExtensionInfo {
/** @deprecated Use FileExtensionInfo instead. */
type JsFileExtensionInfo = FileExtensionInfo;
interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2372,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | null | undefined;
interface ProjectReference {
/** A normalized path on disk */
path: string;
/** The path as the user originally wrote it */
originalPath?: string;
/** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
/** True if it is intended that this reference form a circularity */
circular?: boolean;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2438,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2454,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
[option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2499,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
JSON = 6
JSON = 6,
/**
* Used on extensions that doesn't define the ScriptKind but the content defines it.
* Deferred extensions are going to be included in all project contexts.
*/
Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2514,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2526,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
projectReferences?: ReadonlyArray<ProjectReference>;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
@@ -2469,8 +2538,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
projectReferences: ReadonlyArray<ProjectReference> | undefined;
wildcardDirectories: MapLike<WatchDirectoryFlags>;
}
interface CreateProgramOptions {
rootNames: ReadonlyArray<string>;
options: CompilerOptions;
projectReferences?: ReadonlyArray<ProjectReference>;
host?: CompilerHost;
oldProgram?: Program;
configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>;
}
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2639,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
readDirectory?(rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -2918,10 +2997,11 @@ declare namespace ts {
readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[];
getModifiedTime?(path: string): Date;
/**
* This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
/** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -3298,6 +3378,8 @@ declare namespace ts {
function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag;
function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag;
function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral;
function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag;
function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
/**
@@ -3423,6 +3505,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3811,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray<Expression>): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
function createInputFiles(javascript: string, declaration: string): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray<Statement>): CallExpression;
@@ -3792,6 +3878,7 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
function moveSyntheticComments<T extends Node>(node: T, original: Node): T;
/**
* Gets the constant value to emit for an expression.
*/
@@ -3935,6 +4022,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): Program;
}
declare namespace ts {
@@ -4074,7 +4162,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): BuilderProgram;
}
declare namespace ts {
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>) => T;
@@ -4137,15 +4224,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Host to create watch with config file
*/
@@ -4192,6 +4270,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray<string>, readFile?: (path: string) => string | undefined): ParsedCommandLine;
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
*/
interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
getCurrentDirectory(): string;
}
/**
* Reads the config file, reports errors if any and exits if the config file cannot be found
*/
function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4311,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4323,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4331,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4350,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
getWidth(sourceFile?: SourceFile): number;
getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4462,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getProjectReferences?(): ReadonlyArray<ProjectReference> | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4378,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -4393,6 +4493,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4542,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray<number>, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray<CodeFixAction>;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise<ApplyCodeActionCommandResult>;
@@ -4465,9 +4567,10 @@ declare namespace ts {
fileName: string;
}
type OrganizeImportsScope = CombinedCodeFixScope;
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
/** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
triggerCharacter?: string;
triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4534,6 +4637,7 @@ declare namespace ts {
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
/** Description of the code action to display in the UI of the editor */
@@ -4620,6 +4724,12 @@ declare namespace ts {
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
/**
* If the span represents a location that was remapped (e.g. via a .d.ts.map file),
* then the original filename and span will be specified here
*/
originalTextSpan?: TextSpan;
originalFileName?: string;
}
interface RenameLocation extends DocumentSpan {
}
@@ -4717,9 +4827,7 @@ declare namespace ts {
insertSpaceBeforeTypeAnnotation?: boolean;
indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean;
}
interface DefinitionInfo {
fileName: string;
textSpan: TextSpan;
interface DefinitionInfo extends DocumentSpan {
kind: ScriptElementKind;
name: string;
containerKind: ScriptElementKind;
@@ -4865,6 +4973,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
/**
* Classification of the contents of the span
*/
kind: OutliningSpanKind;
}
enum OutliningSpanKind {
/** Single or multi-line comments */
Comment = "comment",
/** Sections marked by '// #region' and '// #endregion' comments */
Region = "region",
/** Declarations and expressions */
Code = "code",
/** Contiguous blocks of import declarations */
Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5110,9 @@ declare namespace ts {
/**
* <JsxTagName attribute1 attribute2={0} />
*/
jsxAttribute = "JSX attribute"
jsxAttribute = "JSX attribute",
/** String literal */
string = "string"
}
enum ScriptElementKindModifier {
none = "",
@@ -5348,6 +5472,7 @@ declare namespace ts.server {
configHasFilesProperty: boolean;
configHasIncludeProperty: boolean;
configHasExcludeProperty: boolean;
projectReferences: ReadonlyArray<ProjectReference> | undefined;
/**
* these fields can be present in the project file
*/
@@ -5587,6 +5712,10 @@ declare namespace ts.server.protocol {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
/**
* Classification of the contents of the span
*/
kind: OutliningSpanKind;
}
/**
* Response to OutliningSpansRequest request.
@@ -6318,7 +6447,7 @@ declare namespace ts.server.protocol {
/**
* The host's additional supported .js file extensions
*/
extraFileExtensions?: JsFileExtensionInfo[];
extraFileExtensions?: FileExtensionInfo[];
}
/**
* Configure request; value of command field is "configure". Specifies
@@ -6682,6 +6811,7 @@ declare namespace ts.server.protocol {
command: CommandTypes.Formatonkey;
arguments: FormatOnKeyRequestArgs;
}
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
/**
* Arguments for completions messages.
*/
@@ -6690,7 +6820,7 @@ declare namespace ts.server.protocol {
* Optional prefix to apply to possible completions.
*/
prefix?: string;
triggerCharacter?: string;
triggerCharacter?: CompletionsTriggerCharacter;
/**
* @deprecated Use UserPreferences.includeCompletionsForModuleExports
*/
@@ -7470,6 +7600,7 @@ declare namespace ts.server.protocol {
*/
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface CompilerOptions {
allowJs?: boolean;
@@ -7523,6 +7654,7 @@ declare namespace ts.server.protocol {
project?: string;
reactNamespace?: string;
removeComments?: boolean;
references?: ProjectReference[];
rootDir?: string;
rootDirs?: string[];
skipLibCheck?: boolean;
@@ -7535,6 +7667,7 @@ declare namespace ts.server.protocol {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget | ts.ScriptTarget;
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
typeRoots?: string[];
@@ -7633,7 +7766,7 @@ declare namespace ts.server {
enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>): void;
attach(projectService: ProjectService): void;
onProjectClosed(p: Project): void;
readonly globalTypingsCacheLocation: string;
readonly globalTypingsCacheLocation: string | undefined;
}
const nullTypingsInstaller: ITypingsInstaller;
}
@@ -7710,7 +7843,7 @@ declare namespace ts.server {
private readonly cancellationToken;
isNonTsProject(): boolean;
isJsOnlyProject(): boolean;
static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {};
static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined;
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
private readonly typingsCache;
@@ -7718,6 +7851,7 @@ declare namespace ts.server {
getCompilerOptions(): CompilerOptions;
getNewLine(): string;
getProjectVersion(): string;
getProjectReferences(): ReadonlyArray<ProjectReference> | undefined;
getScriptFileNames(): string[];
private getOrCreateScriptInfoAndAttachToProject;
getScriptKind(fileName: string): ScriptKind;
@@ -7731,6 +7865,7 @@ declare namespace ts.server {
readFile(fileName: string): string | undefined;
fileExists(file: string): boolean;
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[];
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists(path: string): boolean;
getDirectories(path: string): string[];
@@ -7784,13 +7919,15 @@ declare namespace ts.server {
private detachScriptInfoFromProject;
private addMissingFileWatcher;
private isWatchedMissingFile;
getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo;
getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined;
getScriptInfo(uncheckedFileName: string): ScriptInfo;
filesToString(writeProjectFileNames: boolean): string;
setCompilerOptions(compilerOptions: CompilerOptions): void;
protected removeRoot(info: ScriptInfo): void;
protected enableGlobalPlugins(): void;
protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void;
/** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
refreshDiagnostics(): void;
private enableProxy;
}
/**
@@ -7817,6 +7954,7 @@ declare namespace ts.server {
*/
class ConfiguredProject extends Project {
compileOnSaveEnabled: boolean;
private projectReferences;
private typeAcquisition;
private directoriesWatchedForWildcards;
readonly canonicalConfigFilePath: NormalizedPath;
@@ -7829,6 +7967,8 @@ declare namespace ts.server {
*/
updateGraph(): boolean;
getConfigFilePath(): NormalizedPath;
getProjectReferences(): ReadonlyArray<ProjectReference> | undefined;
updateReferences(refs: ReadonlyArray<ProjectReference> | undefined): void;
enablePlugins(): void;
/**
* Get the errors that dont have any file name associated
@@ -7864,6 +8004,7 @@ declare namespace ts.server {
const ConfigFileDiagEvent = "configFileDiag";
const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
const ProjectInfoTelemetryEvent = "projectInfo";
const OpenFileInfoTelemetryEvent = "openFileInfo";
interface ProjectsUpdatedInBackgroundEvent {
eventName: typeof ProjectsUpdatedInBackgroundEvent;
data: {
@@ -7912,6 +8053,18 @@ declare namespace ts.server {
/** TypeScript version used by the server. */
readonly version: string;
}
/**
* Info that we may send about a file that was just opened.
* Info about a file will only be sent once per session, even if the file changes in ways that might affect the info.
* Currently this is only sent for '.js' files.
*/
interface OpenFileInfoTelemetryEvent {
readonly eventName: typeof OpenFileInfoTelemetryEvent;
readonly data: OpenFileInfoTelemetryEventData;
}
interface OpenFileInfoTelemetryEventData {
readonly info: OpenFileInfo;
}
interface ProjectInfoTypeAcquisitionData {
readonly enable: boolean;
readonly include: boolean;
@@ -7923,8 +8076,12 @@ declare namespace ts.server {
readonly ts: number;
readonly tsx: number;
readonly dts: number;
readonly deferred: number;
}
type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent;
interface OpenFileInfo {
readonly checkJs: boolean;
}
type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent;
type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void;
interface SafeList {
[name: string]: {
@@ -7947,7 +8104,7 @@ declare namespace ts.server {
formatCodeOptions: FormatCodeSettings;
preferences: UserPreferences;
hostInfo: string;
extraFileExtensions?: JsFileExtensionInfo[];
extraFileExtensions?: FileExtensionInfo[];
}
interface OpenConfiguredProjectResult {
configFileName?: NormalizedPath;
@@ -7975,6 +8132,7 @@ declare namespace ts.server {
* Container of all known scripts
*/
private readonly filenameToScriptInfo;
private readonly allJsFilesForOpenFileTelemetry;
/**
* maps external project file name to list of config files that were the part of this project
*/
@@ -8043,7 +8201,6 @@ declare namespace ts.server {
updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void;
private delayEnsureProjectForOpenFiles;
private delayUpdateProjectGraph;
private sendProjectsUpdatedInBackgroundEvent;
private delayUpdateProjectGraphs;
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void;
findProject(projectName: string): Project | undefined;
@@ -8180,6 +8337,7 @@ declare namespace ts.server {
openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult;
private findExternalProjectContainingOpenScriptInfo;
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult;
private telemetryOnOpenFile;
/**
* Close file whose contents is managed by the client
* @param filename is absolute pathname
@@ -8195,6 +8353,7 @@ declare namespace ts.server {
resetSafeList(): void;
applySafeList(proj: protocol.ExternalProject): NormalizedPath[];
openExternalProject(proj: protocol.ExternalProject): void;
hasDeferredExtension(): boolean;
}
}
declare namespace ts.server {
@@ -8280,6 +8439,7 @@ declare namespace ts.server {
private getDefinition;
private getDefinitionAndBoundSpan;
private mapDefinitionInfo;
private static mapToOriginalLocation;
private toFileSpan;
private getTypeDefinition;
private getImplementation;
@@ -8353,6 +8513,7 @@ declare namespace ts.server {
private mapTextChangesToCodeEdits;
private mapTextChangesToCodeEditsUsingScriptinfo;
private convertTextChangeToCodeEdit;
private convertNewFileTextChangeToCodeEdit;
private getBraceMatching;
private getDiagnosticsForProject;
getCanonicalFileName(fileName: string): string;
+5899 -3160
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+186 -62
View File
@@ -337,32 +337,36 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
JSDocTypeExpression = 275,
JSDocAllType = 276,
JSDocUnknownType = 277,
JSDocNullableType = 278,
JSDocNonNullableType = 279,
JSDocOptionalType = 280,
JSDocFunctionType = 281,
JSDocVariadicType = 282,
JSDocComment = 283,
JSDocTypeLiteral = 284,
JSDocTag = 285,
JSDocAugmentsTag = 286,
JSDocClassTag = 287,
JSDocParameterTag = 288,
JSDocReturnTag = 289,
JSDocTypeTag = 290,
JSDocTemplateTag = 291,
JSDocTypedefTag = 292,
JSDocPropertyTag = 293,
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
UnparsedSource = 275,
InputFiles = 276,
JSDocTypeExpression = 277,
JSDocAllType = 278,
JSDocUnknownType = 279,
JSDocNullableType = 280,
JSDocNonNullableType = 281,
JSDocOptionalType = 282,
JSDocFunctionType = 283,
JSDocVariadicType = 284,
JSDocComment = 285,
JSDocTypeLiteral = 286,
JSDocSignature = 287,
JSDocTag = 288,
JSDocAugmentsTag = 289,
JSDocClassTag = 290,
JSDocCallbackTag = 291,
JSDocParameterTag = 292,
JSDocReturnTag = 293,
JSDocTypeTag = 294,
JSDocTemplateTag = 295,
JSDocTypedefTag = 296,
JSDocPropertyTag = 297,
SyntaxList = 298,
NotEmittedStatement = 299,
PartiallyEmittedExpression = 300,
CommaListExpression = 301,
MergeDeclarationMarker = 302,
EndOfDeclarationMarker = 303,
Count = 304,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +392,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
FirstJSDocNode = 275,
LastJSDocNode = 293,
FirstJSDocTagNode = 285,
LastJSDocTagNode = 293
FirstJSDocNode = 277,
LastJSDocNode = 297,
FirstJSDocTagNode = 288,
LastJSDocTagNode = 297
}
enum NodeFlags {
None = 0,
@@ -415,6 +419,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1154,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
* A list of comma-seperated expressions. This node is only created by transformations.
* A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1277,7 +1282,7 @@ declare namespace ts {
block: Block;
}
type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature;
interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
name?: Identifier;
@@ -1534,6 +1539,19 @@ declare namespace ts {
name?: Identifier;
typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
parent: JSDoc;
kind: SyntaxKind.JSDocCallbackTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression: JSDocSignature;
}
interface JSDocSignature extends JSDocType, Declaration {
kind: SyntaxKind.JSDocSignature;
typeParameters?: ReadonlyArray<JSDocTemplateTag>;
parameters: ReadonlyArray<JSDocParameterTag>;
type: JSDocReturnTag | undefined;
}
interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
parent: JSDoc;
name: EntityName;
@@ -1644,12 +1662,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
prepends: ReadonlyArray<InputFiles | UnparsedSource>;
sourceFiles: ReadonlyArray<SourceFile>;
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptText: string;
declarationText: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
text: string;
}
interface JsonSourceFile extends SourceFile {
jsonObject?: ObjectLiteralExpression;
statements: NodeArray<JsonObjectExpressionStatement>;
}
interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
kind: SyntaxKind.PrefixUnaryExpression;
operator: SyntaxKind.MinusToken;
operand: NumericLiteral;
}
interface JsonObjectExpressionStatement extends ExpressionStatement {
expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
}
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1743,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
}
interface ResolvedProjectReference {
commandLine: ParsedCommandLine;
sourceFile: SourceFile;
}
interface CustomTransformers {
/** Custom transformers to evaluate before built-in transformations. */
/** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in transformations. */
/** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in .d.ts transformations. */
afterDeclarations?: TransformerFactory<Bundle | SourceFile>[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,7 +1898,9 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
@@ -2217,6 +2264,7 @@ declare namespace ts {
objectType: Type;
indexType: Type;
constraint?: Type;
simplified?: Type;
}
type TypeVariable = TypeParameter | IndexedAccessType;
interface IndexType extends InstantiableType {
@@ -2251,7 +2299,7 @@ declare namespace ts {
Construct = 1
}
interface Signature {
declaration?: SignatureDeclaration;
declaration?: SignatureDeclaration | JSDocSignature;
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
@@ -2274,7 +2322,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
interface JsFileExtensionInfo {
/** @deprecated Use FileExtensionInfo instead. */
type JsFileExtensionInfo = FileExtensionInfo;
interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2372,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | null | undefined;
interface ProjectReference {
/** A normalized path on disk */
path: string;
/** The path as the user originally wrote it */
originalPath?: string;
/** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
/** True if it is intended that this reference form a circularity */
circular?: boolean;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2438,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2454,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
[option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2499,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
JSON = 6
JSON = 6,
/**
* Used on extensions that doesn't define the ScriptKind but the content defines it.
* Deferred extensions are going to be included in all project contexts.
*/
Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2514,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2526,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
projectReferences?: ReadonlyArray<ProjectReference>;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
@@ -2469,8 +2538,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
projectReferences: ReadonlyArray<ProjectReference> | undefined;
wildcardDirectories: MapLike<WatchDirectoryFlags>;
}
interface CreateProgramOptions {
rootNames: ReadonlyArray<string>;
options: CompilerOptions;
projectReferences?: ReadonlyArray<ProjectReference>;
host?: CompilerHost;
oldProgram?: Program;
configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>;
}
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2639,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
readDirectory?(rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -2918,10 +2997,11 @@ declare namespace ts {
readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[];
getModifiedTime?(path: string): Date;
/**
* This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
/** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -3298,6 +3378,8 @@ declare namespace ts {
function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag;
function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag;
function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral;
function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag;
function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
/**
@@ -3423,6 +3505,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3811,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray<Expression>): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
function createInputFiles(javascript: string, declaration: string): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray<Statement>): CallExpression;
@@ -3792,6 +3878,7 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
function moveSyntheticComments<T extends Node>(node: T, original: Node): T;
/**
* Gets the constant value to emit for an expression.
*/
@@ -3935,6 +4022,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): Program;
}
declare namespace ts {
@@ -4074,7 +4162,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): BuilderProgram;
}
declare namespace ts {
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>) => T;
@@ -4137,15 +4224,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Host to create watch with config file
*/
@@ -4192,6 +4270,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray<string>, readFile?: (path: string) => string | undefined): ParsedCommandLine;
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
*/
interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
getCurrentDirectory(): string;
}
/**
* Reads the config file, reports errors if any and exits if the config file cannot be found
*/
function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4311,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4323,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4331,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4350,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
getWidth(sourceFile?: SourceFile): number;
getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4462,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getProjectReferences?(): ReadonlyArray<ProjectReference> | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4378,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -4393,6 +4493,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4542,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray<number>, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray<CodeFixAction>;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise<ApplyCodeActionCommandResult>;
@@ -4465,9 +4567,10 @@ declare namespace ts {
fileName: string;
}
type OrganizeImportsScope = CombinedCodeFixScope;
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
/** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
triggerCharacter?: string;
triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4534,6 +4637,7 @@ declare namespace ts {
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
/** Description of the code action to display in the UI of the editor */
@@ -4620,6 +4724,12 @@ declare namespace ts {
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
/**
* If the span represents a location that was remapped (e.g. via a .d.ts.map file),
* then the original filename and span will be specified here
*/
originalTextSpan?: TextSpan;
originalFileName?: string;
}
interface RenameLocation extends DocumentSpan {
}
@@ -4717,9 +4827,7 @@ declare namespace ts {
insertSpaceBeforeTypeAnnotation?: boolean;
indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean;
}
interface DefinitionInfo {
fileName: string;
textSpan: TextSpan;
interface DefinitionInfo extends DocumentSpan {
kind: ScriptElementKind;
name: string;
containerKind: ScriptElementKind;
@@ -4865,6 +4973,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
/**
* Classification of the contents of the span
*/
kind: OutliningSpanKind;
}
enum OutliningSpanKind {
/** Single or multi-line comments */
Comment = "comment",
/** Sections marked by '// #region' and '// #endregion' comments */
Region = "region",
/** Declarations and expressions */
Code = "code",
/** Contiguous blocks of import declarations */
Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5110,9 @@ declare namespace ts {
/**
* <JsxTagName attribute1 attribute2={0} />
*/
jsxAttribute = "JSX attribute"
jsxAttribute = "JSX attribute",
/** String literal */
string = "string"
}
enum ScriptElementKindModifier {
none = "",
+5354 -2688
View File
File diff suppressed because it is too large Load Diff
+186 -62
View File
@@ -337,32 +337,36 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
JSDocTypeExpression = 275,
JSDocAllType = 276,
JSDocUnknownType = 277,
JSDocNullableType = 278,
JSDocNonNullableType = 279,
JSDocOptionalType = 280,
JSDocFunctionType = 281,
JSDocVariadicType = 282,
JSDocComment = 283,
JSDocTypeLiteral = 284,
JSDocTag = 285,
JSDocAugmentsTag = 286,
JSDocClassTag = 287,
JSDocParameterTag = 288,
JSDocReturnTag = 289,
JSDocTypeTag = 290,
JSDocTemplateTag = 291,
JSDocTypedefTag = 292,
JSDocPropertyTag = 293,
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
UnparsedSource = 275,
InputFiles = 276,
JSDocTypeExpression = 277,
JSDocAllType = 278,
JSDocUnknownType = 279,
JSDocNullableType = 280,
JSDocNonNullableType = 281,
JSDocOptionalType = 282,
JSDocFunctionType = 283,
JSDocVariadicType = 284,
JSDocComment = 285,
JSDocTypeLiteral = 286,
JSDocSignature = 287,
JSDocTag = 288,
JSDocAugmentsTag = 289,
JSDocClassTag = 290,
JSDocCallbackTag = 291,
JSDocParameterTag = 292,
JSDocReturnTag = 293,
JSDocTypeTag = 294,
JSDocTemplateTag = 295,
JSDocTypedefTag = 296,
JSDocPropertyTag = 297,
SyntaxList = 298,
NotEmittedStatement = 299,
PartiallyEmittedExpression = 300,
CommaListExpression = 301,
MergeDeclarationMarker = 302,
EndOfDeclarationMarker = 303,
Count = 304,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +392,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
FirstJSDocNode = 275,
LastJSDocNode = 293,
FirstJSDocTagNode = 285,
LastJSDocTagNode = 293
FirstJSDocNode = 277,
LastJSDocNode = 297,
FirstJSDocTagNode = 288,
LastJSDocTagNode = 297
}
enum NodeFlags {
None = 0,
@@ -415,6 +419,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1154,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
* A list of comma-seperated expressions. This node is only created by transformations.
* A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1277,7 +1282,7 @@ declare namespace ts {
block: Block;
}
type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag;
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature;
interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
name?: Identifier;
@@ -1534,6 +1539,19 @@ declare namespace ts {
name?: Identifier;
typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
parent: JSDoc;
kind: SyntaxKind.JSDocCallbackTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression: JSDocSignature;
}
interface JSDocSignature extends JSDocType, Declaration {
kind: SyntaxKind.JSDocSignature;
typeParameters?: ReadonlyArray<JSDocTemplateTag>;
parameters: ReadonlyArray<JSDocParameterTag>;
type: JSDocReturnTag | undefined;
}
interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
parent: JSDoc;
name: EntityName;
@@ -1644,12 +1662,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
prepends: ReadonlyArray<InputFiles | UnparsedSource>;
sourceFiles: ReadonlyArray<SourceFile>;
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptText: string;
declarationText: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
text: string;
}
interface JsonSourceFile extends SourceFile {
jsonObject?: ObjectLiteralExpression;
statements: NodeArray<JsonObjectExpressionStatement>;
}
interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
kind: SyntaxKind.PrefixUnaryExpression;
operator: SyntaxKind.MinusToken;
operand: NumericLiteral;
}
interface JsonObjectExpressionStatement extends ExpressionStatement {
expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
}
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1743,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
}
interface ResolvedProjectReference {
commandLine: ParsedCommandLine;
sourceFile: SourceFile;
}
interface CustomTransformers {
/** Custom transformers to evaluate before built-in transformations. */
/** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in transformations. */
/** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory<SourceFile>[];
/** Custom transformers to evaluate after built-in .d.ts transformations. */
afterDeclarations?: TransformerFactory<Bundle | SourceFile>[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,7 +1898,9 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
@@ -2217,6 +2264,7 @@ declare namespace ts {
objectType: Type;
indexType: Type;
constraint?: Type;
simplified?: Type;
}
type TypeVariable = TypeParameter | IndexedAccessType;
interface IndexType extends InstantiableType {
@@ -2251,7 +2299,7 @@ declare namespace ts {
Construct = 1
}
interface Signature {
declaration?: SignatureDeclaration;
declaration?: SignatureDeclaration | JSDocSignature;
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
@@ -2274,7 +2322,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
interface JsFileExtensionInfo {
/** @deprecated Use FileExtensionInfo instead. */
type JsFileExtensionInfo = FileExtensionInfo;
interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2372,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | null | undefined;
interface ProjectReference {
/** A normalized path on disk */
path: string;
/** The path as the user originally wrote it */
originalPath?: string;
/** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
/** True if it is intended that this reference form a circularity */
circular?: boolean;
}
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2438,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2454,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
[option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2499,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
JSON = 6
JSON = 6,
/**
* Used on extensions that doesn't define the ScriptKind but the content defines it.
* Deferred extensions are going to be included in all project contexts.
*/
Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2514,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2526,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
projectReferences?: ReadonlyArray<ProjectReference>;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
@@ -2469,8 +2538,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
projectReferences: ReadonlyArray<ProjectReference> | undefined;
wildcardDirectories: MapLike<WatchDirectoryFlags>;
}
interface CreateProgramOptions {
rootNames: ReadonlyArray<string>;
options: CompilerOptions;
projectReferences?: ReadonlyArray<ProjectReference>;
host?: CompilerHost;
oldProgram?: Program;
configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>;
}
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2639,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
readDirectory?(rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -2918,10 +2997,11 @@ declare namespace ts {
readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[];
getModifiedTime?(path: string): Date;
/**
* This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
/** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -3298,6 +3378,8 @@ declare namespace ts {
function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag;
function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag;
function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral;
function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag;
function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
/**
@@ -3423,6 +3505,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3811,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray<Expression>): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>): Bundle;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
function createInputFiles(javascript: string, declaration: string): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray<Statement>): CallExpression;
@@ -3792,6 +3878,7 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
function moveSyntheticComments<T extends Node>(node: T, original: Node): T;
/**
* Gets the constant value to emit for an expression.
*/
@@ -3935,6 +4022,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): Program;
}
declare namespace ts {
@@ -4074,7 +4162,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): BuilderProgram;
}
declare namespace ts {
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>) => T;
@@ -4137,15 +4224,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Host to create watch with config file
*/
@@ -4192,6 +4270,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray<string>, readFile?: (path: string) => string | undefined): ParsedCommandLine;
type DiagnosticReporter = (diagnostic: Diagnostic) => void;
/**
* Reports config file diagnostics
*/
interface ConfigFileDiagnosticsReporter {
/**
* Reports unrecoverable error when parsing config file
*/
onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
}
/**
* Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
*/
interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
getCurrentDirectory(): string;
}
/**
* Reads the config file, reports errors if any and exits if the config file cannot be found
*/
function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4311,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4323,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4331,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<JsFileExtensionInfo>): ParsedCommandLine;
function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4350,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
getWidth(sourceFile?: SourceFile): number;
getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4462,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getProjectReferences?(): ReadonlyArray<ProjectReference> | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4378,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -4393,6 +4493,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4542,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray<number>, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray<CodeFixAction>;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise<ApplyCodeActionCommandResult>;
@@ -4465,9 +4567,10 @@ declare namespace ts {
fileName: string;
}
type OrganizeImportsScope = CombinedCodeFixScope;
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
/** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
triggerCharacter?: string;
triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4534,6 +4637,7 @@ declare namespace ts {
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
/** Description of the code action to display in the UI of the editor */
@@ -4620,6 +4724,12 @@ declare namespace ts {
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
/**
* If the span represents a location that was remapped (e.g. via a .d.ts.map file),
* then the original filename and span will be specified here
*/
originalTextSpan?: TextSpan;
originalFileName?: string;
}
interface RenameLocation extends DocumentSpan {
}
@@ -4717,9 +4827,7 @@ declare namespace ts {
insertSpaceBeforeTypeAnnotation?: boolean;
indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean;
}
interface DefinitionInfo {
fileName: string;
textSpan: TextSpan;
interface DefinitionInfo extends DocumentSpan {
kind: ScriptElementKind;
name: string;
containerKind: ScriptElementKind;
@@ -4865,6 +4973,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
/**
* Classification of the contents of the span
*/
kind: OutliningSpanKind;
}
enum OutliningSpanKind {
/** Single or multi-line comments */
Comment = "comment",
/** Sections marked by '// #region' and '// #endregion' comments */
Region = "region",
/** Declarations and expressions */
Code = "code",
/** Contiguous blocks of import declarations */
Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5110,9 @@ declare namespace ts {
/**
* <JsxTagName attribute1 attribute2={0} />
*/
jsxAttribute = "JSX attribute"
jsxAttribute = "JSX attribute",
/** String literal */
string = "string"
}
enum ScriptElementKindModifier {
none = "",
+5354 -2688
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
-5171
View File
File diff suppressed because it is too large Load Diff
+1033 -1813
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+27
View File
@@ -0,0 +1,27 @@
/*! *****************************************************************************
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.
***************************************************************************** */
"use strict";
if (process.argv.length < 3) {
process.exit(1);
}
var directoryName = process.argv[2];
var fs = require("fs");
try {
var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); });
watcher.close();
}
catch (_a) { }
process.exit(0);
+21 -1
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。",
"All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。",
"All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。",
"Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。",
"Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。",
"Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。",
"Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。",
"Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。",
"Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类",
"Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"",
"Convert_all_to_default_imports_95035": "全部转换为默认导入",
"Convert_function_0_to_class_95002": "将函数“{0}”转换为类",
"Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类",
"Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"",
"Convert_to_ES6_module_95017": "转换为 ES6 模块",
"Convert_to_default_import_95013": "转换为默认导入",
"Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "标签“{0}”重复。",
"Duplicate_number_index_signature_2375": "数字索引签名重复。",
"Duplicate_string_index_signature_2374": "字符串索引签名重复。",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "面向 ECMAScript 2015 模块时,不能使用动态导入。",
"Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "仅当 \"--module\" 标志为 \"commonjs\" 或 \"esNext\" 时,才支持动态导入。",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。",
"Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。",
"Enable_project_compilation_6302": "启用项目编译",
"Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。",
"Enable_strict_null_checks_6113": "启用严格的 NULL 检查。",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。",
"File_0_is_not_a_module_2306": "文件“{0}”不是模块。",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "文件“{0}”不在项目文件列表中。项目必须列出的所有文件,或使用“包含”模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。",
"File_0_not_found_6053": "找不到文件“{0}”。",
"File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。",
"Include_modules_imported_with_json_extension_6197": "包括通过 \".json\" 扩展导入的模块",
"Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。",
"Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。",
"Index_signatures_are_incompatible_2330": "索引签名不兼容。",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========",
"Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。",
"Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。",
"Move_to_a_new_file_95049": "移动到新的文件",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允许使用多个连续的数字分隔符。",
"Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。",
"NEWLINE_6061": "换行符",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。",
"Options_Colon_6027": "选项:",
"Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。",
"Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。",
"Print_the_compiler_s_version_6019": "打印编译器的版本。",
"Print_this_message_6017": "打印此消息。",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}",
"Projects_to_reference_6300": "要引用的项目",
"Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "类型“{1}”上不存在属性“{0}”。是否忘记使用 \"await\"?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。",
"Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。",
"Remove_all_unreachable_code_95051": "删除所有无法访问的代码",
"Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明",
"Remove_destructuring_90009": "删除解构",
"Remove_import_from_0_90005": "从“{0}”删除导入",
"Remove_unreachable_code_95050": "删除无法访问的代码",
"Replace_import_with_0_95015": "用“{0}”替换导入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "\"import.meta\" 元属性仅允许对 \"target\" 和 \"module\" 编译器选项使用 \"ESNext\"。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。",
"require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。",
+21 -5
View File
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。",
"All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。",
"All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。",
"Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。",
"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。",
"Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。",
"Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。",
"Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。",
"Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。",
@@ -271,11 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。",
"Convert_all_constructor_functions_to_classes_95045": "將所有建構函式轉換為類別",
"Convert_all_require_to_import_95048": "Convert all 'require' to 'import'",
"Convert_all_require_to_import_95048": "將所有 'require' 轉換至 'import'",
"Convert_all_to_default_imports_95035": "全部轉換為預設匯入",
"Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別",
"Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別",
"Convert_require_to_import_95047": "Convert 'require' to 'import'",
"Convert_require_to_import_95047": " 'require' 轉換至 'import'",
"Convert_to_ES6_module_95017": "轉換為 ES6 模組",
"Convert_to_default_import_95013": "轉換為預設匯入",
"Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。",
@@ -328,8 +331,8 @@
"Duplicate_label_0_1114": "標籤 '{0}' 重複。",
"Duplicate_number_index_signature_2375": "數字索引簽章重複。",
"Duplicate_string_index_signature_2374": "字串索引簽章重複。",
"Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "以 ECMAScript 2015 模組為目標時,無法使用動態匯入。",
"Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數",
"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "只有當 '--module' 旗標是 'commonjs' 或 'esNext' 時,才支援動態匯入。",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。",
@@ -338,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。",
"Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。",
"Enable_project_compilation_6302": "啟用專案編譯",
"Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。",
"Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。",
@@ -399,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。",
"File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。",
"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "檔案 '{0}' 不在專案檔案清單內。專案必須列出所有檔案,或使用 'include' 模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。",
"File_0_not_found_6053": "找不到檔案 '{0}'。",
"File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...",
@@ -463,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。",
"Include_modules_imported_with_json_extension_6197": "包含匯入有 '.json' 延伸模組的模組",
"Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。",
"Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。",
"Index_signatures_are_incompatible_2330": "索引簽章不相容。",
@@ -561,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========",
"Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。",
"Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。",
"Move_to_a_new_file_95049": "移至新行",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。",
"Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。",
"NEWLINE_6061": "新行",
@@ -602,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。",
"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "指定選項 '-resolveJsonModule' 時,不可沒有 'node' 模組解析策略。",
"Options_Colon_6027": "選項:",
"Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。",
"Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'",
"Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。",
@@ -647,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。",
"Print_the_compiler_s_version_6019": "列印編譯器的版本。",
"Print_this_message_6017": "列印這則訊息。",
"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}",
"Projects_to_reference_6300": "專案至參考",
"Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "類型 '{1}' 不存在屬性 '{0}'。是否忘記要使用 'await'?",
@@ -694,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。",
"Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。",
"Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼",
"Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告",
"Remove_destructuring_90009": "移除解構",
"Remove_import_from_0_90005": "從 '{0}' 移除匯入",
"Remove_unreachable_code_95050": "移除無法連線的程式碼",
"Replace_import_with_0_95015": "以 '{0}' 取代匯入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。",
@@ -803,7 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "只有在為 'target' 及 'module' 編譯器選項使用 'ESNext' 時,才允許 'import.meta' 中繼屬性。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。",
@@ -1016,7 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。",
"require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.",
"require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "2.9.0",
"version": "3.0.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
+4 -4
View File
@@ -8,7 +8,7 @@ function endsWith(s: string, suffix: string) {
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.length && declaration.members.every(m => m.initializer && m.initializer.kind === ts.SyntaxKind.StringLiteral);
return declaration.members.length && declaration.members.every(m => !!m.initializer && m.initializer.kind === ts.SyntaxKind.StringLiteral);
}
class DeclarationsWalker {
@@ -30,7 +30,7 @@ class DeclarationsWalker {
text += "\ndeclare namespace ts {\n";
text += " // these types are empty stubs for types from services and should not be used directly\n"
for (const type of walker.removedTypes) {
text += ` export type ${type.symbol.name} = never;\n`;
text += ` export type ${type.symbol!.name} = never;\n`;
}
text += "}"
}
@@ -130,7 +130,7 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
function getInitialDtsFileForProtocol() {
const program = ts.createProgram([protocolTs, typeScriptServicesDts], options);
let protocolDts: string;
let protocolDts: string | undefined;
program.emit(program.getSourceFile(protocolTs), (file, content) => {
if (endsWith(file, ".d.ts")) {
protocolDts = content;
@@ -162,7 +162,7 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
let protocolDts = getInitialDtsFileForProtocol();
const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true);
const protocolFile = program.getSourceFile("protocol.d.ts");
const protocolFile = program.getSourceFile("protocol.d.ts")!;
const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile);
if (extraDeclarations) {
protocolDts += extraDeclarations;
+2 -1
View File
@@ -27,7 +27,7 @@ runSequence([
["git", ["add", "."]], // Add all changes
["git", ["commit", "-m", `"Update user baselines"`]], // Commit all changes
["git", ["remote", "add", "fork", remoteUrl]], // Add the remote fork
["git", ["push", "--set-upstream", "fork", branchName]] // push the branch
["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch
]);
const gh = new Octokit();
@@ -44,6 +44,7 @@ gh.pullRequests.create({
base: "master",
body:
`Please review the diff and merge if no changes are unexpected.
You can view the build log [here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary).
cc ${reviewers.map(r => "@" + r).join(" ")}`,
}).then(r => {
+1 -1
View File
@@ -22,7 +22,7 @@ function main(): void {
}
const inputFilePath = sys.args[0].replace(/\\/g, "/");
const inputStr = sys.readFile(inputFilePath);
const inputStr = sys.readFile(inputFilePath)!;
const diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr);
+1 -1
View File
@@ -12,7 +12,7 @@ export class Rule extends Lint.Rules.AbstractRule {
function walk(ctx: Lint.WalkContext<void>): void {
ts.forEachChild(ctx.sourceFile, recur);
function recur(node: ts.Node): void {
if (node.kind === ts.SyntaxKind.InKeyword && node.parent.kind === ts.SyntaxKind.BinaryExpression) {
if (node.kind === ts.SyntaxKind.InKeyword && node.parent!.kind === ts.SyntaxKind.BinaryExpression) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}
}
@@ -1,98 +0,0 @@
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as ts from "typescript";
import * as Lint from "tslint";
export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-unnecessary-type-assertion",
description: "Warns if a type assertion does not change the type of an expression.",
options: {
type: "list",
listType: {
type: "array",
items: { type: "string" },
},
},
optionsDescription: "A list of whitelisted assertion types to ignore",
type: "typescript",
hasFix: true,
typescriptOnly: true,
requiresTypeInfo: true,
};
/* tslint:enable:object-literal-sort-keys */
public static FAILURE_STRING = "This assertion is unnecessary since it does not change the type of the expression.";
public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.ruleName, this.ruleArguments, program.getTypeChecker()));
}
}
class Walker extends Lint.AbstractWalker<string[]> {
constructor(sourceFile: ts.SourceFile, ruleName: string, options: string[], private readonly checker: ts.TypeChecker) {
super(sourceFile, ruleName, options);
}
public walk(sourceFile: ts.SourceFile) {
const cb = (node: ts.Node): void => {
switch (node.kind) {
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.AsExpression:
this.verifyCast(node as ts.TypeAssertion | ts.AsExpression);
}
return ts.forEachChild(node, cb);
};
return ts.forEachChild(sourceFile, cb);
}
private verifyCast(node: ts.TypeAssertion | ts.NonNullExpression | ts.AsExpression) {
if (ts.isAssertionExpression(node) && this.options.indexOf(node.type.getText(this.sourceFile)) !== -1) {
return;
}
const castType = this.checker.getTypeAtLocation(node);
if (castType === undefined) {
return;
}
if (node.kind !== ts.SyntaxKind.NonNullExpression &&
(castType.flags & ts.TypeFlags.Literal ||
castType.flags & ts.TypeFlags.Object &&
(castType as ts.ObjectType).objectFlags & ts.ObjectFlags.Tuple) ||
// Sometimes tuple types don't have ObjectFlags.Tuple set, like when
// they're being matched against an inferred type. So, in addition,
// check if any properties are numbers, which implies that this is
// likely a tuple type.
(castType.getProperties().some((symbol) => !isNaN(Number(symbol.name))))) {
// It's not always safe to remove a cast to a literal type or tuple
// type, as those types are sometimes widened without the cast.
return;
}
const uncastType = this.checker.getTypeAtLocation(node.expression);
if (uncastType === castType) {
this.addFailureAtNode(node, Rule.FAILURE_STRING, node.kind === ts.SyntaxKind.TypeAssertionExpression
? Lint.Replacement.deleteFromTo(node.getStart(), node.expression.getStart())
: Lint.Replacement.deleteFromTo(node.expression.getEnd(), node.getEnd()));
}
}
}
+183 -183
View File
@@ -118,18 +118,18 @@ namespace ts {
let thisParentContainer: Node; // Container one level up
let blockScopeContainer: Node;
let lastContainer: Node;
let delayedTypedefs: { typedef: JSDocTypedefTag, container: Node, lastContainer: Node, blockScopeContainer: Node, parent: Node }[];
let delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag)[];
let seenThisKeyword: boolean;
// state used by control flow analysis
let currentFlow: FlowNode;
let currentBreakTarget: FlowLabel;
let currentContinueTarget: FlowLabel;
let currentReturnTarget: FlowLabel;
let currentTrueTarget: FlowLabel;
let currentFalseTarget: FlowLabel;
let preSwitchCaseFlow: FlowNode;
let activeLabels: ActiveLabel[];
let currentBreakTarget: FlowLabel | undefined;
let currentContinueTarget: FlowLabel | undefined;
let currentReturnTarget: FlowLabel | undefined;
let currentTrueTarget: FlowLabel | undefined;
let currentFalseTarget: FlowLabel | undefined;
let preSwitchCaseFlow: FlowNode | undefined;
let activeLabels: ActiveLabel[] | undefined;
let hasExplicitReturn: boolean;
// state used for emit helpers
@@ -158,7 +158,7 @@ namespace ts {
* If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
* This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
*/
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): DiagnosticWithLocation {
return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
}
@@ -180,23 +180,23 @@ namespace ts {
delayedBindJSDocTypedefTag();
}
file = undefined;
options = undefined;
languageVersion = undefined;
parent = undefined;
container = undefined;
thisParentContainer = undefined;
blockScopeContainer = undefined;
lastContainer = undefined;
delayedTypedefs = undefined;
file = undefined!;
options = undefined!;
languageVersion = undefined!;
parent = undefined!;
container = undefined!;
thisParentContainer = undefined!;
blockScopeContainer = undefined!;
lastContainer = undefined!;
delayedTypeAliases = undefined!;
seenThisKeyword = false;
currentFlow = undefined;
currentFlow = undefined!;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
currentReturnTarget = undefined;
currentTrueTarget = undefined;
currentFalseTarget = undefined;
activeLabels = undefined;
activeLabels = undefined!;
hasExplicitReturn = false;
emitFlags = NodeFlags.None;
subtreeTransformFlags = TransformFlags.None;
@@ -234,7 +234,7 @@ namespace ts {
}
if (symbolFlags & SymbolFlags.Value) {
const valueDeclaration = symbol.valueDeclaration;
const { valueDeclaration } = symbol;
if (!valueDeclaration ||
(valueDeclaration.kind !== node.kind && valueDeclaration.kind === SyntaxKind.ModuleDeclaration)) {
// other kinds of value declarations take precedence over modules
@@ -245,7 +245,7 @@ namespace ts {
// Should not be called on a declaration with a computed property name,
// unless it is a well known Symbol.
function getDeclarationName(node: Declaration): __String {
function getDeclarationName(node: Declaration): __String | undefined {
if (node.kind === SyntaxKind.ExportAssignment) {
return (<ExportAssignment>node).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default;
}
@@ -273,6 +273,7 @@ namespace ts {
return InternalSymbolName.Constructor;
case SyntaxKind.FunctionType:
case SyntaxKind.CallSignature:
case SyntaxKind.JSDocSignature:
return InternalSymbolName.Call;
case SyntaxKind.ConstructorType:
case SyntaxKind.ConstructSignature:
@@ -301,14 +302,11 @@ namespace ts {
const functionType = <JSDocFunctionType>node.parent;
const index = functionType.parameters.indexOf(node as ParameterDeclaration);
return "arg" + index as __String;
case SyntaxKind.JSDocTypedefTag:
const name = getNameOfJSDocTypedef(node as JSDocTypedefTag);
return typeof name !== "undefined" ? name.escapedText : undefined;
}
}
function getDisplayName(node: Declaration): string {
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(getDeclarationName(node));
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(getDeclarationName(node)!); // TODO: GH#18217
}
/**
@@ -319,7 +317,7 @@ namespace ts {
* @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
* @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
*/
function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags, isReplaceableByMethod?: boolean): Symbol {
function declareSymbol(symbolTable: SymbolTable, parent: Symbol | undefined, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags, isReplaceableByMethod?: boolean): Symbol {
Debug.assert(!hasDynamicName(node));
const isDefaultExport = hasModifier(node, ModifierFlags.Default);
@@ -327,7 +325,7 @@ namespace ts {
// The exported symbol for an export default function/class node is always named "default"
const name = isDefaultExport && parent ? InternalSymbolName.Default : getDeclarationName(node);
let symbol: Symbol;
let symbol: Symbol | undefined;
if (name === undefined) {
symbol = createSymbol(SymbolFlags.None, InternalSymbolName.Missing);
}
@@ -434,10 +432,10 @@ namespace ts {
const hasExportModifier = getCombinedModifierFlags(node) & ModifierFlags.Export;
if (symbolFlags & SymbolFlags.Alias) {
if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes);
}
else {
return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
else {
@@ -456,19 +454,19 @@ namespace ts {
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefTag(node)) {
if (isJSDocTypeAlias(node)) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypeAlias(node)) {
if (hasModifier(node, ModifierFlags.Default) && !getDeclarationName(node)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
const exportKind = symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0;
const local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
const local = declareSymbol(container.locals!, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes);
node.localSymbol = local;
return local;
}
else {
return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
}
@@ -549,6 +547,7 @@ namespace ts {
if (node.kind === SyntaxKind.SourceFile) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
addAntecedent(currentReturnTarget, currentFlow);
currentFlow = finishFlowLabel(currentReturnTarget);
@@ -597,12 +596,12 @@ namespace ts {
}
}
function bindEachFunctionsFirst(nodes: NodeArray<Node>) {
function bindEachFunctionsFirst(nodes: NodeArray<Node> | undefined): void {
bindEach(nodes, n => n.kind === SyntaxKind.FunctionDeclaration ? bind(n) : undefined);
bindEach(nodes, n => n.kind !== SyntaxKind.FunctionDeclaration ? bind(n) : undefined);
}
function bindEach(nodes: NodeArray<Node>, bindFunction = bind) {
function bindEach(nodes: NodeArray<Node> | undefined, bindFunction: (node: Node) => void = bind): void {
if (nodes === undefined) {
return;
}
@@ -628,22 +627,6 @@ namespace ts {
}
function bindChildrenWorker(node: Node): void {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
// container or not.
if (hasJSDocNodes(node)) {
if (isInJavaScriptFile(node)) {
for (const j of node.jsDoc) {
bind(j);
}
}
else {
for (const j of node.jsDoc) {
setParentPointers(node, j);
}
}
}
if (checkUnreachable(node)) {
bindEachChild(node);
return;
@@ -709,11 +692,9 @@ namespace ts {
case SyntaxKind.CallExpression:
bindCallExpressionFlow(<CallExpression>node);
break;
case SyntaxKind.JSDocComment:
bindJSDocComment(<JSDoc>node);
break;
case SyntaxKind.JSDocTypedefTag:
bindJSDocTypedefTag(<JSDocTypedefTag>node);
case SyntaxKind.JSDocCallbackTag:
bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
case SyntaxKind.SourceFile:
@@ -728,6 +709,7 @@ namespace ts {
bindEachChild(node);
break;
}
bindJSDoc(node);
}
function isNarrowingExpression(expr: Expression): boolean {
@@ -839,7 +821,7 @@ namespace ts {
}
}
function createFlowCondition(flags: FlowFlags, antecedent: FlowNode, expression: Expression): FlowNode {
function createFlowCondition(flags: FlowFlags, antecedent: FlowNode, expression: Expression | undefined): FlowNode {
if (antecedent.flags & FlowFlags.Unreachable) {
return antecedent;
}
@@ -926,7 +908,7 @@ namespace ts {
return !isStatementCondition(node) && !isLogicalExpression(node.parent);
}
function bindCondition(node: Expression, trueTarget: FlowLabel, falseTarget: FlowLabel) {
function bindCondition(node: Expression | undefined, trueTarget: FlowLabel, falseTarget: FlowLabel) {
const saveTrueTarget = currentTrueTarget;
const saveFalseTarget = currentFalseTarget;
currentTrueTarget = trueTarget;
@@ -966,7 +948,7 @@ namespace ts {
function bindDoStatement(node: DoStatement): void {
const preDoLabel = createLoopLabel();
const enclosingLabeledStatement = node.parent.kind === SyntaxKind.LabeledStatement
? lastOrUndefined(activeLabels)
? lastOrUndefined(activeLabels!)
: undefined;
// if do statement is wrapped in labeled statement then target labels for break/continue with or without
// label should be the same
@@ -1051,7 +1033,7 @@ namespace ts {
return undefined;
}
function bindBreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) {
function bindBreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel | undefined, continueTarget: FlowLabel | undefined) {
const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget;
if (flowLabel) {
addAntecedent(flowLabel, currentFlow);
@@ -1181,7 +1163,8 @@ namespace ts {
i++;
}
const preCaseLabel = createBranchLabel();
addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1));
addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1));
addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow!, node.parent, clauseStart, i + 1));
addAntecedent(preCaseLabel, fallthroughFlow);
currentFlow = finishFlowLabel(preCaseLabel);
const clause = clauses[i];
@@ -1197,7 +1180,7 @@ namespace ts {
function bindCaseClause(node: CaseClause): void {
const saveCurrentFlow = currentFlow;
currentFlow = preSwitchCaseFlow;
currentFlow = preSwitchCaseFlow!;
bind(node.expression);
currentFlow = saveCurrentFlow;
bindEach(node.statements);
@@ -1215,7 +1198,7 @@ namespace ts {
}
function popActiveLabel() {
activeLabels.pop();
activeLabels!.pop();
}
function bindLabeledStatement(node: LabeledStatement): void {
@@ -1227,7 +1210,7 @@ namespace ts {
bind(node.statement);
popActiveLabel();
if (!activeLabel.referenced && !options.allowUnusedLabels) {
file.bindDiagnostics.push(createDiagnosticForNode(node.label, Diagnostics.Unused_label));
errorOrSuggestionOnFirstToken(unusedLabelIsError(options), node, Diagnostics.Unused_label);
}
if (!node.statement || node.statement.kind !== SyntaxKind.DoStatement) {
// do statement sets current flow inside bindDoStatement
@@ -1320,7 +1303,7 @@ namespace ts {
currentFlow = finishFlowLabel(postExpressionLabel);
}
else {
bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
bindLogicalExpression(node, currentTrueTarget!, currentFalseTarget!);
}
}
else {
@@ -1379,24 +1362,10 @@ namespace ts {
}
}
function bindJSDocComment(node: JSDoc) {
forEachChild(node, n => {
if (n.kind !== SyntaxKind.JSDocTypedefTag) {
bind(n);
}
});
}
function bindJSDocTypedefTag(node: JSDocTypedefTag) {
forEachChild(node, n => {
// if the node has a fullName "A.B.C", that means symbol "C" was already bound
// when we visit "fullName"; so when we visit the name "C" as the next child of
// the jsDocTypedefTag, we should skip binding it.
if (node.fullName && n === node.name && node.fullName.kind !== SyntaxKind.Identifier) {
return;
}
bind(n);
});
function bindJSDocTypeAlias(node: JSDocTypedefTag | JSDocCallbackTag) {
if (node.fullName) {
setParentPointers(node, node.fullName);
}
}
function bindCallExpressionFlow(node: CallExpression) {
@@ -1456,6 +1425,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.CallSignature:
case SyntaxKind.JSDocSignature:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructSignature:
@@ -1510,7 +1480,7 @@ namespace ts {
lastContainer = next;
}
function declareSymbolAndAddToSymbolTable(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol {
function declareSymbolAndAddToSymbolTable(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol | undefined {
switch (container.kind) {
// Modules, source files, and classes need specialized handling for how their
// members are declared (for example, a member of a class will go into a specific
@@ -1527,7 +1497,7 @@ namespace ts {
return declareClassMember(node, symbolFlags, symbolExcludes);
case SyntaxKind.EnumDeclaration:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes);
case SyntaxKind.TypeLiteral:
case SyntaxKind.JSDocTypeLiteral:
@@ -1539,12 +1509,13 @@ namespace ts {
// container, and are never in scope otherwise (even inside the body of the
// object / type / interface declaring them). An exception is type parameters,
// which are in scope without qualification (similar to 'locals').
return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
return declareSymbol(container.symbol.members!, container.symbol, node, symbolFlags, symbolExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.JSDocSignature:
case SyntaxKind.IndexSignature:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
@@ -1555,6 +1526,8 @@ namespace ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocTypedefTag:
case SyntaxKind.JSDocCallbackTag:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.MappedType:
// All the children of these container types are never visible through another
@@ -1563,20 +1536,20 @@ namespace ts {
// their container in the tree). To accomplish this, we simply add their declared
// symbol to the 'locals' of the container. These symbols can then be found as
// the type checker walks up the containers, checking them for matching names.
return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
return hasModifier(node, ModifierFlags.Static)
? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
: declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
? declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes)
: declareSymbol(container.symbol.members!, container.symbol, node, symbolFlags, symbolExcludes);
}
function declareSourceFileMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
return isExternalModule(file)
? declareModuleMember(node, symbolFlags, symbolExcludes)
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
: declareSymbol(file.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
@@ -1623,8 +1596,8 @@ namespace ts {
}
}
const symbol = declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
file.patternAmbientModules = append(file.patternAmbientModules, pattern && { pattern, symbol });
const symbol = declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes)!;
file.patternAmbientModules = append<PatternAmbientModule>(file.patternAmbientModules, pattern && { pattern, symbol });
}
}
else {
@@ -1650,14 +1623,14 @@ namespace ts {
return state;
}
function bindFunctionOrConstructorType(node: SignatureDeclaration): void {
function bindFunctionOrConstructorType(node: SignatureDeclaration | JSDocSignature): void {
// For a given function symbol "<...>(...) => T" we want to generate a symbol identical
// to the one we would get for: { <...>(...): T }
//
// We do that by making an anonymous type literal symbol, and then setting the function
// symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
// from an actual type literal symbol you would have gotten had you used the long form.
const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node));
const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)!); // TODO: GH#18217
addDeclarationToSymbol(symbol, node, SymbolFlags.Signature);
const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
@@ -1752,29 +1725,42 @@ namespace ts {
}
function delayedBindJSDocTypedefTag() {
if (!delayedTypedefs) {
if (!delayedTypeAliases) {
return;
}
const saveContainer = container;
const saveLastContainer = lastContainer;
const saveBlockScopeContainer = blockScopeContainer;
const saveParent = parent;
for (const delay of delayedTypedefs) {
({ container, lastContainer, blockScopeContainer, parent } = delay);
bindBlockScopedDeclaration(delay.typedef, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
const saveCurrentFlow = currentFlow;
for (const typeAlias of delayedTypeAliases) {
const host = getJSDocHost(typeAlias);
container = findAncestor(host.parent, n => !!(getContainerFlags(n) & ContainerFlags.IsContainer)) || file;
blockScopeContainer = getEnclosingBlockScopeContainer(host) || file;
currentFlow = { flags: FlowFlags.Start };
parent = typeAlias;
bind(typeAlias.typeExpression);
if (!typeAlias.fullName || typeAlias.fullName.kind === SyntaxKind.Identifier) {
parent = typeAlias.parent;
bindBlockScopedDeclaration(typeAlias, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
else {
bind(typeAlias.fullName);
}
}
container = saveContainer;
lastContainer = saveLastContainer;
blockScopeContainer = saveBlockScopeContainer;
parent = saveParent;
currentFlow = saveCurrentFlow;
}
// The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
// check for reserved words used as identifiers in strict mode code.
function checkStrictModeIdentifier(node: Identifier) {
if (inStrictMode &&
node.originalKeywordKind >= SyntaxKind.FirstFutureReservedWord &&
node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord &&
node.originalKeywordKind! >= SyntaxKind.FirstFutureReservedWord &&
node.originalKeywordKind! <= SyntaxKind.LastFutureReservedWord &&
!isIdentifierName(node) &&
!(node.flags & NodeFlags.Ambient)) {
@@ -1830,7 +1816,7 @@ namespace ts {
return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
}
function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) {
function checkStrictModeEvalOrArguments(contextNode: Node, name: Node | undefined) {
if (name && name.kind === SyntaxKind.Identifier) {
const identifier = <Identifier>name;
if (isEvalOrArgumentsIdentifier(identifier)) {
@@ -1930,7 +1916,18 @@ namespace ts {
file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
}
function bind(node: Node): void {
function errorOrSuggestionOnFirstToken(isError: boolean, node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) {
const span = getSpanOfTokenAtPosition(file, node.pos);
const diag = createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2);
if (isError) {
file.bindDiagnostics.push(diag);
}
else {
file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag, category: DiagnosticCategory.Suggestion });
}
}
function bind(node: Node | undefined): void {
if (!node) {
return;
}
@@ -1946,7 +1943,6 @@ namespace ts {
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
if (isInJavaScriptFile(node)) bindJSDocTypedefTagIfAny(node);
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
@@ -1978,26 +1974,21 @@ namespace ts {
}
else if (!skipTransformFlagAggregation && (node.transformFlags & TransformFlags.HasComputedFlags) === 0) {
subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
bindJSDoc(node);
}
inStrictMode = saveInStrictMode;
}
function bindJSDocTypedefTagIfAny(node: Node) {
if (!hasJSDocNodes(node)) {
return;
}
for (const jsDoc of node.jsDoc) {
if (!jsDoc.tags) {
continue;
function bindJSDoc(node: Node) {
if (hasJSDocNodes(node)) {
if (isInJavaScriptFile(node)) {
for (const j of node.jsDoc!) {
bind(j);
}
}
for (const tag of jsDoc.tags) {
if (tag.kind === SyntaxKind.JSDocTypedefTag) {
const savedParent = parent;
parent = jsDoc;
bind(tag);
parent = savedParent;
else {
for (const j of node.jsDoc!) {
setParentPointers(node, j);
}
}
}
@@ -2036,10 +2027,10 @@ namespace ts {
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if ((<Identifier>node).isInJSDocNamespace) {
let parentNode = node.parent;
while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) {
while (parentNode && !isJSDocTypeAlias(parentNode)) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(<Declaration>parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
bindBlockScopedDeclaration(parentNode as Declaration, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
break;
}
// falls through
@@ -2141,8 +2132,9 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocSignature:
case SyntaxKind.ConstructorType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
return bindFunctionOrConstructorType(<SignatureDeclaration | JSDocSignature>node);
case SyntaxKind.TypeLiteral:
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.MappedType:
@@ -2205,6 +2197,9 @@ namespace ts {
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
case SyntaxKind.JSDocParameterTag:
if (node.parent.kind === SyntaxKind.JSDocSignature) {
return bindParameter(node as JSDocParameterTag);
}
if (node.parent.kind !== SyntaxKind.JSDocTypeLiteral) {
break;
}
@@ -2215,13 +2210,9 @@ namespace ts {
SymbolFlags.Property | SymbolFlags.Optional :
SymbolFlags.Property;
return declareSymbolAndAddToSymbolTable(propTag, flags, SymbolFlags.PropertyExcludes);
case SyntaxKind.JSDocTypedefTag: {
const { fullName } = node as JSDocTypedefTag;
if (!fullName || fullName.kind === SyntaxKind.Identifier) {
(delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node as JSDocTypedefTag, container, lastContainer, blockScopeContainer, parent });
}
break;
}
case SyntaxKind.JSDocTypedefTag:
case SyntaxKind.JSDocCallbackTag:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node as JSDocTypedefTag | JSDocCallbackTag);
}
}
@@ -2242,7 +2233,7 @@ namespace ts {
bindSourceFileAsExternalModule();
// Create symbol equivalent for the module.exports = {}
const originalSymbol = file.symbol;
declareSymbol(file.symbol.exports, file.symbol, file, SymbolFlags.Property, SymbolFlags.All);
declareSymbol(file.symbol.exports!, file.symbol, file, SymbolFlags.Property, SymbolFlags.All);
file.symbol = originalSymbol;
}
}
@@ -2254,7 +2245,7 @@ namespace ts {
function bindExportAssignment(node: ExportAssignment) {
if (!container.symbol || !container.symbol.exports) {
// Export assignment in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!);
}
else {
const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node)
@@ -2298,7 +2289,7 @@ namespace ts {
function bindExportDeclaration(node: ExportDeclaration) {
if (!container.symbol || !container.symbol.exports) {
// Export * in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.ExportStar, getDeclarationName(node));
bindAnonymousDeclaration(node, SymbolFlags.ExportStar, getDeclarationName(node)!);
}
else if (!node.exportClause) {
// All export * declarations are collected in an __export symbol
@@ -2330,7 +2321,7 @@ namespace ts {
if (!original) {
return undefined;
}
const s = getJSInitializerSymbol(original);
const s = getJSInitializerSymbol(original)!;
addDeclarationToSymbol(s, id, SymbolFlags.Module | SymbolFlags.JSContainer);
return s;
});
@@ -2338,7 +2329,7 @@ namespace ts {
const flags = isClassExpression(node.right) ?
SymbolFlags.Property | SymbolFlags.ExportValue | SymbolFlags.Class :
SymbolFlags.Property | SymbolFlags.ExportValue;
declareSymbol(symbol.exports, symbol, lhs, flags, SymbolFlags.None);
declareSymbol(symbol.exports!, symbol, lhs, flags, SymbolFlags.None);
}
}
@@ -2359,7 +2350,7 @@ namespace ts {
const flags = exportAssignmentIsAlias(node)
? SymbolFlags.Alias // An export= with an EntityNameExpression or a ClassExpression exports all meanings of that identifier or class
: SymbolFlags.Property | SymbolFlags.ExportValue | SymbolFlags.ValueModule;
declareSymbol(file.symbol.exports, file.symbol, node, flags, SymbolFlags.None);
declareSymbol(file.symbol.exports!, file.symbol, node, flags, SymbolFlags.None);
}
function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) {
@@ -2373,7 +2364,7 @@ namespace ts {
if (isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === SyntaxKind.EqualsToken) {
const l = thisContainer.parent.left;
if (isPropertyAccessEntityNameExpression(l) && isPrototypeAccess(l.expression)) {
constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer);
constructorSymbol = getJSInitializerSymbolFromName(l.expression.expression, thisParentContainer)!;
}
}
@@ -2393,7 +2384,7 @@ namespace ts {
// this.foo assignment in a JavaScript class
// Bind this property to the containing class
const containingClass = thisContainer.parent;
const symbolTable = hasModifier(thisContainer, ModifierFlags.Static) ? containingClass.symbol.exports : containingClass.symbol.members;
const symbolTable = hasModifier(thisContainer, ModifierFlags.Static) ? containingClass.symbol.exports! : containingClass.symbol.members!;
declareSymbol(symbolTable, containingClass.symbol, node, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true);
break;
case SyntaxKind.SourceFile:
@@ -2472,7 +2463,7 @@ namespace ts {
bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false);
}
function getJSInitializerSymbolFromName(name: EntityNameExpression, lookupContainer?: Node): Symbol {
function getJSInitializerSymbolFromName(name: EntityNameExpression, lookupContainer?: Node): Symbol | undefined {
return getJSInitializerSymbol(lookupSymbolForPropertyAccess(name, lookupContainer));
}
@@ -2493,7 +2484,7 @@ namespace ts {
return original;
}
else {
return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags, excludeFlags);
return symbol = declareSymbol(symbol ? symbol.exports! : container.locals!, symbol, id, flags, excludeFlags);
}
});
}
@@ -2508,7 +2499,7 @@ namespace ts {
// Declare the method/property
const jsContainerFlag = isToplevelNamespaceableInitializer ? SymbolFlags.JSContainer : 0;
const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess));
const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess)!); // TODO: GH#18217
const symbolFlags = (isMethod ? SymbolFlags.Method : SymbolFlags.Property) | jsContainerFlag;
const symbolExcludes = (isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes) & ~jsContainerFlag;
declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes);
@@ -2531,7 +2522,7 @@ namespace ts {
}
}
function forEachIdentifierInEntityName(e: EntityNameExpression, action: (e: Identifier, symbol: Symbol) => Symbol): Symbol {
function forEachIdentifierInEntityName(e: EntityNameExpression, action: (e: Identifier, symbol: Symbol | undefined) => Symbol | undefined): Symbol | undefined {
if (isExportsOrModuleExportsOrAlias(file, e)) {
return file.symbol;
}
@@ -2540,7 +2531,7 @@ namespace ts {
}
else {
const s = getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action));
Debug.assert(!!s && !!s.exports);
if (!s || !s.exports) return Debug.fail();
return action(e.name, s.exports.get(e.name.escapedText));
}
}
@@ -2566,7 +2557,7 @@ namespace ts {
}
}
const symbol = node.symbol;
const { symbol } = node;
// TypeScript 1.0 spec (April 2014): 8.4
// Every class automatically contains a static property member named 'prototype', the
@@ -2578,14 +2569,14 @@ namespace ts {
// module might have an exported variable called 'prototype'. We can't allow that as
// that would clash with the built-in 'prototype' for the class.
const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype" as __String);
const symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
const symbolExport = symbol.exports!.get(prototypeSymbol.escapedName);
if (symbolExport) {
if (node.name) {
node.name.parent = node;
}
file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol)));
}
symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
symbol.exports!.set(prototypeSymbol.escapedName, prototypeSymbol);
prototypeSymbol.parent = symbol;
}
@@ -2622,7 +2613,10 @@ namespace ts {
}
}
function bindParameter(node: ParameterDeclaration) {
function bindParameter(node: ParameterDeclaration | JSDocParameterTag) {
if (node.kind === SyntaxKind.JSDocParameterTag && container.kind !== SyntaxKind.JSDocSignature) {
return;
}
if (inStrictMode && !(node.flags & NodeFlags.Ambient)) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -2630,7 +2624,7 @@ namespace ts {
}
if (isBindingPattern(node.name)) {
bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, "__" + node.parent.parameters.indexOf(node) as __String);
bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, "__" + (node as ParameterDeclaration).parent.parameters.indexOf(node as ParameterDeclaration) as __String);
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes);
@@ -2640,7 +2634,7 @@ namespace ts {
// containing class.
if (isParameterPropertyDeclaration(node)) {
const classDeclaration = <ClassLikeDeclaration>node.parent.parent;
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
declareSymbol(classDeclaration.symbol.members!, classDeclaration.symbol, node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
}
}
@@ -2689,19 +2683,25 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
function getInferTypeContainer(node: Node): ConditionalTypeNode {
while (node) {
const parent = node.parent;
if (parent && parent.kind === SyntaxKind.ConditionalType && (<ConditionalTypeNode>parent).extendsType === node) {
return <ConditionalTypeNode>parent;
}
node = parent;
}
return undefined;
function getInferTypeContainer(node: Node): ConditionalTypeNode | undefined {
const extendsType = findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n);
return extendsType && extendsType.parent as ConditionalTypeNode;
}
function bindTypeParameter(node: TypeParameterDeclaration) {
if (node.parent.kind === SyntaxKind.InferType) {
if (isJSDocTemplateTag(node.parent)) {
const container = find((node.parent.parent as JSDoc).tags!, isJSDocTypeAlias) || getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
if (container) {
if (!container.locals) {
container.locals = createSymbolTable();
}
declareSymbol(container.locals, /*parent*/ undefined, node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
}
}
else if (node.parent.kind === SyntaxKind.InferType) {
const container = getInferTypeContainer(node.parent);
if (container) {
if (!container.locals) {
@@ -2710,7 +2710,7 @@ namespace ts {
declareSymbol(container.locals, /*parent*/ undefined, node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
}
else {
bindAnonymousDeclaration(node, SymbolFlags.TypeParameter, getDeclarationName(node));
bindAnonymousDeclaration(node, SymbolFlags.TypeParameter, getDeclarationName(node)!); // TODO: GH#18217
}
}
else {
@@ -2722,7 +2722,7 @@ namespace ts {
function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean {
const instanceState = getModuleInstanceState(node);
return instanceState === ModuleInstanceState.Instantiated || (instanceState === ModuleInstanceState.ConstEnumOnly && options.preserveConstEnums);
return instanceState === ModuleInstanceState.Instantiated || (instanceState === ModuleInstanceState.ConstEnumOnly && !!options.preserveConstEnums);
}
function checkUnreachable(node: Node): boolean {
@@ -2743,26 +2743,26 @@ namespace ts {
if (reportError) {
currentFlow = reportedUnreachableFlow;
// unreachable code is reported if
// - user has explicitly asked about it AND
// - statement is in not ambient context (statements in ambient context is already an error
// so we should not report extras) AND
// - node is not variable statement OR
// - node is block scoped variable statement OR
// - node is not block scoped variable statement and at least one variable declaration has initializer
// Rationale: we don't want to report errors on non-initialized var's since they are hoisted
// On the other side we do want to report errors on non-initialized 'lets' because of TDZ
const reportUnreachableCode =
!options.allowUnreachableCode &&
!(node.flags & NodeFlags.Ambient) &&
(
node.kind !== SyntaxKind.VariableStatement ||
getCombinedNodeFlags((<VariableStatement>node).declarationList) & NodeFlags.BlockScoped ||
forEach((<VariableStatement>node).declarationList.declarations, d => d.initializer)
);
if (!options.allowUnreachableCode) {
// unreachable code is reported if
// - user has explicitly asked about it AND
// - statement is in not ambient context (statements in ambient context is already an error
// so we should not report extras) AND
// - node is not variable statement OR
// - node is block scoped variable statement OR
// - node is not block scoped variable statement and at least one variable declaration has initializer
// Rationale: we don't want to report errors on non-initialized var's since they are hoisted
// On the other side we do want to report errors on non-initialized 'lets' because of TDZ
const isError =
unreachableCodeIsError(options) &&
!(node.flags & NodeFlags.Ambient) &&
(
!isVariableStatement(node) ||
!!(getCombinedNodeFlags(node.declarationList) & NodeFlags.BlockScoped) ||
node.declarationList.declarations.some(d => !!d.initializer)
);
if (reportUnreachableCode) {
errorOnFirstToken(node, Diagnostics.Unreachable_code_detected);
errorOrSuggestionOnFirstToken(isError, node, Diagnostics.Unreachable_code_detected);
}
}
}
@@ -2779,8 +2779,8 @@ namespace ts {
function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile: SourceFile, node: Identifier): boolean {
const symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
return symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) &&
symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer);
return !!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) &&
!!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer);
}
function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile: SourceFile, node: Expression): boolean {
@@ -3804,6 +3804,6 @@ namespace ts {
*/
function setParentPointers(parent: Node, child: Node): void {
child.parent = parent;
forEachChild(child, (childsChild) => setParentPointers(child, childsChild));
forEachChild(child, grandchild => setParentPointers(child, grandchild));
}
}
+32 -31
View File
@@ -3,6 +3,7 @@ namespace ts {
/**
* State to store the changed files, affected files and cache semantic diagnostics
*/
// TODO: GH#18217 Properties of this interface are frequently asserted to be defined.
export interface BuilderProgramState extends BuilderState {
/**
* Cache of semantic diagnostics for files with their Path being the key
@@ -41,7 +42,7 @@ namespace ts {
function hasSameKeys<T, U>(map1: ReadonlyMap<T> | undefined, map2: ReadonlyMap<U> | undefined): boolean {
// Has same size and every key is present in both maps
return map1 as ReadonlyMap<T | U> === map2 || map1 && map2 && map1.size === map2.size && !forEachKey(map1, key => !map2.has(key));
return map1 as ReadonlyMap<T | U> === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !forEachKey(map1, key => !map2.has(key));
}
/**
@@ -56,45 +57,45 @@ namespace ts {
}
state.changedFilesSet = createMap<true>();
const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
const canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile;
const canCopySemanticDiagnostics = useOldState && oldState!.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile;
if (useOldState) {
// Verify the sanity of old state
if (!oldState.currentChangedFilePath) {
Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
if (!oldState!.currentChangedFilePath) {
Debug.assert(!oldState!.affectedFiles && (!oldState!.currentAffectedFilesSignatures || !oldState!.currentAffectedFilesSignatures!.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
if (canCopySemanticDiagnostics) {
Debug.assert(!forEachKey(oldState.changedFilesSet, path => oldState.semanticDiagnosticsPerFile.has(path)), "Semantic diagnostics shouldnt be available for changed files");
Debug.assert(!forEachKey(oldState!.changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
copyEntries(oldState.changedFilesSet, state.changedFilesSet);
copyEntries(oldState!.changedFilesSet, state.changedFilesSet);
}
// Update changed files and copy semantic diagnostics if we can
const referencedMap = state.referencedMap;
const oldReferencedMap = useOldState && oldState.referencedMap;
const oldReferencedMap = useOldState ? oldState!.referencedMap : undefined;
state.fileInfos.forEach((info, sourceFilePath) => {
let oldInfo: Readonly<BuilderState.FileInfo>;
let newReferences: BuilderState.ReferencedSet;
let oldInfo: Readonly<BuilderState.FileInfo> | undefined;
let newReferences: BuilderState.ReferencedSet | undefined;
// if not using old state, every file is changed
if (!useOldState ||
// File wasnt present in old state
!(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
!(oldInfo = oldState!.fileInfos.get(sourceFilePath)) ||
// versions dont match
oldInfo.version !== info.version ||
// Referenced files changed
!hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
// Referenced file was deleted in the new program
newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) {
newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState!.fileInfos.has(path))) {
// Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
state.changedFilesSet.set(sourceFilePath, true);
}
else if (canCopySemanticDiagnostics) {
// Unchanged file copy diagnostics
const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath);
if (diagnostics) {
state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
state.semanticDiagnosticsPerFile!.set(sourceFilePath, diagnostics);
}
}
});
@@ -106,7 +107,7 @@ namespace ts {
* Verifies that source file is ok to be used in calls that arent handled by next
*/
function assertSourceFileOkWithoutNextAffectedCall(state: BuilderProgramState, sourceFile: SourceFile | undefined) {
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path));
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex! - 1] !== sourceFile || !state.semanticDiagnosticsPerFile!.has(sourceFile.path));
}
/**
@@ -120,25 +121,25 @@ namespace ts {
const { affectedFiles } = state;
if (affectedFiles) {
const { seenAffectedFiles, semanticDiagnosticsPerFile } = state;
let { affectedFilesIndex } = state;
let affectedFilesIndex = state.affectedFilesIndex!; // TODO: GH#18217
while (affectedFilesIndex < affectedFiles.length) {
const affectedFile = affectedFiles[affectedFilesIndex];
if (!seenAffectedFiles.has(affectedFile.path)) {
if (!seenAffectedFiles!.has(affectedFile.path)) {
// Set the next affected file as seen and remove the cached semantic diagnostics
state.affectedFilesIndex = affectedFilesIndex;
semanticDiagnosticsPerFile.delete(affectedFile.path);
semanticDiagnosticsPerFile!.delete(affectedFile.path);
return affectedFile;
}
seenAffectedFiles.set(affectedFile.path, true);
seenAffectedFiles!.set(affectedFile.path, true);
affectedFilesIndex++;
}
// Remove the changed file from the change set
state.changedFilesSet.delete(state.currentChangedFilePath);
state.changedFilesSet.delete(state.currentChangedFilePath!);
state.currentChangedFilePath = undefined;
// Commit the changes in file signature
BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
state.currentAffectedFilesSignatures.clear();
BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures!);
state.currentAffectedFilesSignatures!.clear();
state.affectedFiles = undefined;
}
@@ -161,7 +162,7 @@ namespace ts {
state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || createMap();
state.affectedFiles = BuilderState.getFilesAffectedBy(state, state.program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures);
state.currentChangedFilePath = nextKey.value as Path;
state.semanticDiagnosticsPerFile.delete(nextKey.value as Path);
state.semanticDiagnosticsPerFile!.delete(nextKey.value as Path);
state.affectedFilesIndex = 0;
state.seenAffectedFiles = state.seenAffectedFiles || createMap<true>();
}
@@ -176,8 +177,8 @@ namespace ts {
state.changedFilesSet.clear();
}
else {
state.seenAffectedFiles.set((affected as SourceFile).path, true);
state.affectedFilesIndex++;
state.seenAffectedFiles!.set((affected as SourceFile).path, true);
state.affectedFilesIndex!++;
}
}
@@ -195,7 +196,7 @@ namespace ts {
*/
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<Diagnostic> {
const path = sourceFile.path;
const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
const cachedDiagnostics = state.semanticDiagnosticsPerFile!.get(path);
// Report the semantic diagnostics from the cache if we already have those diagnostics present
if (cachedDiagnostics) {
return cachedDiagnostics;
@@ -203,7 +204,7 @@ namespace ts {
// Diagnostics werent cached, get them from program, and cache the result
const diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken);
state.semanticDiagnosticsPerFile.set(path, diagnostics);
state.semanticDiagnosticsPerFile!.set(path, diagnostics);
return diagnostics;
}
@@ -250,7 +251,7 @@ namespace ts {
// Return same program if underlying program doesnt change
let oldState = oldProgram && oldProgram.getState();
if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
newProgram = undefined;
newProgram = undefined!; // TODO: GH#18217
oldState = undefined;
return oldProgram;
}
@@ -266,7 +267,7 @@ namespace ts {
const state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined;
newProgram = undefined!; // TODO: GH#18217
oldProgram = undefined;
oldState = undefined;
@@ -336,8 +337,8 @@ namespace ts {
if (!targetSourceFile) {
// Emit and report any errors we ran into.
let sourceMaps: SourceMapData[] = [];
let emitSkipped: boolean;
let diagnostics: Diagnostic[];
let emitSkipped = false;
let diagnostics: Diagnostic[] | undefined;
let emittedFiles: string[] = [];
let affectedEmitResult: AffectedFileResult<EmitResult>;
@@ -423,7 +424,7 @@ namespace ts {
}
}
let diagnostics: Diagnostic[];
let diagnostics: Diagnostic[] | undefined;
for (const sourceFile of state.program.getSourceFiles()) {
diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken));
}
+12 -12
View File
@@ -108,7 +108,7 @@ namespace ts.BuilderState {
return;
}
const fileName = resolvedTypeReferenceDirective.resolvedFileName;
const fileName = resolvedTypeReferenceDirective.resolvedFileName!; // TODO: GH#18217
const typeFilePath = toPath(fileName, sourceFileDirectory, getCanonicalFileName);
addReferencedFile(typeFilePath);
});
@@ -127,7 +127,7 @@ namespace ts.BuilderState {
/**
* Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
*/
export function canReuseOldState(newReferencedMap: ReadonlyMap<ReferencedSet>, oldState: Readonly<BuilderState> | undefined) {
export function canReuseOldState(newReferencedMap: ReadonlyMap<ReferencedSet> | undefined, oldState: Readonly<BuilderState> | undefined) {
return oldState && !oldState.referencedMap === !newReferencedMap;
}
@@ -143,7 +143,7 @@ namespace ts.BuilderState {
// Create the reference map, and set the file infos
for (const sourceFile of newProgram.getSourceFiles()) {
const version = sourceFile.version;
const oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path);
const oldInfo = useOldState ? oldState!.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
const newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
if (newReferences) {
@@ -194,7 +194,7 @@ namespace ts.BuilderState {
*/
export function updateSignaturesFromCache(state: BuilderState, signatureCache: Map<string>) {
signatureCache.forEach((signature, path) => {
state.fileInfos.get(path).signature = signature;
state.fileInfos.get(path)!.signature = signature;
state.hasCalledUpdateShapeSignature.set(path, true);
});
}
@@ -211,7 +211,7 @@ namespace ts.BuilderState {
}
const info = state.fileInfos.get(sourceFile.path);
Debug.assert(!!info);
if (!info) return Debug.fail();
const prevSignature = info.signature;
let latestSignature: string;
@@ -224,7 +224,7 @@ namespace ts.BuilderState {
latestSignature = computeHash(emitOutput.outputFiles[0].text);
}
else {
latestSignature = prevSignature;
latestSignature = prevSignature!; // TODO: GH#18217
}
}
cacheToUpdateSignature.set(sourceFile.path, latestSignature);
@@ -251,7 +251,7 @@ namespace ts.BuilderState {
const seenMap = createMap<true>();
const queue = [sourceFile.path];
while (queue.length) {
const path = queue.pop();
const path = queue.pop()!;
if (!seenMap.has(path)) {
seenMap.set(path, true);
const references = state.referencedMap.get(path);
@@ -285,7 +285,7 @@ namespace ts.BuilderState {
* Gets the files referenced by the the file path
*/
function getReferencedByPaths(state: Readonly<BuilderState>, referencedFilePath: Path) {
return arrayFrom(mapDefinedIterator(state.referencedMap.entries(), ([filePath, referencesInFile]) =>
return arrayFrom(mapDefinedIterator(state.referencedMap!.entries(), ([filePath, referencesInFile]) =>
referencesInFile.has(referencedFilePath) ? filePath as Path : undefined
));
}
@@ -314,7 +314,7 @@ namespace ts.BuilderState {
return state.allFilesExcludingDefaultLibraryFile;
}
let result: SourceFile[];
let result: SourceFile[] | undefined;
addSourceFile(firstSourceFile);
for (const sourceFile of programOfThisState.getSourceFiles()) {
if (sourceFile !== firstSourceFile) {
@@ -366,11 +366,11 @@ namespace ts.BuilderState {
seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape);
const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path);
while (queue.length > 0) {
const currentPath = queue.pop();
const currentPath = queue.pop()!;
if (!seenFileNamesMap.has(currentPath)) {
const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath)!;
seenFileNamesMap.set(currentPath, currentSourceFile);
if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) {
if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash!)) { // TODO: GH#18217
queue.push(...getReferencedByPaths(state, currentPath));
}
}
+1557 -1284
View File
File diff suppressed because it is too large Load Diff
+38 -40
View File
@@ -814,7 +814,7 @@ namespace ts {
case "string":
return map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors)), v => !!v);
return mapDefined(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors));
}
}
@@ -965,7 +965,7 @@ namespace ts {
* Reads the config file, reports errors if any and exits if the config file cannot be found
*/
export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined {
let configFileText: string;
let configFileText: string | undefined;
try {
configFileText = host.readFile(configFileName);
}
@@ -1035,7 +1035,7 @@ namespace ts {
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
_tsconfigRootOptions = {
name: undefined, // should never be needed since this is root
name: undefined!, // should never be needed since this is root
type: "object",
elementOptions: commandLineOptionsToMap([
{
@@ -1194,7 +1194,7 @@ namespace ts {
if (parentOption) {
if (isValidOptionValue) {
// Notify option set in the parent if its a valid option value
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option!, value);
}
}
else if (isRootOptionMap(knownOptions)) {
@@ -1220,7 +1220,7 @@ namespace ts {
return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption));
}
function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption): any {
function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption | undefined): any {
switch (valueExpression.kind) {
case SyntaxKind.TrueKeyword:
reportInvalidOptionValue(option && option.type !== "boolean");
@@ -1303,9 +1303,9 @@ namespace ts {
return undefined;
function reportInvalidOptionValue(isError: boolean) {
function reportInvalidOptionValue(isError: boolean | undefined) {
if (isError) {
errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option!.name, getCompilerOptionValueTypeString(option!)));
}
}
}
@@ -1321,7 +1321,7 @@ namespace ts {
isString(option.type) ? option.type : "string";
}
function isCompilerOptionsValue(option: CommandLineOption, value: any): value is CompilerOptionsValue {
function isCompilerOptionsValue(option: CommandLineOption | undefined, value: any): value is CompilerOptionsValue {
if (option) {
if (isNullOrUndefined(value)) return true; // All options are undefinable/nullable
if (option.type === "list") {
@@ -1330,6 +1330,7 @@ namespace ts {
const expectedType = isString(option.type) ? option.type : "string";
return typeof value === expectedType;
}
return false;
}
/**
@@ -1373,7 +1374,7 @@ namespace ts {
if (hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
if (optionsNameMap.has(name) && optionsNameMap.get(name).category === Diagnostics.Command_line_Options) {
if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) {
continue;
}
const value = <CompilerOptionsValue>options[name];
@@ -1387,7 +1388,7 @@ namespace ts {
}
else {
if (optionDefinition.type === "list") {
result.set(name, (value as ReadonlyArray<string | number>).map(element => getNameOfCompilerOptionValue(element, customTypeMap)));
result.set(name, (value as ReadonlyArray<string | number>).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217
}
else {
// There is a typeMap associated with this command-line option so use it to map value back to its name
@@ -1436,7 +1437,7 @@ namespace ts {
const { category } = option;
if (isAllowedOption(option)) {
categorizedOptions.add(getLocaleSpecificMessage(category), option);
categorizedOptions.add(getLocaleSpecificMessage(category!), option);
}
}
@@ -1517,7 +1518,7 @@ namespace ts {
}
/*@internal*/
export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile) {
export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile | undefined) {
if (configFile) {
Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
}
@@ -1545,7 +1546,7 @@ namespace ts {
*/
function parseJsonConfigFileContentWorker(
json: any,
sourceFile: TsConfigSourceFile,
sourceFile: TsConfigSourceFile | undefined,
host: ParseConfigHost,
basePath: string,
existingOptions: CompilerOptions = {},
@@ -1575,7 +1576,7 @@ namespace ts {
};
function getFileNames(): ExpandResult {
let filesSpecs: ReadonlyArray<string>;
let filesSpecs: ReadonlyArray<string> | undefined;
if (hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
if (isArray(raw.files)) {
filesSpecs = <ReadonlyArray<string>>raw.files;
@@ -1588,7 +1589,7 @@ namespace ts {
}
}
let includeSpecs: ReadonlyArray<string>;
let includeSpecs: ReadonlyArray<string> | undefined;
if (hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
if (isArray(raw.include)) {
includeSpecs = <ReadonlyArray<string>>raw.include;
@@ -1598,7 +1599,7 @@ namespace ts {
}
}
let excludeSpecs: ReadonlyArray<string>;
let excludeSpecs: ReadonlyArray<string> | undefined;
if (hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
if (isArray(raw.exclude)) {
excludeSpecs = <ReadonlyArray<string>>raw.exclude;
@@ -1692,10 +1693,10 @@ namespace ts {
*/
function parseConfig(
json: any,
sourceFile: TsConfigSourceFile,
sourceFile: TsConfigSourceFile | undefined,
host: ParseConfigHost,
basePath: string,
configFileName: string,
configFileName: string | undefined,
resolutionStack: string[],
errors: Push<Diagnostic>,
): ParsedTsconfig {
@@ -1704,17 +1705,17 @@ namespace ts {
if (resolutionStack.indexOf(resolvedPath) >= 0) {
errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
return { raw: json || convertToObject(sourceFile, errors) };
return { raw: json || convertToObject(sourceFile!, errors) };
}
const ownConfig = json ?
parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
parseOwnConfigOfJsonSourceFile(sourceFile!, host, basePath, configFileName, errors);
if (ownConfig.extendedConfigPath) {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = resolutionStack.concat([resolvedPath]);
const extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
const extendedConfig = getExtendedConfig(sourceFile!, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
const baseRaw = extendedConfig.raw;
const raw = ownConfig.raw;
@@ -1754,7 +1755,7 @@ namespace ts {
// It should be removed in future releases - use typeAcquisition instead.
const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
let extendedConfigPath: string;
let extendedConfigPath: string | undefined;
if (json.extends) {
if (!isString(json.extends)) {
@@ -1776,8 +1777,8 @@ namespace ts {
errors: Push<Diagnostic>
): ParsedTsconfig {
const options = getDefaultCompilerOptions(configFileName);
let typeAcquisition: TypeAcquisition, typingOptionstypeAcquisition: TypeAcquisition;
let extendedConfigPath: string;
let typeAcquisition: TypeAcquisition | undefined, typingOptionstypeAcquisition: TypeAcquisition | undefined;
let extendedConfigPath: string | undefined;
const optionsIterator: JsonConversionNotifier = {
onSetValidOptionKeyValueInParent(parentOption: string, option: CommandLineOption, value: CompilerOptionsValue) {
@@ -1879,7 +1880,7 @@ namespace ts {
const extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname,
getBaseFileName(extendedConfigPath), resolutionStack, errors);
if (sourceFile) {
sourceFile.extendedSourceFiles.push(...extendedResult.extendedSourceFiles);
sourceFile.extendedSourceFiles!.push(...extendedResult.extendedSourceFiles!);
}
if (isSuccessfulParsedTsconfig(extendedConfig)) {
@@ -1903,13 +1904,10 @@ namespace ts {
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Push<Diagnostic>): boolean {
if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
return undefined;
return false;
}
const result = convertJsonOption(compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
if (typeof result === "boolean" && result) {
return result;
}
return false;
return typeof result === "boolean" && result;
}
export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
@@ -1943,7 +1941,7 @@ namespace ts {
}
function getDefaultTypeAcquisition(configFileName?: string): TypeAcquisition {
return { enable: configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions: any,
@@ -2106,18 +2104,18 @@ namespace ts {
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(
filesSpecs: ReadonlyArray<string>,
includeSpecs: ReadonlyArray<string>,
excludeSpecs: ReadonlyArray<string>,
filesSpecs: ReadonlyArray<string> | undefined,
includeSpecs: ReadonlyArray<string> | undefined,
excludeSpecs: ReadonlyArray<string> | undefined,
basePath: string,
options: CompilerOptions,
host: ParseConfigHost,
errors: Push<Diagnostic>,
extraFileExtensions: ReadonlyArray<FileExtensionInfo>,
jsonSourceFile: TsConfigSourceFile
jsonSourceFile: TsConfigSourceFile | undefined
): ExpandResult {
basePath = normalizePath(basePath);
let validatedIncludeSpecs: ReadonlyArray<string>, validatedExcludeSpecs: ReadonlyArray<string>;
let validatedIncludeSpecs: ReadonlyArray<string> | undefined, validatedExcludeSpecs: ReadonlyArray<string> | undefined;
// The exclude spec list is converted into a regular expression, which allows us to quickly
// test whether a file or directory should be excluded before recursively traversing the
@@ -2223,7 +2221,7 @@ namespace ts {
};
}
function validateSpecs(specs: ReadonlyArray<string>, errors: Push<Diagnostic>, allowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile, specKey: string): ReadonlyArray<string> {
function validateSpecs(specs: ReadonlyArray<string>, errors: Push<Diagnostic>, allowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile | undefined, specKey: string): ReadonlyArray<string> {
return specs.filter(spec => {
const diag = specToDiagnostic(spec, allowTrailingRecursion);
if (diag !== undefined) {
@@ -2235,7 +2233,7 @@ namespace ts {
function createDiagnostic(message: DiagnosticMessage, spec: string): Diagnostic {
const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
return element ?
createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
createDiagnosticForNodeInSourceFile(jsonSourceFile!, element, message, spec) :
createCompilerDiagnostic(message, spec);
}
}
@@ -2252,7 +2250,7 @@ namespace ts {
/**
* Gets directories in a set of include patterns that should be watched for changes.
*/
function getWildcardDirectories(include: ReadonlyArray<string>, exclude: ReadonlyArray<string>, path: string, useCaseSensitiveFileNames: boolean): MapLike<WatchDirectoryFlags> {
function getWildcardDirectories(include: ReadonlyArray<string> | undefined, exclude: ReadonlyArray<string> | undefined, path: string, useCaseSensitiveFileNames: boolean): MapLike<WatchDirectoryFlags> {
// We watch a directory recursively if it contains a wildcard anywhere in a directory segment
// of the pattern:
//
@@ -2394,7 +2392,7 @@ namespace ts {
if (optionEnumValue === value) {
return optionStringValue;
}
});
})!; // TODO: GH#18217
}
}
}
+14 -14
View File
@@ -3,8 +3,8 @@ namespace ts {
export interface CommentWriter {
reset(): void;
setSourceFile(sourceFile: SourceFile): void;
setWriter(writer: EmitTextWriter): void;
emitNodeWithComments(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
setWriter(writer: EmitTextWriter | undefined): void;
emitNodeWithComments(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node) => void): void;
emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void;
emitTrailingCommentsOfPosition(pos: number, prefixSpace?: boolean): void;
emitLeadingCommentsOfPosition(pos: number): void;
@@ -20,9 +20,9 @@ namespace ts {
let currentSourceFile: SourceFile;
let currentText: string;
let currentLineMap: ReadonlyArray<number>;
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[];
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined;
let hasWrittenComment = false;
let disabled: boolean = printerOptions.removeComments;
let disabled: boolean = !!printerOptions.removeComments;
return {
reset,
@@ -44,7 +44,7 @@ namespace ts {
hasWrittenComment = false;
const emitNode = node.emitNode;
const emitFlags = emitNode && emitNode.flags;
const emitFlags = emitNode && emitNode.flags || 0;
const { pos, end } = emitNode && emitNode.commentRange || node;
if ((pos < 0 && end < 0) || (pos === end)) {
// Both pos and end are synthesized, so just emit the node without comments.
@@ -114,7 +114,7 @@ namespace ts {
}
}
function emitNodeWithSynthesizedComments(hint: EmitHint, node: Node, emitNode: EmitNode, emitFlags: EmitFlags, emitCallback: (hint: EmitHint, node: Node) => void) {
function emitNodeWithSynthesizedComments(hint: EmitHint, node: Node, emitNode: EmitNode | undefined, emitFlags: EmitFlags, emitCallback: (hint: EmitHint, node: Node) => void) {
const leadingComments = emitNode && emitNode.leadingComments;
if (some(leadingComments)) {
if (extendedDiagnostics) {
@@ -170,7 +170,7 @@ namespace ts {
function writeSynthesizedComment(comment: SynthesizedComment) {
const text = formatSynthesizedComment(comment);
const lineMap = comment.kind === SyntaxKind.MultiLineCommentTrivia ? computeLineStarts(text) : undefined;
writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
writeCommentRange(text, lineMap!, writer, 0, text.length, newLine);
}
function formatSynthesizedComment(comment: SynthesizedComment) {
@@ -364,9 +364,9 @@ namespace ts {
}
function reset() {
currentSourceFile = undefined;
currentText = undefined;
currentLineMap = undefined;
currentSourceFile = undefined!;
currentText = undefined!;
currentLineMap = undefined!;
detachedCommentsInfo = undefined;
}
@@ -382,14 +382,14 @@ namespace ts {
}
function hasDetachedComments(pos: number) {
return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos;
return detachedCommentsInfo !== undefined && last(detachedCommentsInfo).nodePos === pos;
}
function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) {
// get the leading comments from detachedPos
const pos = lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos;
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
const pos = last(detachedCommentsInfo!).detachedCommentEndPos;
if (detachedCommentsInfo!.length - 1) {
detachedCommentsInfo!.pop();
}
else {
detachedCommentsInfo = undefined;
+165 -103
View File
@@ -1,7 +1,7 @@
namespace ts {
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configureNightly` too.
export const versionMajorMinor = "2.9";
export const versionMajorMinor = "3.0";
/** The version of the TypeScript compiler release */
export const version = `${versionMajorMinor}.0-dev`;
}
@@ -14,8 +14,8 @@ namespace ts {
return pathIsRelative(moduleName) || isRootedDiskPath(moduleName);
}
export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray<Diagnostic>): Diagnostic[] {
return sortAndDeduplicate(diagnostics, compareDiagnostics);
export function sortAndDeduplicateDiagnostics<T extends Diagnostic>(diagnostics: ReadonlyArray<T>): T[] {
return sortAndDeduplicate<T>(diagnostics, compareDiagnostics);
}
}
@@ -59,7 +59,7 @@ namespace ts {
return result;
}
export function createMapFromTemplate<T>(template?: MapLike<T>): Map<T> {
export function createMapFromTemplate<T>(template: MapLike<T>): Map<T> {
const map: Map<T> = new MapCtr<T>();
// Copies keys/values from template. Note that for..in will not throw if
@@ -107,7 +107,7 @@ namespace ts {
private data = createDictionaryObject<T>();
public size = 0;
get(key: string): T {
get(key: string): T | undefined {
return this.data[key];
}
@@ -138,15 +138,15 @@ namespace ts {
this.size = 0;
}
keys() {
keys(): Iterator<string> {
return new MapIterator(this.data, (_data, key) => key);
}
values() {
values(): Iterator<T> {
return new MapIterator(this.data, (data, key) => data[key]);
}
entries() {
entries(): Iterator<[string, T]> {
return new MapIterator(this.data, (data, key) => [key, data[key]] as [string, T]);
}
@@ -158,14 +158,14 @@ namespace ts {
};
}
export function toPath(fileName: string, basePath: string, getCanonicalFileName: (path: string) => string): Path {
export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path {
const nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return <Path>getCanonicalFileName(nonCanonicalizedPath);
}
export function length(array: ReadonlyArray<any>) {
export function length(array: ReadonlyArray<any> | undefined): number {
return array ? array.length : 0;
}
@@ -220,9 +220,9 @@ namespace ts {
* If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit"
* At that point findAncestor returns undefined.
*/
export function findAncestor<T extends Node>(node: Node, callback: (element: Node) => element is T): T | undefined;
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node | undefined;
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node {
export function findAncestor<T extends Node>(node: Node | undefined, callback: (element: Node) => element is T): T | undefined;
export function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined;
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node | undefined {
while (node) {
const result = callback(node);
if (result === "quit") {
@@ -320,6 +320,15 @@ namespace ts {
return -1;
}
export function findLastIndex<T>(array: ReadonlyArray<T>, predicate: (element: T, index: number) => boolean, startIndex?: number): number {
for (let i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
if (predicate(array[i], i)) {
return i;
}
}
return -1;
}
/**
* Returns the first truthy result of `callback`, or else fails.
* This is like `forEach`, but never returns undefined.
@@ -331,10 +340,10 @@ namespace ts {
return result;
}
}
Debug.fail();
return Debug.fail();
}
export function contains<T>(array: ReadonlyArray<T>, value: T, equalityComparer: EqualityComparer<T> = equateValues): boolean {
export function contains<T>(array: ReadonlyArray<T> | undefined, value: T, equalityComparer: EqualityComparer<T> = equateValues): boolean {
if (array) {
for (const v of array) {
if (equalityComparer(v, value)) {
@@ -379,7 +388,11 @@ namespace ts {
export function filter<T>(array: T[], f: (x: T) => boolean): T[];
export function filter<T, U extends T>(array: ReadonlyArray<T>, f: (x: T) => x is U): ReadonlyArray<U>;
export function filter<T, U extends T>(array: ReadonlyArray<T>, f: (x: T) => boolean): ReadonlyArray<T>;
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
export function filter<T, U extends T>(array: T[] | undefined, f: (x: T) => x is U): U[] | undefined;
export function filter<T>(array: T[] | undefined, f: (x: T) => boolean): T[] | undefined;
export function filter<T, U extends T>(array: ReadonlyArray<T> | undefined, f: (x: T) => x is U): ReadonlyArray<U> | undefined;
export function filter<T, U extends T>(array: ReadonlyArray<T> | undefined, f: (x: T) => boolean): ReadonlyArray<T> | undefined;
export function filter<T>(array: ReadonlyArray<T> | undefined, f: (x: T) => boolean): ReadonlyArray<T> | undefined {
if (array) {
const len = array.length;
let i = 0;
@@ -415,8 +428,10 @@ namespace ts {
array.length = 0;
}
export function map<T, U>(array: ReadonlyArray<T>, f: (x: T, i: number) => U): U[] {
let result: U[];
export function map<T, U>(array: ReadonlyArray<T>, f: (x: T, i: number) => U): U[];
export function map<T, U>(array: ReadonlyArray<T> | undefined, f: (x: T, i: number) => U): U[] | undefined;
export function map<T, U>(array: ReadonlyArray<T> | undefined, f: (x: T, i: number) => U): U[] | undefined {
let result: U[] | undefined;
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
@@ -439,7 +454,9 @@ namespace ts {
// Maps from T to T and avoids allocation if all elements map to themselves
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[];
export function sameMap<T>(array: ReadonlyArray<T>, f: (x: T, i: number) => T): ReadonlyArray<T>;
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[] {
export function sameMap<T>(array: T[] | undefined, f: (x: T, i: number) => T): T[] | undefined;
export function sameMap<T>(array: ReadonlyArray<T> | undefined, f: (x: T, i: number) => T): ReadonlyArray<T> | undefined;
export function sameMap<T>(array: ReadonlyArray<T> | undefined, f: (x: T, i: number) => T): ReadonlyArray<T> | undefined {
if (array) {
for (let i = 0; i < array.length; i++) {
const item = array[i];
@@ -462,8 +479,10 @@ namespace ts {
*
* @param array The array to flatten.
*/
export function flatten<T>(array: ReadonlyArray<T | ReadonlyArray<T>>): T[] {
let result: T[];
export function flatten<T>(array: ReadonlyArray<T | ReadonlyArray<T> | undefined>): T[];
export function flatten<T>(array: ReadonlyArray<T | ReadonlyArray<T> | undefined> | undefined): T[] | undefined;
export function flatten<T>(array: ReadonlyArray<T | ReadonlyArray<T> | undefined> | undefined): T[] | undefined {
let result: T[] | undefined;
if (array) {
result = [];
for (const v of array) {
@@ -487,8 +506,10 @@ namespace ts {
* @param array The array to map.
* @param mapfn The callback used to map the result into one or more values.
*/
export function flatMap<T, U>(array: ReadonlyArray<T>, mapfn: (x: T, i: number) => U | ReadonlyArray<U> | undefined): U[];
export function flatMap<T, U>(array: ReadonlyArray<T> | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray<U> | undefined): U[] | undefined;
export function flatMap<T, U>(array: ReadonlyArray<T> | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray<U> | undefined): U[] | undefined {
let result: U[];
let result: U[] | undefined;
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
@@ -544,7 +565,7 @@ namespace ts {
export function sameFlatMap<T>(array: T[], mapfn: (x: T, i: number) => T | ReadonlyArray<T>): T[];
export function sameFlatMap<T>(array: ReadonlyArray<T>, mapfn: (x: T, i: number) => T | ReadonlyArray<T>): ReadonlyArray<T>;
export function sameFlatMap<T>(array: T[], mapfn: (x: T, i: number) => T | T[]): T[] {
let result: T[];
let result: T[] | undefined;
if (array) {
for (let i = 0; i < array.length; i++) {
const item = array[i];
@@ -627,13 +648,15 @@ namespace ts {
* @param keyfn A callback used to select the key for an element.
* @param mapfn A callback used to map a contiguous chunk of values to a single value.
*/
export function spanMap<T, K, U>(array: ReadonlyArray<T>, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] {
let result: U[];
export function spanMap<T, K, U>(array: ReadonlyArray<T>, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[];
export function spanMap<T, K, U>(array: ReadonlyArray<T> | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined;
export function spanMap<T, K, U>(array: ReadonlyArray<T> | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined {
let result: U[] | undefined;
if (array) {
result = [];
const len = array.length;
let previousKey: K;
let key: K;
let previousKey: K | undefined;
let key: K | undefined;
let start = 0;
let pos = 0;
while (start < len) {
@@ -651,7 +674,7 @@ namespace ts {
}
if (start < pos) {
const v = mapfn(array.slice(start, pos), previousKey, start, pos);
const v = mapfn(array.slice(start, pos), previousKey!, start, pos);
if (v) {
result.push(v);
}
@@ -667,7 +690,9 @@ namespace ts {
return result;
}
export function mapEntries<T, U>(map: ReadonlyMap<T>, f: (key: string, value: T) => [string, U]): Map<U> {
export function mapEntries<T, U>(map: ReadonlyMap<T>, f: (key: string, value: T) => [string, U]): Map<U>;
export function mapEntries<T, U>(map: ReadonlyMap<T> | undefined, f: (key: string, value: T) => [string, U]): Map<U> | undefined;
export function mapEntries<T, U>(map: ReadonlyMap<T> | undefined, f: (key: string, value: T) => [string, U]): Map<U> | undefined {
if (!map) {
return undefined;
}
@@ -679,8 +704,9 @@ namespace ts {
});
return result;
}
export function some<T>(array: ReadonlyArray<T>, predicate?: (value: T) => boolean): boolean {
export function some<T>(array: ReadonlyArray<T> | undefined): array is ReadonlyArray<T>;
export function some<T>(array: ReadonlyArray<T> | undefined, predicate: (value: T) => boolean): boolean;
export function some<T>(array: ReadonlyArray<T> | undefined, predicate?: (value: T) => boolean): boolean {
if (array) {
if (predicate) {
for (const v of array) {
@@ -696,8 +722,27 @@ namespace ts {
return false;
}
/** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
export function getRangesWhere<T>(arr: ReadonlyArray<T>, pred: (t: T) => boolean, cb: (start: number, afterEnd: number) => void): void {
let start: number | undefined;
for (let i = 0; i < arr.length; i++) {
if (pred(arr[i])) {
start = start === undefined ? i : start;
}
else {
if (start !== undefined) {
cb(start, i);
start = undefined;
}
}
}
if (start !== undefined) cb(start, arr.length);
}
export function concatenate<T>(array1: T[], array2: T[]): T[];
export function concatenate<T>(array1: ReadonlyArray<T>, array2: ReadonlyArray<T>): ReadonlyArray<T>;
export function concatenate<T>(array1: T[] | undefined, array2: T[] | undefined): T[];
export function concatenate<T>(array1: ReadonlyArray<T> | undefined, array2: ReadonlyArray<T> | undefined): ReadonlyArray<T>;
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!some(array2)) return array1;
if (!some(array1)) return array2;
@@ -740,7 +785,9 @@ namespace ts {
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
export function deduplicate<T>(array: ReadonlyArray<T>, equalityComparer: EqualityComparer<T>, comparer?: Comparer<T>): T[] {
export function deduplicate<T>(array: ReadonlyArray<T>, equalityComparer?: EqualityComparer<T>, comparer?: Comparer<T>): T[];
export function deduplicate<T>(array: ReadonlyArray<T> | undefined, equalityComparer?: EqualityComparer<T>, comparer?: Comparer<T>): T[] | undefined;
export function deduplicate<T>(array: ReadonlyArray<T> | undefined, equalityComparer: EqualityComparer<T>, comparer?: Comparer<T>): T[] | undefined {
return !array ? undefined :
array.length === 0 ? [] :
array.length === 1 ? array.slice() :
@@ -751,7 +798,9 @@ namespace ts {
/**
* Deduplicates an array that has already been sorted.
*/
function deduplicateSorted<T>(array: ReadonlyArray<T>, comparer: EqualityComparer<T> | Comparer<T>) {
function deduplicateSorted<T>(array: ReadonlyArray<T>, comparer: EqualityComparer<T> | Comparer<T>): T[];
function deduplicateSorted<T>(array: ReadonlyArray<T> | undefined, comparer: EqualityComparer<T> | Comparer<T>): T[] | undefined;
function deduplicateSorted<T>(array: ReadonlyArray<T> | undefined, comparer: EqualityComparer<T> | Comparer<T>): T[] | undefined {
if (!array) return undefined;
if (array.length === 0) return [];
@@ -794,7 +843,7 @@ namespace ts {
return deduplicateSorted(sort(array, comparer), equalityComparer || comparer);
}
export function arrayIsEqualTo<T>(array1: ReadonlyArray<T>, array2: ReadonlyArray<T>, equalityComparer: (a: T, b: T) => boolean = equateValues): boolean {
export function arrayIsEqualTo<T>(array1: ReadonlyArray<T> | undefined, array2: ReadonlyArray<T> | undefined, equalityComparer: (a: T, b: T) => boolean = equateValues): boolean {
if (!array1 || !array2) {
return array1 === array2;
}
@@ -837,7 +886,7 @@ namespace ts {
export function compact<T>(array: T[]): T[];
export function compact<T>(array: ReadonlyArray<T>): ReadonlyArray<T>;
export function compact<T>(array: T[]): T[] {
let result: T[];
let result: T[] | undefined;
if (array) {
for (let i = 0; i < array.length; i++) {
const v = array[i];
@@ -913,7 +962,11 @@ namespace ts {
* @param value The value to append to the array. If `value` is `undefined`, nothing is
* appended.
*/
export function append<T>(to: T[] | undefined, value: T | undefined): T[] | undefined {
export function append<T>(to: T[], value: T | undefined): T[];
export function append<T>(to: T[] | undefined, value: T): T[];
export function append<T>(to: T[] | undefined, value: T | undefined): T[] | undefined;
export function append<T>(to: Push<T>, value: T | undefined): void;
export function append<T>(to: T[], value: T | undefined): T[] | undefined {
if (value === undefined) return to;
if (to === undefined) return [value];
to.push(value);
@@ -938,6 +991,8 @@ namespace ts {
* @param start The offset in `from` at which to start copying values.
* @param end The offset in `from` at which to stop copying values (non-inclusive).
*/
export function addRange<T>(to: T[], from: ReadonlyArray<T> | undefined, start?: number, end?: number): T[];
export function addRange<T>(to: T[] | undefined, from: ReadonlyArray<T> | undefined, start?: number, end?: number): T[] | undefined;
export function addRange<T>(to: T[] | undefined, from: ReadonlyArray<T> | undefined, start?: number, end?: number): T[] | undefined {
if (from === undefined || from.length === 0) return to;
if (to === undefined) return from.slice(start, end);
@@ -1000,7 +1055,7 @@ namespace ts {
/**
* Returns a new sorted array.
*/
export function sort<T>(array: ReadonlyArray<T>, comparer: Comparer<T>) {
export function sort<T>(array: ReadonlyArray<T>, comparer: Comparer<T>): T[] {
return array.slice().sort(comparer);
}
@@ -1094,7 +1149,7 @@ namespace ts {
/**
* Returns the only element of an array if it contains only one element, `undefined` otherwise.
*/
export function singleOrUndefined<T>(array: ReadonlyArray<T>): T | undefined {
export function singleOrUndefined<T>(array: ReadonlyArray<T> | undefined): T | undefined {
return array && array.length === 1
? array[0]
: undefined;
@@ -1106,7 +1161,9 @@ namespace ts {
*/
export function singleOrMany<T>(array: T[]): T | T[];
export function singleOrMany<T>(array: ReadonlyArray<T>): T | ReadonlyArray<T>;
export function singleOrMany<T>(array: T[]): T | T[] {
export function singleOrMany<T>(array: T[] | undefined): T | T[] | undefined;
export function singleOrMany<T>(array: ReadonlyArray<T> | undefined): T | ReadonlyArray<T> | undefined;
export function singleOrMany<T>(array: ReadonlyArray<T> | undefined): T | ReadonlyArray<T> | undefined {
return array && array.length === 1
? array[0]
: array;
@@ -1155,9 +1212,9 @@ namespace ts {
return ~low;
}
export function reduceLeft<T, U>(array: ReadonlyArray<T>, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
export function reduceLeft<T>(array: ReadonlyArray<T>, f: (memo: T, value: T, i: number) => T): T;
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
export function reduceLeft<T, U>(array: ReadonlyArray<T> | undefined, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
export function reduceLeft<T>(array: ReadonlyArray<T>, f: (memo: T, value: T, i: number) => T): T | undefined;
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T | undefined {
if (array && array.length > 0) {
const size = array.length;
if (size > 0) {
@@ -1169,7 +1226,7 @@ namespace ts {
pos++;
}
else {
result = initial;
result = initial!;
}
while (pos <= end) {
result = f(result, array[pos], pos);
@@ -1280,11 +1337,11 @@ namespace ts {
});
}
export function assign<T extends object>(t: T, ...args: T[]) {
export function assign<T extends object>(t: T, ...args: (T | undefined)[]) {
for (const arg of args) {
for (const p in arg) {
if (hasProperty(arg, p)) {
t[p] = arg[p];
for (const p in arg!) {
if (hasProperty(arg!, p)) {
t![p] = arg![p]; // TODO: GH#23368
}
}
}
@@ -1297,7 +1354,7 @@ namespace ts {
* @param left A map-like whose properties should be compared.
* @param right A map-like whose properties should be compared.
*/
export function equalOwnProperties<T>(left: MapLike<T>, right: MapLike<T>, equalityComparer: EqualityComparer<T> = equateValues) {
export function equalOwnProperties<T>(left: MapLike<T> | undefined, right: MapLike<T> | undefined, equalityComparer: EqualityComparer<T> = equateValues) {
if (left === right) return true;
if (!left || !right) return false;
for (const key in left) {
@@ -1477,10 +1534,10 @@ namespace ts {
if (value !== undefined && test(value)) return value;
if (value && typeof (value as any).kind === "number") {
Debug.fail(`Invalid cast. The supplied ${Debug.showSyntaxKind(value as any as Node)} did not pass the test '${Debug.getFunctionName(test)}'.`);
return Debug.fail(`Invalid cast. The supplied ${Debug.showSyntaxKind(value as any as Node)} did not pass the test '${Debug.getFunctionName(test)}'.`);
}
else {
Debug.fail(`Invalid cast. The supplied value did not pass the test '${Debug.getFunctionName(test)}'.`);
return Debug.fail(`Invalid cast. The supplied value did not pass the test '${Debug.getFunctionName(test)}'.`);
}
}
@@ -1509,7 +1566,7 @@ namespace ts {
return () => {
if (callback) {
value = callback();
callback = undefined;
callback = undefined!;
}
return value;
};
@@ -1581,20 +1638,18 @@ namespace ts {
}
}
export function formatStringFromArgs(text: string, args: ArrayLike<string>, baseIndex?: number): string {
baseIndex = baseIndex || 0;
return text.replace(/{(\d+)}/g, (_match, index?: string) => Debug.assertDefined(args[+index + baseIndex]));
export function formatStringFromArgs(text: string, args: ArrayLike<string>, baseIndex = 0): string {
return text.replace(/{(\d+)}/g, (_match, index: string) => Debug.assertDefined(args[+index + baseIndex]));
}
export let localizedDiagnosticMessages: MapLike<string>;
export let localizedDiagnosticMessages: MapLike<string> | undefined;
export function getLocaleSpecificMessage(message: DiagnosticMessage) {
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message;
}
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic;
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic {
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticWithLocation;
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): DiagnosticWithLocation {
Debug.assertGreaterThanOrEqual(start, 0);
Debug.assertGreaterThanOrEqual(length, 0);
@@ -1632,7 +1687,7 @@ namespace ts {
return text;
}
export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number)[]): Diagnostic;
export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number | undefined)[]): Diagnostic;
export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic {
let text = getLocaleSpecificMessage(message);
@@ -1664,8 +1719,8 @@ namespace ts {
};
}
export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: string[]): DiagnosticMessageChain;
export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain {
export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain;
export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage): DiagnosticMessageChain {
let text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
@@ -1720,9 +1775,9 @@ namespace ts {
return equateValues(a, b);
}
function compareComparableValues(a: string, b: string): Comparison;
function compareComparableValues(a: number, b: number): Comparison;
function compareComparableValues(a: string | number, b: string | number) {
function compareComparableValues(a: string | undefined, b: string | undefined): Comparison;
function compareComparableValues(a: number | undefined, b: number | undefined): Comparison;
function compareComparableValues(a: string | number | undefined, b: string | number | undefined) {
return a === b ? Comparison.EqualTo :
a === undefined ? Comparison.LessThan :
b === undefined ? Comparison.GreaterThan :
@@ -1734,7 +1789,7 @@ namespace ts {
* Compare two numeric values for their order relative to each other.
* To compare strings, use any of the `compareStrings` functions.
*/
export function compareValues(a: number, b: number) {
export function compareValues(a: number | undefined, b: number | undefined): Comparison {
return compareComparableValues(a, b);
}
@@ -1773,7 +1828,7 @@ namespace ts {
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point.
*/
export function compareStringsCaseSensitive(a: string, b: string) {
export function compareStringsCaseSensitive(a: string | undefined, b: string | undefined): Comparison {
return compareComparableValues(a, b);
}
@@ -1876,7 +1931,7 @@ namespace ts {
return uiLocale;
}
export function setUILocale(value: string) {
export function setUILocale(value: string | undefined) {
if (uiLocale !== value) {
uiLocale = value;
uiComparerCaseSensitive = undefined;
@@ -1898,14 +1953,14 @@ namespace ts {
return comparer(a, b);
}
export function compareProperties<T, K extends keyof T>(a: T, b: T, key: K, comparer: Comparer<T[K]>) {
export function compareProperties<T, K extends keyof T>(a: T | undefined, b: T | undefined, key: K, comparer: Comparer<T[K]>): Comparison {
return a === b ? Comparison.EqualTo :
a === undefined ? Comparison.LessThan :
b === undefined ? Comparison.GreaterThan :
comparer(a[key], b[key]);
}
function getDiagnosticFilePath(diagnostic: Diagnostic): string {
function getDiagnosticFilePath(diagnostic: Diagnostic): string | undefined {
return diagnostic.file ? diagnostic.file.path : undefined;
}
@@ -1923,7 +1978,9 @@ namespace ts {
return compareValues(a ? 1 : 0, b ? 1 : 0);
}
function compareMessageText(text1: string | DiagnosticMessageChain, text2: string | DiagnosticMessageChain): Comparison {
function compareMessageText(t1: string | DiagnosticMessageChain, t2: string | DiagnosticMessageChain): Comparison {
let text1: string | DiagnosticMessageChain | undefined = t1;
let text2: string | DiagnosticMessageChain | undefined = t2;
while (text1 && text2) {
// We still have both chains.
const string1 = isString(text1) ? text1 : text1.messageText;
@@ -1965,6 +2022,14 @@ namespace ts {
return moduleResolution;
}
export function unreachableCodeIsError(options: CompilerOptions): boolean {
return options.allowUnreachableCode === false;
}
export function unusedLabelIsError(options: CompilerOptions): boolean {
return options.allowUnusedLabels === false;
}
export function getAreDeclarationMapsEnabled(options: CompilerOptions) {
return !!(options.declaration && options.declarationMap);
}
@@ -1985,7 +2050,7 @@ namespace ts {
export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictPropertyInitialization" | "alwaysStrict";
export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
@@ -2264,11 +2329,11 @@ namespace ts {
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*/
export function getNormalizedPathComponents(path: string, currentDirectory: string) {
export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string) {
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) {
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
@@ -2395,7 +2460,7 @@ namespace ts {
/**
* Combines paths. If a path is absolute, it replaces any previous path.
*/
export function combinePaths(path: string, ...paths: string[]): string {
export function combinePaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
@@ -2414,7 +2479,7 @@ namespace ts {
* Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
* `.` and `..` path components are resolved.
*/
export function resolvePath(path: string, ...paths: string[]): string {
export function resolvePath(path: string, ...paths: (string | undefined)[]): string {
const combined = some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path);
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
@@ -2589,7 +2654,7 @@ namespace ts {
/**
* Matches any single directory segment unless it is the last segment and a .min.js file
* Breakdown:
* [^./] # matches everything up to the first . character (excluding directory seperators)
* [^./] # matches everything up to the first . character (excluding directory separators)
* (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
*/
singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
@@ -2623,7 +2688,7 @@ namespace ts {
exclude: excludeMatcher
};
export function getRegularExpressionForWildcard(specs: ReadonlyArray<string>, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined {
export function getRegularExpressionForWildcard(specs: ReadonlyArray<string> | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined {
const patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
if (!patterns || !patterns.length) {
return undefined;
@@ -2635,7 +2700,7 @@ namespace ts {
return `^(${pattern})${terminator}`;
}
function getRegularExpressionsForWildcards(specs: ReadonlyArray<string>, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined {
function getRegularExpressionsForWildcards(specs: ReadonlyArray<string> | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined {
if (specs === undefined || specs.length === 0) {
return undefined;
}
@@ -2656,7 +2721,7 @@ namespace ts {
let subpattern = "";
let hasWrittenComponent = false;
const components = getNormalizedPathComponents(spec, basePath);
const lastComponent = lastOrUndefined(components);
const lastComponent = last(components);
if (usage !== "exclude" && lastComponent === "**") {
return undefined;
}
@@ -2739,15 +2804,15 @@ namespace ts {
export interface FileMatcherPatterns {
/** One pattern for each "include" spec. */
includeFilePatterns: ReadonlyArray<string>;
includeFilePatterns: ReadonlyArray<string> | undefined;
/** One pattern matching one of any of the "include" specs. */
includeFilePattern: string;
includeDirectoryPattern: string;
excludePattern: string;
includeFilePattern: string | undefined;
includeDirectoryPattern: string | undefined;
excludePattern: string | undefined;
basePaths: ReadonlyArray<string>;
}
export function getFileMatcherPatterns(path: string, excludes: ReadonlyArray<string>, includes: ReadonlyArray<string>, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns {
export function getFileMatcherPatterns(path: string, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns {
path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory);
const absolutePath = combinePaths(currentDirectory, path);
@@ -2761,7 +2826,7 @@ namespace ts {
};
}
export function matchFiles(path: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string>, includes: ReadonlyArray<string>, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries): string[] {
export function matchFiles(path: string, extensions: ReadonlyArray<string> | undefined, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries): string[] {
path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory);
@@ -2785,7 +2850,7 @@ namespace ts {
function visitDirectory(path: string, absolutePath: string, depth: number | undefined) {
const { files, directories } = getFileSystemEntries(path);
for (const current of sort(files, compareStringsCaseSensitive)) {
for (const current of sort<string>(files, compareStringsCaseSensitive)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
@@ -2808,7 +2873,7 @@ namespace ts {
}
}
for (const current of sort(directories, compareStringsCaseSensitive)) {
for (const current of sort<string>(directories, compareStringsCaseSensitive)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
@@ -2822,7 +2887,7 @@ namespace ts {
/**
* Computes the unique non-wildcard base paths amongst the provided include patterns.
*/
function getBasePaths(path: string, includes: ReadonlyArray<string>, useCaseSensitiveFileNames: boolean) {
function getBasePaths(path: string, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean): string[] {
// Storage for our results in the form of literal paths (e.g. the paths as written by the user).
const basePaths: string[] = [path];
@@ -2912,19 +2977,19 @@ namespace ts {
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined)
];
return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
return deduplicate<string>(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
function isJavaScriptLike(scriptKind: ScriptKind): boolean {
function isJavaScriptLike(scriptKind: ScriptKind | undefined): boolean {
return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX;
}
export function hasJavaScriptFileExtension(fileName: string) {
return forEach(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
export function hasJavaScriptFileExtension(fileName: string): boolean {
return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
}
export function hasTypeScriptFileExtension(fileName: string) {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
export function hasTypeScriptFileExtension(fileName: string): boolean {
return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray<FileExtensionInfo>) {
@@ -3045,8 +3110,8 @@ namespace ts {
function Symbol(this: Symbol, flags: SymbolFlags, name: __String) {
this.flags = flags;
this.escapedName = name;
this.declarations = undefined;
this.valueDeclaration = undefined;
this.declarations = undefined!;
this.valueDeclaration = undefined!;
this.id = undefined;
this.mergeId = undefined;
this.parent = undefined;
@@ -3069,7 +3134,7 @@ namespace ts {
this.flags = NodeFlags.None;
this.modifierFlagsCache = ModifierFlags.None;
this.transformFlags = TransformFlags.None;
this.parent = undefined;
this.parent = undefined!;
this.original = undefined;
}
@@ -3155,7 +3220,7 @@ namespace ts {
}
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
assert(value !== undefined && value !== null, message);
if (value === undefined || value === null) return fail(message);
return value;
}
@@ -3190,7 +3255,7 @@ namespace ts {
}
function showFlags(flags: number, flagsEnum: { [flag: number]: string }): string {
const out = [];
const out: string[] = [];
for (let pow = 0; pow <= 30; pow++) {
const n = 1 << pow;
if (flags & n) {
@@ -3341,10 +3406,7 @@ namespace ts {
*/
export function extensionFromPath(path: string): Extension {
const ext = tryGetExtensionFromPath(path);
if (ext !== undefined) {
return ext;
}
Debug.fail(`File ${path} has unknown extension.`);
return ext !== undefined ? ext : Debug.fail(`File ${path} has unknown extension.`);
}
export function isAnySupportedFileExtension(path: string): boolean {
+29 -2
View File
@@ -2238,7 +2238,8 @@
},
"Left side of comma operator is unused and has no side effects.": {
"category": "Error",
"code": 2695
"code": 2695,
"reportsUnnecessary": true
},
"The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?": {
"category": "Error",
@@ -3556,6 +3557,11 @@
"code": 6198,
"reportsUnnecessary": true
},
"All variables are unused.": {
"category": "Error",
"code": 6199,
"reportsUnnecessary": true
},
"Projects to reference": {
"category": "Message",
@@ -3713,7 +3719,8 @@
},
"Unreachable code detected.": {
"category": "Error",
"code": 7027
"code": 7027,
"reportsUnnecessary": true
},
"Unused label.": {
"category": "Error",
@@ -4039,6 +4046,10 @@
"category": "Message",
"code": 90009
},
"Remove variable statement": {
"category": "Message",
"code": 90010
},
"Import '{0}' from module \"{1}\"": {
"category": "Message",
"code": 90013
@@ -4302,5 +4313,21 @@
"Remove all unreachable code": {
"category": "Message",
"code": 95051
},
"Add missing 'typeof'": {
"category": "Message",
"code": 95052
},
"Remove unused label": {
"category": "Message",
"code": 95053
},
"Remove all unused labels": {
"category": "Message",
"code": 95054
},
"Convert '{0}' to mapped object type": {
"category": "Message",
"code": 95055
}
}
+63 -61
View File
@@ -15,7 +15,7 @@ namespace ts {
export function forEachEmittedFile<T>(
host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) => T,
sourceFilesOrTargetSourceFile?: ReadonlyArray<SourceFile> | SourceFile,
emitOnlyDtsFiles?: boolean) {
emitOnlyDtsFiles = false) {
const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
const options = host.getCompilerOptions();
if (options.outFile || options.out) {
@@ -38,14 +38,14 @@ namespace ts {
}
/*@internal*/
export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean) {
export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames {
const options = host.getCompilerOptions();
if (sourceFile.kind === SyntaxKind.Bundle) {
const jsFilePath = options.outFile || options.out;
const jsFilePath = options.outFile || options.out!;
const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
const declarationFilePath = (forceDtsPaths || options.declaration) ? removeFileExtension(jsFilePath) + Extension.Dts : undefined;
const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
const bundleInfoPath = options.references && jsFilePath && (removeFileExtension(jsFilePath) + infoExtension);
const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined;
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath };
}
else {
@@ -97,8 +97,8 @@ namespace ts {
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory<Bundle | SourceFile>[], declarationTransformers?: TransformerFactory<Bundle | SourceFile>[]): EmitResult {
const compilerOptions = host.getCompilerOptions();
const sourceMapDataList: SourceMapData[] = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
const emittedFilesList: string[] = compilerOptions.listEmittedFiles ? [] : undefined;
const sourceMapDataList: SourceMapData[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
const emittedFilesList: string[] | undefined = compilerOptions.listEmittedFiles ? [] : undefined;
const emitterDiagnostics = createDiagnosticCollection();
const newLine = host.getNewLine();
const writer = createTextWriter(newLine);
@@ -124,7 +124,7 @@ namespace ts {
emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
sourceMaps: sourceMapDataList,
};
function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) {
@@ -147,7 +147,7 @@ namespace ts {
}
}
function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string, bundleInfoPath: string | undefined) {
function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) {
// Make sure not to write js file and source map file if any of them cannot be written
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
emitSkipped = true;
@@ -157,7 +157,7 @@ namespace ts {
return;
}
// Transform the source files
const transform = transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
const transform = transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers!, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
const printer = createPrinter({ ...compilerOptions, noEmitHelpers: compilerOptions.noEmitHelpers } as PrinterOptions, {
@@ -194,7 +194,7 @@ namespace ts {
const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
const declarationTransform = transformNodes(resolver, host, compilerOptions, inputListOrBundle, concatenate([transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
if (length(declarationTransform.diagnostics)) {
for (const diagnostic of declarationTransform.diagnostics) {
for (const diagnostic of declarationTransform.diagnostics!) {
emitterDiagnostics.add(diagnostic);
}
}
@@ -224,14 +224,14 @@ namespace ts {
function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, bundleInfoPath: string | undefined, printer: Printer, mapRecorder: SourceMapWriter) {
const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined;
const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined;
const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile!];
mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
if (bundle) {
printer.writeBundle(bundle, writer, bundleInfo);
}
else {
printer.writeFile(sourceFile, writer);
printer.writeFile(sourceFile!, writer);
}
writer.writeLine();
@@ -247,7 +247,7 @@ namespace ts {
}
// Write the output file
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
// Write bundled offset information if applicable
if (bundleInfoPath) {
@@ -302,7 +302,7 @@ namespace ts {
emitLeadingCommentsOfPosition,
} = comments;
let currentSourceFile: SourceFile | undefined;
let currentSourceFile!: SourceFile;
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
let generatedNames: Map<true>; // Set of names generated by the NameGenerator.
@@ -478,8 +478,8 @@ namespace ts {
}
function setWriter(output: EmitTextWriter | undefined) {
writer = output;
comments.setWriter(output);
writer = output!; // TODO: GH#18217
comments.setWriter(output!);
}
function reset() {
@@ -544,8 +544,7 @@ namespace ts {
}
function pipelineEmitWithNotification(hint: EmitHint, node: Node) {
Debug.assertDefined(onEmitNode);
onEmitNode(hint, node, getNextPipelinePhase(PipelinePhase.Notification, hint));
Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(PipelinePhase.Notification, hint));
}
function pipelineEmitWithComments(hint: EmitHint, node: Node) {
@@ -560,9 +559,8 @@ namespace ts {
}
function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) {
Debug.assertDefined(onEmitSourceMapOfNode);
Debug.assert(hint !== EmitHint.SourceFile && hint !== EmitHint.IdentifierName);
onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint);
}
function pipelineEmitWithHint(hint: EmitHint, node: Node): void {
@@ -1503,7 +1501,7 @@ namespace ts {
// check if numeric literal is a decimal literal that was originally written with a dot
const text = getLiteralTextOfNode(<LiteralExpression>expression);
return !expression.numericLiteralFlags
&& !stringContains(text, tokenToString(SyntaxKind.DotToken));
&& !stringContains(text, tokenToString(SyntaxKind.DotToken)!);
}
else if (isPropertyAccessExpression(expression) || isElementAccessExpression(expression)) {
// check if constant enum value is integer
@@ -1841,7 +1839,7 @@ namespace ts {
emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node: VariableDeclarationList | Expression) {
function emitForBinding(node: VariableDeclarationList | Expression | undefined) {
if (node !== undefined) {
if (node.kind === SyntaxKind.VariableDeclarationList) {
emit(node);
@@ -1973,7 +1971,7 @@ namespace ts {
writeKeyword("function");
emit(node.asteriskToken);
writeSpace();
emitIdentifierName(node.name);
emitIdentifierName(node.name!); // TODO: GH#18217
emitSignatureAndBody(node, emitSignatureHead);
}
@@ -2052,7 +2050,7 @@ namespace ts {
return false;
}
let previousStatement: Statement;
let previousStatement: Statement | undefined;
for (const statement of body.statements) {
if (shouldWriteSeparatingLineTerminator(previousStatement, statement, ListFormat.PreserveLines)) {
return false;
@@ -2189,7 +2187,7 @@ namespace ts {
while (body.kind === SyntaxKind.ModuleDeclaration) {
writePunctuation(".");
emit((<ModuleDeclaration>body).name);
body = (<ModuleDeclaration>body).body;
body = (<ModuleDeclaration>body).body!;
}
writeSpace();
@@ -2406,7 +2404,7 @@ namespace ts {
function emitJsxAttribute(node: JsxAttribute) {
emit(node.name);
emitNodeWithPrefix("=", writePunctuation, node.initializer, emit);
emitNodeWithPrefix("=", writePunctuation, node.initializer!, emit); // TODO: GH#18217
}
function emitJsxSpreadAttribute(node: JsxSpreadAttribute) {
@@ -2562,7 +2560,7 @@ namespace ts {
}
function emitSyntheticTripleSlashReferencesIfNeeded(node: Bundle) {
emitTripleSlashDirectives(node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []);
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []);
}
function emitTripleSlashDirectivesIfNeeded(node: SourceFile) {
@@ -2693,7 +2691,7 @@ namespace ts {
write = savedWrite;
}
function emitModifiers(node: Node, modifiers: NodeArray<Modifier>) {
function emitModifiers(node: Node, modifiers: NodeArray<Modifier> | undefined) {
if (modifiers && modifiers.length) {
emitList(node, modifiers, ListFormat.Modifiers);
writeSpace();
@@ -2758,15 +2756,15 @@ namespace ts {
}
}
function emitDecorators(parentNode: Node, decorators: NodeArray<Decorator>) {
function emitDecorators(parentNode: Node, decorators: NodeArray<Decorator> | undefined) {
emitList(parentNode, decorators, ListFormat.Decorators);
}
function emitTypeArguments(parentNode: Node, typeArguments: NodeArray<TypeNode>) {
function emitTypeArguments(parentNode: Node, typeArguments: NodeArray<TypeNode> | undefined) {
emitList(parentNode, typeArguments, ListFormat.TypeArguments);
}
function emitTypeParameters(parentNode: SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | ClassExpression, typeParameters: NodeArray<TypeParameterDeclaration>) {
function emitTypeParameters(parentNode: SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | ClassExpression, typeParameters: NodeArray<TypeParameterDeclaration> | undefined) {
if (isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
return emitTypeArguments(parentNode, parentNode.typeArguments);
}
@@ -2807,12 +2805,12 @@ namespace ts {
emitList(parentNode, parameters, ListFormat.IndexSignatureParameters);
}
function emitList(parentNode: TextRange, children: NodeArray<Node>, format: ListFormat, start?: number, count?: number) {
function emitList(parentNode: TextRange, children: NodeArray<Node> | undefined, format: ListFormat, start?: number, count?: number) {
emitNodeList(emit, parentNode, children, format, start, count);
}
function emitExpressionList(parentNode: TextRange, children: NodeArray<Node>, format: ListFormat, start?: number, count?: number) {
emitNodeList(emitExpression, parentNode, children, format, start, count);
function emitExpressionList(parentNode: TextRange, children: NodeArray<Node> | undefined, format: ListFormat, start?: number, count?: number) {
emitNodeList(emitExpression as (node: Node) => void, parentNode, children, format, start, count); // TODO: GH#18217
}
function writeDelimiter(format: ListFormat) {
@@ -2833,13 +2831,13 @@ namespace ts {
}
}
function emitNodeList(emit: (node: Node) => void, parentNode: TextRange, children: NodeArray<Node>, format: ListFormat, start = 0, count = children ? children.length - start : 0) {
function emitNodeList(emit: (node: Node) => void, parentNode: TextRange, children: NodeArray<Node> | undefined, format: ListFormat, start = 0, count = children ? children.length - start : 0) {
const isUndefined = children === undefined;
if (isUndefined && format & ListFormat.OptionalIfUndefined) {
return;
}
const isEmpty = isUndefined || start >= children.length || count === 0;
const isEmpty = children === undefined || start >= children.length || count === 0;
if (isEmpty && format & ListFormat.OptionalIfEmpty) {
if (onBeforeEmitNodeArray) {
onBeforeEmitNodeArray(children);
@@ -2853,7 +2851,8 @@ namespace ts {
if (format & ListFormat.BracketsMask) {
writePunctuation(getOpeningBracket(format));
if (isEmpty && !isUndefined) {
emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
// TODO: GH#18217
emitTrailingCommentsOfPosition(children!.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
}
}
@@ -2874,7 +2873,7 @@ namespace ts {
// Write the opening line terminator or leading whitespace.
const mayEmitInterveningComments = (format & ListFormat.NoInterveningComments) === 0;
let shouldEmitInterveningComments = mayEmitInterveningComments;
if (shouldWriteLeadingLineTerminator(parentNode, children, format)) {
if (shouldWriteLeadingLineTerminator(parentNode, children!, format)) { // TODO: GH#18217
writeLine();
shouldEmitInterveningComments = false;
}
@@ -2888,10 +2887,10 @@ namespace ts {
}
// Emit each child.
let previousSibling: Node;
let shouldDecreaseIndentAfterEmit: boolean;
let previousSibling: Node | undefined;
let shouldDecreaseIndentAfterEmit = false;
for (let i = 0; i < count; i++) {
const child = children[start + i];
const child = children![start + i];
// Write the delimiter if this is not the first node.
if (previousSibling) {
@@ -2945,7 +2944,7 @@ namespace ts {
}
// Write a trailing comma, if requested.
const hasTrailingComma = (format & ListFormat.AllowTrailingComma) && children.hasTrailingComma;
const hasTrailingComma = (format & ListFormat.AllowTrailingComma) && children!.hasTrailingComma;
if (format & ListFormat.CommaDelimited && hasTrailingComma) {
writePunctuation(",");
}
@@ -2967,7 +2966,7 @@ namespace ts {
}
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
if (shouldWriteClosingLineTerminator(parentNode, children!, format)) {
writeLine();
}
else if (format & ListFormat.SpaceBetweenBraces) {
@@ -2981,7 +2980,8 @@ namespace ts {
if (format & ListFormat.BracketsMask) {
if (isEmpty && !isUndefined) {
emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
// TODO: GH#18217
emitLeadingCommentsOfPosition(children!.end); // Emit leading comments within empty lists
}
writePunctuation(getClosingBracket(format));
}
@@ -3077,16 +3077,18 @@ namespace ts {
if (onBeforeEmitToken) {
onBeforeEmitToken(node);
}
writer(tokenToString(node.kind));
writer(tokenToString(node.kind)!);
if (onAfterEmitToken) {
onAfterEmitToken(node);
}
}
function writeTokenText(token: SyntaxKind, writer: (s: string) => void, pos?: number) {
const tokenString = tokenToString(token);
function writeTokenText(token: SyntaxKind, writer: (s: string) => void): void;
function writeTokenText(token: SyntaxKind, writer: (s: string) => void, pos: number): number;
function writeTokenText(token: SyntaxKind, writer: (s: string) => void, pos?: number): number {
const tokenString = tokenToString(token)!;
writer(tokenString);
return pos < 0 ? pos : pos + tokenString.length;
return pos! < 0 ? pos! : pos! + tokenString.length;
}
function writeLineOrSpace(node: Node) {
@@ -3160,7 +3162,7 @@ namespace ts {
}
}
function shouldWriteSeparatingLineTerminator(previousNode: Node, nextNode: Node, format: ListFormat) {
function shouldWriteSeparatingLineTerminator(previousNode: Node | undefined, nextNode: Node, format: ListFormat) {
if (format & ListFormat.MultiLine) {
return true;
}
@@ -3205,7 +3207,7 @@ namespace ts {
}
}
function synthesizedNodeStartsOnNewLine(node: Node, format?: ListFormat) {
function synthesizedNodeStartsOnNewLine(node: Node, format: ListFormat) {
if (nodeIsSynthesized(node)) {
const startsOnNewLine = getStartsOnNewLine(node);
if (startsOnNewLine === undefined) {
@@ -3255,7 +3257,7 @@ namespace ts {
return idText(node);
}
else if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
return getTextOfNode((<StringLiteral>node).textSourceNode, includeTrivia);
return getTextOfNode((<StringLiteral>node).textSourceNode!, includeTrivia);
}
else if (isLiteralExpression(node) && (nodeIsSynthesized(node) || !node.parent)) {
return node.text;
@@ -3266,7 +3268,7 @@ namespace ts {
function getLiteralTextOfNode(node: LiteralLikeNode): string {
if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
const textSourceNode = (<StringLiteral>node).textSourceNode;
const textSourceNode = (<StringLiteral>node).textSourceNode!;
if (isIdentifier(textSourceNode)) {
return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ?
`"${escapeString(getTextOfNode(textSourceNode))}"` :
@@ -3299,8 +3301,8 @@ namespace ts {
if (node && getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
return;
}
tempFlags = tempFlagsStack.pop();
reservedNames = reservedNamesStack.pop();
tempFlags = tempFlagsStack.pop()!;
reservedNames = reservedNamesStack.pop()!;
}
function reserveNameInNestedScopes(name: string) {
@@ -3430,7 +3432,7 @@ namespace ts {
else {
// Auto, Loop, and Unique names are cached based on their unique
// autoGenerateId.
const autoGenerateId = name.autoGenerateId;
const autoGenerateId = name.autoGenerateId!;
return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
}
}
@@ -3461,7 +3463,7 @@ namespace ts {
* Returns a value indicating whether a name is unique within a container.
*/
function isUniqueLocalName(name: string, container: Node): boolean {
for (let node = container; isNodeDescendantOf(node, container); node = node.nextContainer) {
for (let node = container; isNodeDescendantOf(node, container); node = node.nextContainer!) {
if (node.locals) {
const local = node.locals.get(escapeLeadingUnderscores(name));
// We conservatively include alias symbols to cover cases where they're emitted as locals
@@ -3563,7 +3565,7 @@ namespace ts {
* Generates a unique name for an ImportDeclaration or ExportDeclaration.
*/
function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) {
const expr = getExternalModuleName(node);
const expr = getExternalModuleName(node)!; // TODO: GH#18217
const baseName = isStringLiteral(expr) ?
makeIdentifierFromModuleName(expr.text) : "module";
return makeUniqueName(baseName);
@@ -3599,8 +3601,8 @@ namespace ts {
return makeUniqueName(
getTextOfNode(node),
isUniqueName,
!!(flags & GeneratedIdentifierFlags.Optimistic),
!!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes)
!!(flags! & GeneratedIdentifierFlags.Optimistic),
!!(flags! & GeneratedIdentifierFlags.ReservedInNestedScopes)
);
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
@@ -3641,7 +3643,7 @@ namespace ts {
);
}
Debug.fail("Unsupported GeneratedIdentifierKind.");
return Debug.fail("Unsupported GeneratedIdentifierKind.");
}
/**
@@ -3657,7 +3659,7 @@ namespace ts {
// if "node" is a different generated name (having a different
// "autoGenerateId"), use it and stop traversing.
if (isIdentifier(node)
&& !!(node.autoGenerateFlags & GeneratedIdentifierFlags.Node)
&& !!(node.autoGenerateFlags! & GeneratedIdentifierFlags.Node)
&& node.autoGenerateId !== autoGenerateId) {
break;
}
+96 -84
View File
@@ -39,13 +39,13 @@ namespace ts {
* Creates a shallow, memberwise clone of a node with no source map location.
*/
/* @internal */
export function getSynthesizedClone<T extends Node>(node: T | undefined): T | undefined {
export function getSynthesizedClone<T extends Node>(node: T): T {
// We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
// the original node. We also need to exclude specific properties and only include own-
// properties (to skip members already defined on the shared prototype).
if (node === undefined) {
return undefined;
return node;
}
const clone = <T>createSynthesizedNode(node.kind);
@@ -116,7 +116,7 @@ namespace ts {
export function createIdentifier(text: string): Identifier;
/* @internal */
export function createIdentifier(text: string, typeArguments: ReadonlyArray<TypeNode | TypeParameterDeclaration>): Identifier; // tslint:disable-line unified-signatures
export function createIdentifier(text: string, typeArguments: ReadonlyArray<TypeNode | TypeParameterDeclaration> | undefined): Identifier; // tslint:disable-line unified-signatures
export function createIdentifier(text: string, typeArguments?: ReadonlyArray<TypeNode | TypeParameterDeclaration>): Identifier {
const node = <Identifier>createSynthesizedNode(SyntaxKind.Identifier);
node.escapedText = escapeLeadingUnderscores(text);
@@ -142,9 +142,9 @@ namespace ts {
/** Create a unique temporary variable. */
export function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier;
/* @internal */ export function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes: boolean): Identifier; // tslint:disable-line unified-signatures
export function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier {
const name = createIdentifier("");
/* @internal */ export function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes: boolean): GeneratedIdentifier; // tslint:disable-line unified-signatures
export function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): GeneratedIdentifier {
const name = createIdentifier("") as GeneratedIdentifier;
name.autoGenerateFlags = GeneratedIdentifierFlags.Auto;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
@@ -175,9 +175,11 @@ namespace ts {
return name;
}
/* @internal */ export function createOptimisticUniqueName(text: string): GeneratedIdentifier;
/** Create a unique name based on the supplied text. */
export function createOptimisticUniqueName(text: string): Identifier {
const name = createIdentifier(text);
export function createOptimisticUniqueName(text: string): Identifier;
export function createOptimisticUniqueName(text: string): GeneratedIdentifier {
const name = createIdentifier(text) as GeneratedIdentifier;
name.autoGenerateFlags = GeneratedIdentifierFlags.Unique | GeneratedIdentifierFlags.Optimistic;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
@@ -196,7 +198,7 @@ namespace ts {
/* @internal */ export function getGeneratedNameForNode(node: Node, flags: GeneratedIdentifierFlags): Identifier; // tslint:disable-line unified-signatures
export function getGeneratedNameForNode(node: Node, flags?: GeneratedIdentifierFlags): Identifier {
const name = createIdentifier(isIdentifier(node) ? idText(node) : "");
name.autoGenerateFlags = GeneratedIdentifierFlags.Node | flags;
name.autoGenerateFlags = GeneratedIdentifierFlags.Node | flags!;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
nextAutoGenerateId++;
@@ -713,7 +715,7 @@ namespace ts {
: node;
}
export function createTypeLiteralNode(members: ReadonlyArray<TypeElement>) {
export function createTypeLiteralNode(members: ReadonlyArray<TypeElement> | undefined) {
const node = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode;
node.members = createNodeArray(members);
return node;
@@ -846,7 +848,7 @@ namespace ts {
export function createTypeOperatorNode(operatorOrType: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | TypeNode, type?: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
node.operator = typeof operatorOrType === "number" ? operatorOrType : SyntaxKind.KeyOfKeyword;
node.type = parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
node.type = parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type! : operatorOrType);
return node;
}
@@ -970,10 +972,10 @@ namespace ts {
: node;
}
export function createPropertyAccess(expression: Expression, name: string | Identifier) {
export function createPropertyAccess(expression: Expression, name: string | Identifier | undefined) {
const node = <PropertyAccessExpression>createSynthesizedNode(SyntaxKind.PropertyAccessExpression);
node.expression = parenthesizeForAccess(expression);
node.name = asName(name);
node.name = asName(name)!; // TODO: GH#18217
setEmitFlags(node, EmitFlags.NoIndentation);
return node;
}
@@ -1001,7 +1003,7 @@ namespace ts {
: node;
}
export function createCall(expression: Expression, typeArguments: ReadonlyArray<TypeNode> | undefined, argumentsArray: ReadonlyArray<Expression>) {
export function createCall(expression: Expression, typeArguments: ReadonlyArray<TypeNode> | undefined, argumentsArray: ReadonlyArray<Expression> | undefined) {
const node = <CallExpression>createSynthesizedNode(SyntaxKind.CallExpression);
node.expression = parenthesizeForAccess(expression);
node.typeArguments = asNodeArray(typeArguments);
@@ -1034,15 +1036,15 @@ namespace ts {
}
export function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression;
export function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray<TypeNode>, template: TemplateLiteral): TaggedTemplateExpression;
export function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray<TypeNode> | undefined, template: TemplateLiteral): TaggedTemplateExpression;
/** @internal */
export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral, template?: TemplateLiteral): TaggedTemplateExpression;
export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral, template?: TemplateLiteral) {
export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral | undefined, template?: TemplateLiteral): TaggedTemplateExpression;
export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral | undefined, template?: TemplateLiteral) {
const node = <TaggedTemplateExpression>createSynthesizedNode(SyntaxKind.TaggedTemplateExpression);
node.tag = parenthesizeForAccess(tag);
if (template) {
node.typeArguments = asNodeArray(typeArgumentsOrTemplate as ReadonlyArray<TypeNode>);
node.template = template!;
node.template = template;
}
else {
node.typeArguments = undefined;
@@ -1052,8 +1054,8 @@ namespace ts {
}
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression;
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray<TypeNode>, template: TemplateLiteral): TaggedTemplateExpression;
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral, template?: TemplateLiteral) {
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray<TypeNode> | undefined, template: TemplateLiteral): TaggedTemplateExpression;
export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArgumentsOrTemplate: ReadonlyArray<TypeNode> | TemplateLiteral | undefined, template?: TemplateLiteral) {
return node.tag !== tag
|| (template
? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
@@ -1093,7 +1095,7 @@ namespace ts {
asteriskToken: AsteriskToken | undefined,
name: string | Identifier | undefined,
typeParameters: ReadonlyArray<TypeParameterDeclaration> | undefined,
parameters: ReadonlyArray<ParameterDeclaration>,
parameters: ReadonlyArray<ParameterDeclaration> | undefined,
type: TypeNode | undefined,
body: Block) {
const node = <FunctionExpression>createSynthesizedNode(SyntaxKind.FunctionExpression);
@@ -1288,7 +1290,7 @@ namespace ts {
node.condition = parenthesizeForConditionalHead(condition);
node.questionToken = whenFalse ? <QuestionToken>questionTokenOrWhenTrue : createToken(SyntaxKind.QuestionToken);
node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : <Expression>questionTokenOrWhenTrue);
node.colonToken = whenFalse ? colonToken : createToken(SyntaxKind.ColonToken);
node.colonToken = whenFalse ? colonToken! : createToken(SyntaxKind.ColonToken);
node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
return node;
}
@@ -1360,8 +1362,8 @@ namespace ts {
}
export function createYield(expression?: Expression): YieldExpression;
export function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression;
export function createYield(asteriskTokenOrExpression?: AsteriskToken | Expression, expression?: Expression) {
export function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression;
export function createYield(asteriskTokenOrExpression?: AsteriskToken | undefined | Expression, expression?: Expression) {
const node = <YieldExpression>createSynthesizedNode(SyntaxKind.YieldExpression);
node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === SyntaxKind.AsteriskToken ? <AsteriskToken>asteriskTokenOrExpression : undefined;
node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== SyntaxKind.AsteriskToken ? asteriskTokenOrExpression : expression;
@@ -1391,7 +1393,7 @@ namespace ts {
modifiers: ReadonlyArray<Modifier> | undefined,
name: string | Identifier | undefined,
typeParameters: ReadonlyArray<TypeParameterDeclaration> | undefined,
heritageClauses: ReadonlyArray<HeritageClause>,
heritageClauses: ReadonlyArray<HeritageClause> | undefined,
members: ReadonlyArray<ClassElement>) {
const node = <ClassExpression>createSynthesizedNode(SyntaxKind.ClassExpression);
node.decorators = undefined;
@@ -1408,7 +1410,7 @@ namespace ts {
modifiers: ReadonlyArray<Modifier> | undefined,
name: Identifier | undefined,
typeParameters: ReadonlyArray<TypeParameterDeclaration> | undefined,
heritageClauses: ReadonlyArray<HeritageClause>,
heritageClauses: ReadonlyArray<HeritageClause> | undefined,
members: ReadonlyArray<ClassElement>) {
return node.modifiers !== modifiers
|| node.name !== name
@@ -1423,14 +1425,14 @@ namespace ts {
return <OmittedExpression>createSynthesizedNode(SyntaxKind.OmittedExpression);
}
export function createExpressionWithTypeArguments(typeArguments: ReadonlyArray<TypeNode>, expression: Expression) {
export function createExpressionWithTypeArguments(typeArguments: ReadonlyArray<TypeNode> | undefined, expression: Expression) {
const node = <ExpressionWithTypeArguments>createSynthesizedNode(SyntaxKind.ExpressionWithTypeArguments);
node.expression = parenthesizeForAccess(expression);
node.typeArguments = asNodeArray(typeArguments);
return node;
}
export function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray<TypeNode>, expression: Expression) {
export function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray<TypeNode> | undefined, expression: Expression) {
return node.typeArguments !== typeArguments
|| node.expression !== expression
? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
@@ -1625,7 +1627,7 @@ namespace ts {
: node;
}
export function createForOf(awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement) {
export function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement) {
const node = <ForOfStatement>createSynthesizedNode(SyntaxKind.ForOfStatement);
node.awaitModifier = awaitModifier;
node.initializer = initializer;
@@ -1634,7 +1636,7 @@ namespace ts {
return node;
}
export function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement) {
export function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement) {
return node.awaitModifier !== awaitModifier
|| node.initializer !== initializer
|| node.expression !== expression
@@ -1769,7 +1771,7 @@ namespace ts {
: node;
}
export function createVariableDeclarationList(declarations: ReadonlyArray<VariableDeclaration>, flags?: NodeFlags) {
export function createVariableDeclarationList(declarations: ReadonlyArray<VariableDeclaration>, flags = NodeFlags.None) {
const node = <VariableDeclarationList>createSynthesizedNode(SyntaxKind.VariableDeclarationList);
node.flags |= flags & NodeFlags.BlockScoped;
node.declarations = createNodeArray(declarations);
@@ -1830,7 +1832,7 @@ namespace ts {
modifiers: ReadonlyArray<Modifier> | undefined,
name: string | Identifier | undefined,
typeParameters: ReadonlyArray<TypeParameterDeclaration> | undefined,
heritageClauses: ReadonlyArray<HeritageClause>,
heritageClauses: ReadonlyArray<HeritageClause> | undefined,
members: ReadonlyArray<ClassElement>) {
const node = <ClassDeclaration>createSynthesizedNode(SyntaxKind.ClassDeclaration);
node.decorators = asNodeArray(decorators);
@@ -1848,7 +1850,7 @@ namespace ts {
modifiers: ReadonlyArray<Modifier> | undefined,
name: Identifier | undefined,
typeParameters: ReadonlyArray<TypeParameterDeclaration> | undefined,
heritageClauses: ReadonlyArray<HeritageClause>,
heritageClauses: ReadonlyArray<HeritageClause> | undefined,
members: ReadonlyArray<ClassElement>) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
@@ -1953,7 +1955,7 @@ namespace ts {
: node;
}
export function createModuleDeclaration(decorators: ReadonlyArray<Decorator> | undefined, modifiers: ReadonlyArray<Modifier> | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags) {
export function createModuleDeclaration(decorators: ReadonlyArray<Decorator> | undefined, modifiers: ReadonlyArray<Modifier> | undefined, name: ModuleName, body: ModuleBody | undefined, flags = NodeFlags.None) {
const node = <ModuleDeclaration>createSynthesizedNode(SyntaxKind.ModuleDeclaration);
node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation);
node.decorators = asNodeArray(decorators);
@@ -2044,7 +2046,7 @@ namespace ts {
decorators: ReadonlyArray<Decorator> | undefined,
modifiers: ReadonlyArray<Modifier> | undefined,
importClause: ImportClause | undefined,
moduleSpecifier: Expression | undefined) {
moduleSpecifier: Expression) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.importClause !== importClause
@@ -2105,7 +2107,7 @@ namespace ts {
: node;
}
export function createExportAssignment(decorators: ReadonlyArray<Decorator> | undefined, modifiers: ReadonlyArray<Modifier> | undefined, isExportEquals: boolean, expression: Expression) {
export function createExportAssignment(decorators: ReadonlyArray<Decorator> | undefined, modifiers: ReadonlyArray<Modifier> | undefined, isExportEquals: boolean | undefined, expression: Expression) {
const node = <ExportAssignment>createSynthesizedNode(SyntaxKind.ExportAssignment);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
@@ -2402,7 +2404,7 @@ namespace ts {
export function createSpreadAssignment(expression: Expression) {
const node = <SpreadAssignment>createSynthesizedNode(SyntaxKind.SpreadAssignment);
node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined;
node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined!; // TODO: GH#18217
return node;
}
@@ -2463,6 +2465,7 @@ namespace ts {
if (node.symbolCount !== undefined) updated.symbolCount = node.symbolCount;
if (node.parseDiagnostics !== undefined) updated.parseDiagnostics = node.parseDiagnostics;
if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics;
if (node.bindSuggestionDiagnostics !== undefined) updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
if (node.lineMap !== undefined) updated.lineMap = node.lineMap;
if (node.classifiableNames !== undefined) updated.classifiableNames = node.classifiableNames;
if (node.resolvedModules !== undefined) updated.resolvedModules = node.resolvedModules;
@@ -2511,7 +2514,7 @@ namespace ts {
/* @internal */
export function createEndOfDeclarationMarker(original: Node) {
const node = <EndOfDeclarationMarker>createSynthesizedNode(SyntaxKind.EndOfDeclarationMarker);
node.emitNode = {};
node.emitNode = {} as EmitNode;
node.original = original;
return node;
}
@@ -2523,7 +2526,7 @@ namespace ts {
/* @internal */
export function createMergeDeclarationMarker(original: Node) {
const node = <MergeDeclarationMarker>createSynthesizedNode(SyntaxKind.MergeDeclarationMarker);
node.emitNode = {};
node.emitNode = {} as EmitNode;
node.original = original;
return node;
}
@@ -2700,12 +2703,7 @@ namespace ts {
// Utilities
function asName(name: string | Identifier): Identifier;
function asName(name: string | BindingName): BindingName;
function asName(name: string | PropertyName): PropertyName;
function asName(name: string | EntityName): EntityName;
function asName(name: string | Identifier | ThisTypeNode): Identifier | ThisTypeNode;
function asName(name: string | Identifier | BindingName | PropertyName | QualifiedName | ThisTypeNode) {
function asName<T extends Identifier | BindingName | PropertyName | EntityName | ThisTypeNode | undefined>(name: string | T): T | Identifier {
return isString(name) ? createIdentifier(name) : name;
}
@@ -2713,6 +2711,8 @@ namespace ts {
return isString(value) || typeof value === "number" ? createLiteral(value) : value;
}
function asNodeArray<T extends Node>(array: ReadonlyArray<T>): NodeArray<T>;
function asNodeArray<T extends Node>(array: ReadonlyArray<T> | undefined): NodeArray<T> | undefined;
function asNodeArray<T extends Node>(array: ReadonlyArray<T> | undefined): NodeArray<T> | undefined {
return array ? createNodeArray(array) : undefined;
}
@@ -2747,21 +2747,21 @@ namespace ts {
* various transient transformation properties.
*/
/* @internal */
export function getOrCreateEmitNode(node: Node) {
export function getOrCreateEmitNode(node: Node): EmitNode {
if (!node.emitNode) {
if (isParseTreeNode(node)) {
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
if (node.kind === SyntaxKind.SourceFile) {
return node.emitNode = { annotatedNodes: [node] };
return node.emitNode = { annotatedNodes: [node] } as EmitNode;
}
const sourceFile = getSourceFileOfNode(node);
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
getOrCreateEmitNode(sourceFile).annotatedNodes!.push(node);
}
node.emitNode = {};
node.emitNode = {} as EmitNode;
}
return node.emitNode;
@@ -2877,7 +2877,7 @@ namespace ts {
return emitNode && emitNode.leadingComments;
}
export function setSyntheticLeadingComments<T extends Node>(node: T, comments: SynthesizedComment[]) {
export function setSyntheticLeadingComments<T extends Node>(node: T, comments: SynthesizedComment[] | undefined) {
getOrCreateEmitNode(node).leadingComments = comments;
return node;
}
@@ -2891,7 +2891,7 @@ namespace ts {
return emitNode && emitNode.trailingComments;
}
export function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]) {
export function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[] | undefined) {
getOrCreateEmitNode(node).trailingComments = comments;
return node;
}
@@ -2900,10 +2900,19 @@ namespace ts {
return setSyntheticTrailingComments(node, append<SynthesizedComment>(getSyntheticTrailingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text }));
}
export function moveSyntheticComments<T extends Node>(node: T, original: Node): T {
setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
const emit = getOrCreateEmitNode(original);
emit.leadingComments = undefined;
emit.trailingComments = undefined;
return node;
}
/**
* Gets the constant value to emit for an expression.
*/
export function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression) {
export function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined {
const emitNode = node.emitNode;
return emitNode && emitNode.constantValue;
}
@@ -3005,7 +3014,7 @@ namespace ts {
return node;
}
function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode) {
function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefined) {
const {
flags,
leadingComments,
@@ -3017,21 +3026,21 @@ namespace ts {
helpers,
startsOnNewLine,
} = sourceEmitNode;
if (!destEmitNode) destEmitNode = {};
if (!destEmitNode) destEmitNode = {} as EmitNode;
// We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments);
if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments);
if (flags) destEmitNode.flags = flags;
if (commentRange) destEmitNode.commentRange = commentRange;
if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange;
if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!);
if (constantValue !== undefined) destEmitNode.constantValue = constantValue;
if (helpers) destEmitNode.helpers = addRange(destEmitNode.helpers, helpers);
if (startsOnNewLine !== undefined) destEmitNode.startsOnNewLine = startsOnNewLine;
return destEmitNode;
}
function mergeTokenSourceMapRanges(sourceRanges: TextRange[], destRanges: TextRange[]) {
function mergeTokenSourceMapRanges(sourceRanges: (TextRange | undefined)[], destRanges: (TextRange | undefined)[]) {
if (!destRanges) destRanges = [];
for (const key in sourceRanges) {
destRanges[key] = sourceRanges[key];
@@ -3168,7 +3177,7 @@ namespace ts {
}
}
function createJsxFactoryExpression(jsxFactoryEntity: EntityName, reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression {
function createJsxFactoryExpression(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression {
return jsxFactoryEntity ?
createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
createPropertyAccess(
@@ -3177,7 +3186,7 @@ namespace ts {
);
}
export function createExpressionForJsxElement(jsxFactoryEntity: EntityName, reactNamespace: string, tagName: Expression, props: Expression, children: ReadonlyArray<Expression>, parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression {
export function createExpressionForJsxElement(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, tagName: Expression, props: Expression, children: ReadonlyArray<Expression>, parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression {
const argumentsList = [tagName];
if (props) {
argumentsList.push(props);
@@ -3209,7 +3218,7 @@ namespace ts {
);
}
export function createExpressionForJsxFragment(jsxFactoryEntity: EntityName, reactNamespace: string, children: ReadonlyArray<Expression>, parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression {
export function createExpressionForJsxFragment(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, children: ReadonlyArray<Expression>, parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression {
const tagName = createPropertyAccess(
createReactNamespace(reactNamespace, parentElement),
"Fragment"
@@ -3337,7 +3346,7 @@ namespace ts {
export function createForOfBindingStatement(node: ForInitializer, boundValue: Expression): Statement {
if (isVariableDeclarationList(node)) {
const firstDeclaration = firstOrUndefined(node.declarations);
const firstDeclaration = first(node.declarations);
const updatedDeclaration = updateVariableDeclaration(
firstDeclaration,
firstDeclaration.name,
@@ -3367,7 +3376,7 @@ namespace ts {
}
}
export function restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement {
export function restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement | undefined, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement {
if (!outermostLabeledStatement) {
return node;
}
@@ -3411,7 +3420,7 @@ namespace ts {
}
}
export function createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers?: boolean): CallBinding {
export function createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers = false): CallBinding {
const callee = skipOuterExpressions(expression, OuterExpressionKinds.All);
let thisArg: Expression;
let target: LeftHandSideExpression;
@@ -3421,7 +3430,7 @@ namespace ts {
}
else if (callee.kind === SyntaxKind.SuperKeyword) {
thisArg = createThis();
target = languageVersion < ScriptTarget.ES2015
target = languageVersion! < ScriptTarget.ES2015
? setTextRange(createIdentifier("_super"), callee)
: <PrimaryExpression>callee;
}
@@ -3495,7 +3504,7 @@ namespace ts {
// stack size exceeded" errors.
return expressions.length > 10
? createCommaList(expressions)
: reduceLeft(expressions, createComma);
: reduceLeft(expressions, createComma)!;
}
export function createExpressionFromEntityName(node: EntityName | Expression): Expression {
@@ -3521,11 +3530,11 @@ namespace ts {
}
}
export function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression {
export function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression | undefined {
switch (property.kind) {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine);
return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
case SyntaxKind.PropertyAssignment:
return createExpressionForPropertyAssignment(property, receiver);
case SyntaxKind.ShorthandPropertyAssignment:
@@ -3547,7 +3556,7 @@ namespace ts {
/*typeParameters*/ undefined,
getAccessor.parameters,
/*type*/ undefined,
getAccessor.body
getAccessor.body! // TODO: GH#18217
);
setTextRange(getterFunction, getAccessor);
setOriginalNode(getterFunction, getAccessor);
@@ -3563,7 +3572,7 @@ namespace ts {
/*typeParameters*/ undefined,
setAccessor.parameters,
/*type*/ undefined,
setAccessor.body
setAccessor.body! // TODO: GH#18217
);
setTextRange(setterFunction, setAccessor);
setOriginalNode(setterFunction, setAccessor);
@@ -3638,7 +3647,7 @@ namespace ts {
/*typeParameters*/ undefined,
method.parameters,
/*type*/ undefined,
method.body
method.body! // TODO: GH#18217
),
/*location*/ method
),
@@ -3728,7 +3737,7 @@ namespace ts {
return getName(node, allowComments, allowSourceMaps);
}
function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags: EmitFlags = 0) {
const nodeName = getNameOfDeclaration(node);
if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) {
const name = getMutableClone(nodeName);
@@ -3770,7 +3779,7 @@ namespace ts {
export function getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression {
const qualifiedName = createPropertyAccess(ns, nodeIsSynthesized(name) ? name : getSynthesizedClone(name));
setTextRange(qualifiedName, name);
let emitFlags: EmitFlags;
let emitFlags: EmitFlags = 0;
if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap;
if (!allowComments) emitFlags |= EmitFlags.NoComments;
if (emitFlags) setEmitFlags(qualifiedName, emitFlags);
@@ -3782,7 +3791,7 @@ namespace ts {
}
export function convertFunctionDeclarationToExpression(node: FunctionDeclaration) {
Debug.assert(!!node.body);
if (!node.body) return Debug.fail();
const updated = createFunctionExpression(
node.modifiers,
node.asteriskToken,
@@ -3857,9 +3866,11 @@ namespace ts {
* This function needs to be called whenever we transform the statement
* list of a source file, namespace, or function-like body.
*/
export function addCustomPrologue(target: Statement[], source: ReadonlyArray<Statement>, statementOffset: number, visitor?: (node: Node) => VisitResult<Node>): number {
export function addCustomPrologue(target: Statement[], source: ReadonlyArray<Statement>, statementOffset: number, visitor?: (node: Node) => VisitResult<Node>): number;
export function addCustomPrologue(target: Statement[], source: ReadonlyArray<Statement>, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult<Node>): number | undefined;
export function addCustomPrologue(target: Statement[], source: ReadonlyArray<Statement>, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult<Node>): number | undefined {
const numStatements = source.length;
while (statementOffset < numStatements) {
while (statementOffset !== undefined && statementOffset < numStatements) {
const statement = source[statementOffset];
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
append(target, visitor ? visitNode(statement, visitor, isStatement) : statement);
@@ -3941,7 +3952,7 @@ namespace ts {
* @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
* BinaryExpression.
*/
function binaryOperandNeedsParentheses(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand: Expression) {
function binaryOperandNeedsParentheses(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand: Expression | undefined) {
// If the operand has lower precedence, then it needs to be parenthesized to preserve the
// intent of the expression. For example, if the operand is `a + b` and the operator is
// `*`, then we need to parenthesize the operand to preserve the intended order of
@@ -4186,7 +4197,7 @@ namespace ts {
}
export function parenthesizeListElements(elements: NodeArray<Expression>) {
let result: Expression[];
let result: Expression[] | undefined;
for (let i = 0; i < elements.length; i++) {
const element = parenthesizeExpressionForList(elements[i]);
if (result !== undefined || element !== elements[i]) {
@@ -4263,7 +4274,7 @@ namespace ts {
return createNodeArray(sameMap(members, parenthesizeElementTypeMember));
}
export function parenthesizeTypeParameters(typeParameters: ReadonlyArray<TypeNode>) {
export function parenthesizeTypeParameters(typeParameters: ReadonlyArray<TypeNode> | undefined) {
if (some(typeParameters)) {
const params: TypeNode[] = [];
for (let i = 0; i < typeParameters.length; ++i) {
@@ -4465,7 +4476,7 @@ namespace ts {
/**
* Get the name of that target module from an import or export declaration
*/
export function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier {
export function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier | undefined {
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
const name = namespaceDeclaration.name;
@@ -4489,7 +4500,7 @@ namespace ts {
* Otherwise, a new StringLiteral node representing the module name will be returned.
*/
export function getExternalModuleNameLiteral(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) {
const moduleName = getExternalModuleName(importNode);
const moduleName = getExternalModuleName(importNode)!; // TODO: GH#18217
if (moduleName.kind === SyntaxKind.StringLiteral) {
return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
|| tryRenameExternalModule(<StringLiteral>moduleName, sourceFile)
@@ -4515,7 +4526,7 @@ namespace ts {
* 2. --out or --outFile is used, making the name relative to the rootDir
* Otherwise, a new StringLiteral node representing the module name will be returned.
*/
export function tryGetModuleNameFromFile(file: SourceFile, host: EmitHost, options: CompilerOptions): StringLiteral {
export function tryGetModuleNameFromFile(file: SourceFile | undefined, host: EmitHost, options: CompilerOptions): StringLiteral | undefined {
if (!file) {
return undefined;
}
@@ -4551,8 +4562,9 @@ namespace ts {
// `1` in `({ a: b = 1 } = ...)`
// `1` in `({ a: {b} = 1 } = ...)`
// `1` in `({ a: [b] = 1 } = ...)`
return isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true)
? bindingElement.initializer.right
const initializer = bindingElement.initializer;
return isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
? initializer.right
: undefined;
}
@@ -4577,7 +4589,7 @@ namespace ts {
/**
* Gets the name of an BindingOrAssignmentElement.
*/
export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget {
export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget | undefined {
if (isDeclarationBindingElement(bindingElement)) {
// `a` in `let { a } = ...`
// `a` in `let { a = 1 } = ...`
@@ -4652,7 +4664,7 @@ namespace ts {
/**
* Determines whether an BindingOrAssignmentElement is a rest element.
*/
export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator {
export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator | undefined {
switch (bindingElement.kind) {
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
+43 -33
View File
@@ -2,12 +2,12 @@ namespace ts {
/* @internal */
export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
export function trace(host: ModuleResolutionHost): void {
host.trace(formatMessage.apply(undefined, arguments));
host.trace!(formatMessage.apply(undefined, arguments));
}
/* @internal */
export function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return compilerOptions.traceResolution && host.trace !== undefined;
return !!compilerOptions.traceResolution && host.trace !== undefined;
}
/** Array that is only intended to be pushed to, never read. */
@@ -16,11 +16,11 @@ namespace ts {
push(value: T): void;
}
function withPackageId(packageId: PackageId | undefined, r: PathAndExtension | undefined): Resolved {
function withPackageId(packageId: PackageId | undefined, r: PathAndExtension | undefined): Resolved | undefined {
return r && { path: r.path, extension: r.ext, packageId };
}
function noPackageId(r: PathAndExtension | undefined): Resolved {
function noPackageId(r: PathAndExtension | undefined): Resolved | undefined {
return withPackageId(/*packageId*/ undefined, r);
}
@@ -51,7 +51,7 @@ namespace ts {
interface PathAndPackageId {
readonly fileName: string;
readonly packageId: PackageId;
readonly packageId: PackageId | undefined;
}
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved: Resolved | undefined): PathAndPackageId | undefined {
@@ -141,7 +141,7 @@ namespace ts {
return options.typeRoots;
}
let currentDirectory: string;
let currentDirectory: string | undefined;
if (options.configFilePath) {
currentDirectory = getDirectoryPath(options.configFilePath);
}
@@ -164,10 +164,10 @@ namespace ts {
// And if it doesn't exist, tough.
}
let typeRoots: string[];
let typeRoots: string[] | undefined;
forEachAncestorDirectory(normalizePath(currentDirectory), directory => {
const atTypes = combinePaths(directory, nodeModulesAtTypes);
if (host.directoryExists(atTypes)) {
if (host.directoryExists!(atTypes)) {
(typeRoots || (typeRoots = [])).push(atTypes);
}
return undefined;
@@ -254,7 +254,6 @@ namespace ts {
}
function secondaryLookup(): PathAndPackageId | undefined {
let resolvedFile: PathAndPackageId;
const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
if (initialLocationForSecondaryLookup !== undefined) {
@@ -263,7 +262,7 @@ namespace ts {
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
const result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined);
resolvedFile = resolvedTypeScriptOnly(result && result.value);
const resolvedFile = resolvedTypeScriptOnly(result && result.value);
if (!resolvedFile && traceEnabled) {
trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
@@ -334,7 +333,7 @@ namespace ts {
}
export interface PerModuleNameCache {
get(directory: string): ResolvedModuleWithFailedLookupLocations;
get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined;
set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void;
}
@@ -366,9 +365,9 @@ namespace ts {
return perFolderCache;
}
function getOrCreateCacheForModuleName(nonRelativeModuleName: string) {
function getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache {
if (isExternalModuleNameRelative(nonRelativeModuleName)) {
return undefined;
return undefined!; // TODO: GH#18217
}
let perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName);
if (!perModuleNameCache) {
@@ -383,7 +382,7 @@ namespace ts {
return { get, set };
function get(directory: string): ResolvedModuleWithFailedLookupLocations {
function get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined {
return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName));
}
@@ -427,7 +426,7 @@ namespace ts {
}
}
function getCommonPrefix(directory: Path, resolution: string) {
function getCommonPrefix(directory: Path, resolution: string | undefined) {
if (resolution === undefined) {
return undefined;
}
@@ -492,13 +491,13 @@ namespace ts {
result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache);
break;
default:
Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`);
return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`);
}
if (perFolderCache) {
perFolderCache.set(moduleName, result);
// put result in per-module name cache
const perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName);
const perModuleNameCache = cache!.getOrCreateCacheForModuleName(moduleName);
if (perModuleNameCache) {
perModuleNameCache.set(containingDirectory, result);
}
@@ -611,8 +610,8 @@ namespace ts {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let matchedRootDir: string;
let matchedNormalizedPrefix: string;
let matchedRootDir: string | undefined;
let matchedNormalizedPrefix: string | undefined;
for (const rootDir of state.compilerOptions.rootDirs) {
// rootDirs are expected to be absolute
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
@@ -698,9 +697,9 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
}
return forEach(state.compilerOptions.paths[matchedPatternText], subst => {
return forEach(state.compilerOptions.paths![matchedPatternText], subst => {
const path = matchedStar ? subst.replace("*", matchedStar) : subst;
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path));
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl!, path));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
@@ -781,7 +780,7 @@ namespace ts {
let originalPath: string | undefined;
if (!compilerOptions.preserveSymlinks && resolvedValue) {
originalPath = resolvedValue.path;
const path = realPath(resolved.value.path, host, traceEnabled);
const path = realPath(resolvedValue.path, host, traceEnabled);
if (path === originalPath) {
originalPath = undefined;
}
@@ -899,7 +898,7 @@ namespace ts {
return !host.directoryExists || host.directoryExists(directoryName);
}
function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved {
function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state));
}
@@ -910,7 +909,7 @@ namespace ts {
function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
if (extensions === Extensions.Json) {
const extensionLess = tryRemoveExtension(candidate, Extension.Json);
return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
}
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
@@ -954,7 +953,7 @@ namespace ts {
function tryExtension(ext: Extension): PathAndExtension | undefined {
const path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
return path && { path, ext };
return path === undefined ? undefined : { path, ext };
}
}
@@ -1012,8 +1011,10 @@ namespace ts {
}
else {
const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state);
if (typeof jsPath === "string") {
subModuleName = removeExtension(removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), Extension.Js), Extension.Jsx) + Extension.Dts;
if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) {
const potentialSubModule = jsPath.substring(nodeModuleDirectory.length + 1);
subModuleName = (forEach(supportedJavascriptExtensions, extension =>
tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts;
}
else {
subModuleName = "index.d.ts";
@@ -1023,7 +1024,7 @@ namespace ts {
if (!endsWith(subModuleName, Extension.Dts)) {
subModuleName = addExtensionAndIndex(subModuleName);
}
const packageId: PackageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
const packageId: PackageId | undefined = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version }
: undefined;
if (traceEnabled) {
@@ -1047,9 +1048,18 @@ namespace ts {
}
function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): PathAndExtension | undefined {
const file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
let file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
return undefined;
if (extensions === Extensions.TypeScript) {
// When resolving typescript modules, try resolving using main field as well
file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state);
if (!file) {
return undefined;
}
}
else {
return undefined;
}
}
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host);
@@ -1130,7 +1140,7 @@ namespace ts {
return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
}
function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache): SearchResult<Resolved> {
function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult<Resolved> {
return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache);
}
function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): SearchResult<Resolved> {
@@ -1138,7 +1148,7 @@ namespace ts {
return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined);
}
function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache): SearchResult<Resolved> {
function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push<string>, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult<Resolved> {
const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => {
if (getBaseFileName(ancestorDirectory) !== "node_modules") {
@@ -1278,7 +1288,7 @@ namespace ts {
* This is the minumum code needed to expose that functionality; the rest is in LSHost.
*/
/* @internal */
export function loadModuleFromGlobalCache(moduleName: string, projectName: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations {
export function loadModuleFromGlobalCache(moduleName: string, projectName: string | undefined, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
+249 -158
View File
@@ -10,10 +10,10 @@ namespace ts {
}
// tslint:disable variable-name
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let NodeConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
// tslint:enable variable-name
export function createNode(kind: SyntaxKind, pos?: number, end?: number): Node {
@@ -31,11 +31,11 @@ namespace ts {
}
}
function visitNode<T>(cbNode: (node: Node) => T, node: Node): T | undefined {
function visitNode<T>(cbNode: (node: Node) => T, node: Node | undefined): T | undefined {
return node && cbNode(node);
}
function visitNodes<T>(cbNode: (node: Node) => T, cbNodes: (node: NodeArray<Node>) => T | undefined, nodes: NodeArray<Node>): T | undefined {
function visitNodes<T>(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray<Node>) => T | undefined) | undefined, nodes: NodeArray<Node> | undefined): T | undefined {
if (nodes) {
if (cbNodes) {
return cbNodes(nodes);
@@ -481,7 +481,7 @@ namespace ts {
return visitNodes(cbNode, cbNodes, (<JSDocTemplateTag>node).typeParameters);
case SyntaxKind.JSDocTypedefTag:
if ((node as JSDocTypedefTag).typeExpression &&
(node as JSDocTypedefTag).typeExpression.kind === SyntaxKind.JSDocTypeExpression) {
(node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression) {
return visitNode(cbNode, (<JSDocTypedefTag>node).typeExpression) ||
visitNode(cbNode, (<JSDocTypedefTag>node).fullName);
}
@@ -489,9 +489,18 @@ namespace ts {
return visitNode(cbNode, (<JSDocTypedefTag>node).fullName) ||
visitNode(cbNode, (<JSDocTypedefTag>node).typeExpression);
}
case SyntaxKind.JSDocCallbackTag:
return visitNode(cbNode, (node as JSDocCallbackTag).fullName) ||
visitNode(cbNode, (node as JSDocCallbackTag).typeExpression);
case SyntaxKind.JSDocSignature:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNodes(cbNode, cbNodes, (<SignatureDeclaration>node).typeParameters) ||
visitNodes(cbNode, cbNodes, (<SignatureDeclaration>node).parameters) ||
visitNode(cbNode, (<SignatureDeclaration>node).type);
case SyntaxKind.JSDocTypeLiteral:
if ((node as JSDocTypeLiteral).jsDocPropertyTags) {
for (const tag of (node as JSDocTypeLiteral).jsDocPropertyTags) {
for (const tag of (node as JSDocTypeLiteral).jsDocPropertyTags!) {
visitNode(cbNode, tag);
}
}
@@ -515,7 +524,7 @@ namespace ts {
return result;
}
export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName {
export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined {
return Parser.parseIsolatedEntityName(text, languageVersion);
}
@@ -542,7 +551,7 @@ namespace ts {
// from this SourceFile that are being held onto may change as a result (including
// becoming detached from any SourceFile). It is recommended that this SourceFile not
// be used once 'update' is called on it.
export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile {
export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks = false): SourceFile {
const newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
// Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
// We will manually port the flag to the new source file.
@@ -586,8 +595,8 @@ namespace ts {
// tslint:enable variable-name
let sourceFile: SourceFile;
let parseDiagnostics: Diagnostic[];
let syntaxCursor: IncrementalParser.SyntaxCursor;
let parseDiagnostics: DiagnosticWithLocation[];
let syntaxCursor: IncrementalParser.SyntaxCursor | undefined;
let currentToken: SyntaxKind;
let sourceText: string;
@@ -674,7 +683,7 @@ namespace ts {
// attached to the EOF token.
let parseErrorBeforeNextFinishedNode = false;
export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile {
export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor | undefined, setParentNodes = false, scriptKind?: ScriptKind): SourceFile {
scriptKind = ensureScriptKind(fileName, scriptKind);
if (scriptKind === ScriptKind.JSON) {
const result = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
@@ -693,7 +702,7 @@ namespace ts {
return result;
}
export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName {
export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName | undefined {
// Choice of `isDeclarationFile` should be arbitrary
initializeState(content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS);
// Prime the scanner.
@@ -766,7 +775,7 @@ namespace ts {
return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSON ? LanguageVariant.JSX : LanguageVariant.Standard;
}
function initializeState(_sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) {
function initializeState(_sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor | undefined, scriptKind: ScriptKind) {
NodeConstructor = objectAllocator.getNodeConstructor();
TokenConstructor = objectAllocator.getTokenConstructor();
IdentifierConstructor = objectAllocator.getIdentifierConstructor();
@@ -808,11 +817,11 @@ namespace ts {
scanner.setOnError(undefined);
// Clear any data. We don't want to accidentally hold onto it for too long.
parseDiagnostics = undefined;
sourceFile = undefined;
identifiers = undefined;
parseDiagnostics = undefined!;
sourceFile = undefined!;
identifiers = undefined!;
syntaxCursor = undefined;
sourceText = undefined;
sourceText = undefined!;
}
function parseSourceFileWorker(fileName: string, languageVersion: ScriptTarget, setParentNodes: boolean, scriptKind: ScriptKind): SourceFile {
@@ -856,7 +865,7 @@ namespace ts {
const comments = getJSDocCommentRanges(node, sourceFile.text);
if (comments) {
for (const comment of comments) {
node.jsDoc = append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos));
node.jsDoc = append<JSDoc>(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos));
}
}
@@ -884,7 +893,7 @@ namespace ts {
parent = n;
forEachChild(n, visitNode);
if (hasJSDocNodes(n)) {
for (const jsDoc of n.jsDoc) {
for (const jsDoc of n.jsDoc!) {
jsDoc.parent = n;
parent = jsDoc;
forEachChild(jsDoc, visitNode);
@@ -903,6 +912,7 @@ namespace ts {
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.bindSuggestionDiagnostics = undefined;
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.languageVariant = getLanguageVariant(scriptKind);
@@ -1195,7 +1205,7 @@ namespace ts {
}
function parseOptionalToken<TKind extends SyntaxKind>(t: TKind): Token<TKind>;
function parseOptionalToken(t: SyntaxKind): Node {
function parseOptionalToken(t: SyntaxKind): Node | undefined {
if (token() === t) {
return parseTokenNode();
}
@@ -1240,7 +1250,7 @@ namespace ts {
function createNode(kind: SyntaxKind, pos?: number): Node {
nodeCount++;
const p = pos >= 0 ? pos : scanner.getStartPos();
const p = pos! >= 0 ? pos! : scanner.getStartPos();
return isNodeKind(kind) || kind === SyntaxKind.Unknown ? new NodeConstructor(kind, p, p) :
kind === SyntaxKind.Identifier ? new IdentifierConstructor(kind, p, p) :
new TokenConstructor(kind, p, p);
@@ -1517,7 +1527,7 @@ namespace ts {
return true;
}
Debug.fail("Non-exhaustive case in 'isListElement'.");
return Debug.fail("Non-exhaustive case in 'isListElement'.");
}
function isValidHeritageClauseObjectLiteral() {
@@ -1619,6 +1629,8 @@ namespace ts {
return token() === SyntaxKind.GreaterThanToken || token() === SyntaxKind.SlashToken;
case ParsingContext.JsxChildren:
return token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsSlash);
default:
return false;
}
}
@@ -1693,7 +1705,7 @@ namespace ts {
return parseElement();
}
function currentNode(parsingContext: ParsingContext): Node {
function currentNode(parsingContext: ParsingContext): Node | undefined {
// If there is an outstanding parse error that we've encountered, but not attached to
// some node, then we cannot get a node from the old source tree. This is because we
// want to mark the next node we encounter as being unusable.
@@ -2009,6 +2021,7 @@ namespace ts {
case ParsingContext.ImportOrExportSpecifiers: return Diagnostics.Identifier_expected;
case ParsingContext.JsxAttributes: return Diagnostics.Identifier_expected;
case ParsingContext.JsxChildren: return Diagnostics.Identifier_expected;
default: return undefined!; // TODO: GH#18217 `default: Debug.assertNever(context);`
}
}
@@ -2163,7 +2176,7 @@ namespace ts {
do {
list.push(parseTemplateSpan());
}
while (lastOrUndefined(list).literal.kind === SyntaxKind.TemplateMiddle);
while (last(list).literal.kind === SyntaxKind.TemplateMiddle);
template.templateSpans = createNodeArray(list, listPos);
@@ -2386,7 +2399,7 @@ namespace ts {
}
}
function parseParameterType(): TypeNode {
function parseParameterType(): TypeNode | undefined {
if (parseOptional(SyntaxKind.ColonToken)) {
return parseType();
}
@@ -2436,20 +2449,24 @@ namespace ts {
return finishNode(node);
}
/**
* @returns If return type parsing succeeds
*/
function fillSignature(
returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken,
flags: SignatureFlags,
signature: SignatureDeclaration): void {
signature: SignatureDeclaration): boolean {
if (!(flags & SignatureFlags.JSDoc)) {
signature.typeParameters = parseTypeParameters();
}
signature.parameters = parseParameterList(flags);
signature.type = parseReturnType(returnToken, !!(flags & SignatureFlags.Type));
signature.parameters = parseParameterList(flags)!; // TODO: GH#18217
if (shouldParseReturnType(returnToken, !!(flags & SignatureFlags.Type))) {
signature.type = parseTypeOrTypePredicate();
return signature.type !== undefined;
}
return true;
}
function parseReturnType(returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, isType: boolean): TypeNode | undefined {
return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined;
}
function shouldParseReturnType(returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, isType: boolean): boolean {
if (returnToken === SyntaxKind.EqualsGreaterThanToken) {
parseExpected(returnToken);
@@ -2624,7 +2641,7 @@ namespace ts {
if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) {
return true;
}
let idToken: boolean;
let idToken = false;
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier
while (isModifierKind(token())) {
idToken = true;
@@ -2728,7 +2745,7 @@ namespace ts {
const node = <MappedTypeNode>createNode(SyntaxKind.MappedType);
parseExpected(SyntaxKind.OpenBraceToken);
if (token() === SyntaxKind.ReadonlyKeyword || token() === SyntaxKind.PlusToken || token() === SyntaxKind.MinusToken) {
node.readonlyToken = parseTokenNode();
node.readonlyToken = parseTokenNode<ReadonlyToken | PlusToken | MinusToken>();
if (node.readonlyToken.kind !== SyntaxKind.ReadonlyKeyword) {
parseExpectedToken(SyntaxKind.ReadonlyKeyword);
}
@@ -2737,7 +2754,7 @@ namespace ts {
node.typeParameter = parseMappedTypeParameter();
parseExpected(SyntaxKind.CloseBracketToken);
if (token() === SyntaxKind.QuestionToken || token() === SyntaxKind.PlusToken || token() === SyntaxKind.MinusToken) {
node.questionToken = parseTokenNode();
node.questionToken = parseTokenNode<QuestionToken | PlusToken | MinusToken>();
if (node.questionToken.kind !== SyntaxKind.QuestionToken) {
parseExpectedToken(SyntaxKind.QuestionToken);
}
@@ -2758,16 +2775,24 @@ namespace ts {
const node = <ParenthesizedTypeNode>createNode(SyntaxKind.ParenthesizedType);
parseExpected(SyntaxKind.OpenParenToken);
node.type = parseType();
if (!node.type) {
return undefined!; // TODO: GH#18217
}
parseExpected(SyntaxKind.CloseParenToken);
return finishNode(node);
}
function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode {
function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode | undefined {
const node = <FunctionOrConstructorTypeNode>createNodeWithJSDoc(kind);
if (kind === SyntaxKind.ConstructorType) {
parseExpected(SyntaxKind.NewKeyword);
}
fillSignature(SyntaxKind.EqualsGreaterThanToken, SignatureFlags.Type, node);
if (!fillSignature(SyntaxKind.EqualsGreaterThanToken, SignatureFlags.Type | (sourceFile.languageVariant === LanguageVariant.JSX ? SignatureFlags.RequireCompleteParameterList : 0), node)) {
return undefined;
}
if (!node.parameters) {
return undefined;
}
return finishNode(node);
}
@@ -2778,7 +2803,7 @@ namespace ts {
function parseLiteralTypeNode(negative?: boolean): LiteralTypeNode {
const node = createNode(SyntaxKind.LiteralType) as LiteralTypeNode;
let unaryMinusExpression: PrefixUnaryExpression;
let unaryMinusExpression!: PrefixUnaryExpression;
if (negative) {
unaryMinusExpression = createNode(SyntaxKind.PrefixUnaryExpression) as PrefixUnaryExpression;
unaryMinusExpression.operator = SyntaxKind.MinusToken;
@@ -3107,10 +3132,10 @@ namespace ts {
function parseTypeWorker(noConditionalTypes?: boolean): TypeNode {
if (isStartOfFunctionType()) {
return parseFunctionOrConstructorType(SyntaxKind.FunctionType);
return parseFunctionOrConstructorType(SyntaxKind.FunctionType)!; // TODO: GH#18217
}
if (token() === SyntaxKind.NewKeyword) {
return parseFunctionOrConstructorType(SyntaxKind.ConstructorType);
return parseFunctionOrConstructorType(SyntaxKind.ConstructorType)!;
}
const type = parseUnionTypeOrHigher();
if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.ExtendsKeyword)) {
@@ -3127,7 +3152,7 @@ namespace ts {
return type;
}
function parseTypeAnnotation(): TypeNode {
function parseTypeAnnotation(): TypeNode | undefined {
return parseOptional(SyntaxKind.ColonToken) ? parseType() : undefined;
}
@@ -3351,7 +3376,7 @@ namespace ts {
}
}
function parseSimpleArrowFunctionExpression(identifier: Identifier, asyncModifier?: NodeArray<Modifier>): ArrowFunction {
function parseSimpleArrowFunctionExpression(identifier: Identifier, asyncModifier?: NodeArray<Modifier> | undefined): ArrowFunction {
Debug.assert(token() === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
let node: ArrowFunction;
@@ -3550,7 +3575,7 @@ namespace ts {
}
}
function parsePossibleParenthesizedArrowFunctionExpressionHead(): ArrowFunction {
function parsePossibleParenthesizedArrowFunctionExpressionHead(): ArrowFunction | undefined {
return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
}
@@ -3587,7 +3612,7 @@ namespace ts {
return Tristate.False;
}
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction {
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction | undefined {
const node = <ArrowFunction>createNodeWithJSDoc(SyntaxKind.ArrowFunction);
node.modifiers = parseModifiersForArrowFunction();
const isAsync = hasModifier(node, ModifierFlags.Async) ? SignatureFlags.Await : SignatureFlags.None;
@@ -3598,7 +3623,9 @@ namespace ts {
// a => (b => c)
// And think that "(b =>" was actually a parenthesized arrow function with a missing
// close paren.
fillSignature(SyntaxKind.ColonToken, isAsync | (allowAmbiguity ? SignatureFlags.None : SignatureFlags.RequireCompleteParameterList), node);
if (!fillSignature(SyntaxKind.ColonToken, isAsync | (allowAmbiguity ? SignatureFlags.None : SignatureFlags.RequireCompleteParameterList), node)) {
return undefined;
}
// If we couldn't get parameters, we definitely could not parse out an arrow function.
if (!node.parameters) {
@@ -4184,7 +4211,7 @@ namespace ts {
badNode.end = invalidElement.end;
badNode.left = result;
badNode.right = invalidElement;
badNode.operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined);
badNode.operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined!); // TODO: GH#18217
badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
return <JsxElement><Node>badNode;
}
@@ -4878,7 +4905,7 @@ namespace ts {
const awaitToken = parseOptionalToken(SyntaxKind.AwaitKeyword);
parseExpected(SyntaxKind.OpenParenToken);
let initializer: VariableDeclarationList | Expression;
let initializer!: VariableDeclarationList | Expression;
if (token() !== SyntaxKind.SemicolonToken) {
if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword) {
initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
@@ -5321,7 +5348,7 @@ namespace ts {
node.decorators = parseDecorators();
node.modifiers = parseModifiers();
if (some(node.modifiers, isDeclareModifier)) {
for (const m of node.modifiers) {
for (const m of node.modifiers!) {
m.flags |= NodeFlags.Ambient;
}
return doInsideOfContext(NodeFlags.Ambient, () => parseDeclarationWorker(node));
@@ -5374,6 +5401,7 @@ namespace ts {
missing.modifiers = node.modifiers;
return finishNode(missing);
}
return undefined!; // TODO: GH#18217
}
}
@@ -5382,7 +5410,7 @@ namespace ts {
return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === SyntaxKind.StringLiteral);
}
function parseFunctionBlockOrSemicolon(flags: SignatureFlags, diagnosticMessage?: DiagnosticMessage): Block {
function parseFunctionBlockOrSemicolon(flags: SignatureFlags, diagnosticMessage?: DiagnosticMessage): Block | undefined {
if (token() !== SyntaxKind.OpenBraceToken && canParseSemicolon()) {
parseSemicolon();
return;
@@ -5460,7 +5488,7 @@ namespace ts {
node.name = parseIdentifierOrPattern();
if (allowExclamation && node.name.kind === SyntaxKind.Identifier &&
token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
node.exclamationToken = parseTokenNode();
node.exclamationToken = parseTokenNode<Token<SyntaxKind.ExclamationToken>>();
}
node.type = parseTypeAnnotation();
if (!isInOrOfKeyword(token())) {
@@ -5556,7 +5584,7 @@ namespace ts {
function parsePropertyDeclaration(node: PropertyDeclaration): PropertyDeclaration {
node.kind = SyntaxKind.PropertyDeclaration;
if (!node.questionToken && token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
node.exclamationToken = parseTokenNode();
node.exclamationToken = parseTokenNode<Token<SyntaxKind.ExclamationToken>>();
}
node.type = parseTypeAnnotation();
@@ -5598,7 +5626,7 @@ namespace ts {
}
function isClassMemberStart(): boolean {
let idToken: SyntaxKind;
let idToken: SyntaxKind | undefined;
if (token() === SyntaxKind.AtToken) {
return true;
@@ -5690,7 +5718,7 @@ namespace ts {
* In such situations, 'permitInvalidConstAsModifier' should be set to true.
*/
function parseModifiers(permitInvalidConstAsModifier?: boolean): NodeArray<Modifier> | undefined {
let list: Modifier[];
let list: Modifier[] | undefined;
const listPos = getNodePos();
while (true) {
const modifierStart = scanner.getStartPos();
@@ -5715,8 +5743,8 @@ namespace ts {
return list && createNodeArray(list, listPos);
}
function parseModifiersForArrowFunction(): NodeArray<Modifier> {
let modifiers: NodeArray<Modifier>;
function parseModifiersForArrowFunction(): NodeArray<Modifier> | undefined {
let modifiers: NodeArray<Modifier> | undefined;
if (token() === SyntaxKind.AsyncKeyword) {
const modifierStart = scanner.getStartPos();
const modifierKind = token();
@@ -5772,7 +5800,7 @@ namespace ts {
}
// 'isClassMemberStart' should have hinted not to attempt parsing.
Debug.fail("Should not have attempted to parse class member declaration.");
return Debug.fail("Should not have attempted to parse class member declaration.");
}
function parseClassExpression(): ClassExpression {
@@ -5829,17 +5857,14 @@ namespace ts {
return undefined;
}
function parseHeritageClause(): HeritageClause | undefined {
function parseHeritageClause(): HeritageClause {
const tok = token();
if (tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword) {
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
node.token = tok;
nextToken();
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
return finishNode(node);
}
return undefined;
Debug.assert(tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword); // isListElement() should ensure this.
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
node.token = tok as SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
nextToken();
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
return finishNode(node);
}
function parseExpressionWithTypeArguments(): ExpressionWithTypeArguments {
@@ -5998,7 +6023,7 @@ namespace ts {
parseExpected(SyntaxKind.ImportKeyword);
const afterImportPos = scanner.getStartPos();
let identifier: Identifier;
let identifier: Identifier | undefined;
if (isIdentifier()) {
identifier = parseIdentifier();
if (token() !== SyntaxKind.CommaToken && token() !== SyntaxKind.FromKeyword) {
@@ -6032,7 +6057,7 @@ namespace ts {
return finishNode(node);
}
function parseImportClause(identifier: Identifier, fullStart: number) {
function parseImportClause(identifier: Identifier | undefined, fullStart: number) {
// ImportClause:
// ImportedDefaultBinding
// NameSpaceImport
@@ -6209,7 +6234,7 @@ namespace ts {
undefined;
}
function walkTreeForExternalModuleIndicators(node: Node): Node {
function walkTreeForExternalModuleIndicators(node: Node): Node | undefined {
return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
}
@@ -6251,7 +6276,7 @@ namespace ts {
}
export namespace JSDocParser {
export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number): { jsDocTypeExpression: JSDocTypeExpression, diagnostics: Diagnostic[] } | undefined {
export function parseJSDocTypeExpressionForTests(content: string, start: number | undefined, length: number | undefined): { jsDocTypeExpression: JSDocTypeExpression, diagnostics: Diagnostic[] } | undefined {
initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS);
sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
@@ -6277,7 +6302,7 @@ namespace ts {
return finishNode(result);
}
export function parseIsolatedJSDocComment(content: string, start: number, length: number): { jsDoc: JSDoc, diagnostics: Diagnostic[] } | undefined {
export function parseIsolatedJSDocComment(content: string, start: number | undefined, length: number | undefined): { jsDoc: JSDoc, diagnostics: Diagnostic[] } | undefined {
initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS);
sourceFile = <SourceFile>{ languageVariant: LanguageVariant.Standard, text: content }; // tslint:disable-line no-object-literal-type-assertion
const jsDoc = parseJSDocCommentWorker(start, length);
@@ -6287,7 +6312,7 @@ namespace ts {
return jsDoc ? { jsDoc, diagnostics } : undefined;
}
export function parseJSDocComment(parent: HasJSDoc, start: number, length: number): JSDoc {
export function parseJSDocComment(parent: HasJSDoc, start: number, length: number): JSDoc | undefined {
const saveToken = currentToken;
const saveParseDiagnosticsLength = parseDiagnostics.length;
const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -6317,13 +6342,13 @@ namespace ts {
}
const enum PropertyLikeParse {
Property,
Parameter,
Property = 1 << 0,
Parameter = 1 << 1,
CallbackParameter = 1 << 2,
}
export function parseJSDocCommentWorker(start: number, length: number): JSDoc {
export function parseJSDocCommentWorker(start = 0, length: number | undefined): JSDoc | undefined {
const content = sourceText;
start = start || 0;
const end = length === undefined ? content.length : start + length;
length = end - start;
@@ -6335,7 +6360,7 @@ namespace ts {
let tagsPos: number;
let tagsEnd: number;
const comments: string[] = [];
let result: JSDoc;
let result: JSDoc | undefined;
// Check for /** (JSDoc opening part)
if (!isJSDocLikeText(content, start)) {
@@ -6372,7 +6397,7 @@ namespace ts {
case SyntaxKind.AtToken:
if (state === JSDocState.BeginningOfLine || state === JSDocState.SawAsterisk) {
removeTrailingNewlines(comments);
parseTag(indent);
addTag(parseTag(indent));
// NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
// Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
// for malformed examples like `/** @param {string} x @returns {number} the length */`
@@ -6457,7 +6482,25 @@ namespace ts {
return finishNode(result, end);
}
function isNextNonwhitespaceTokenEndOfFile(): boolean {
// We must use infinite lookahead, as there could be any number of newlines :(
while (true) {
nextJSDocToken();
if (token() === SyntaxKind.EndOfFileToken) {
return true;
}
if (!(token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia)) {
return false;
}
}
}
function skipWhitespace(): void {
if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) {
if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
}
}
while (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) {
nextJSDocToken();
}
@@ -6475,7 +6518,7 @@ namespace ts {
return;
}
let tag: JSDocTag;
let tag: JSDocTag | undefined;
if (tagName) {
switch (tagName.escapedText) {
case "augments":
@@ -6489,8 +6532,7 @@ namespace ts {
case "arg":
case "argument":
case "param":
addTag(parseParameterOrPropertyTag(atToken, tagName, PropertyLikeParse.Parameter, indent));
return;
return parseParameterOrPropertyTag(atToken, tagName, PropertyLikeParse.Parameter, indent);
case "return":
case "returns":
tag = parseReturnTag(atToken, tagName);
@@ -6502,7 +6544,10 @@ namespace ts {
tag = parseTypeTag(atToken, tagName);
break;
case "typedef":
tag = parseTypedefTag(atToken, tagName);
tag = parseTypedefTag(atToken, tagName, indent);
break;
case "callback":
tag = parseCallbackTag(atToken, tagName, indent);
break;
default:
tag = parseUnknownTag(atToken, tagName);
@@ -6517,8 +6562,11 @@ namespace ts {
// a badly malformed tag should not be added to the list of tags
return;
}
tag.comment = parseTagComments(indent + tag.end - tag.pos);
addTag(tag);
if (!tag.comment) {
// some tags, like typedef and callback, have already parsed their comments earlier
tag.comment = parseTagComments(indent + tag.end - tag.pos);
}
return tag;
}
function parseTagComments(indent: number): string | undefined {
@@ -6590,7 +6638,10 @@ namespace ts {
return finishNode(result);
}
function addTag(tag: JSDocTag): void {
function addTag(tag: JSDocTag | undefined): void {
if (!tag) {
return;
}
if (!tags) {
tags = [tag];
tagsPos = tag.pos;
@@ -6651,9 +6702,9 @@ namespace ts {
typeExpression = tryParseTypeExpression();
}
const result = target === PropertyLikeParse.Parameter ?
<JSDocParameterTag>createNode(SyntaxKind.JSDocParameterTag, atToken.pos) :
<JSDocPropertyTag>createNode(SyntaxKind.JSDocPropertyTag, atToken.pos);
const result = target === PropertyLikeParse.Property ?
<JSDocPropertyTag>createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) :
<JSDocParameterTag>createNode(SyntaxKind.JSDocParameterTag, atToken.pos);
let comment: string | undefined;
if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target);
@@ -6671,13 +6722,13 @@ namespace ts {
return finishNode(result);
}
function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression, name: EntityName, target: PropertyLikeParse) {
function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
const typeLiteralExpression = <JSDocTypeExpression>createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos());
let child: JSDocPropertyLikeTag | JSDocTypeTag | false;
let jsdocTypeLiteral: JSDocTypeLiteral;
const start = scanner.getStartPos();
let children: JSDocPropertyLikeTag[];
let children: JSDocPropertyLikeTag[] | undefined;
while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) {
if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) {
children = append(children, child);
@@ -6744,7 +6795,7 @@ namespace ts {
while (parseOptional(SyntaxKind.DotToken)) {
const prop: PropertyAccessEntityNameExpression = createNode(SyntaxKind.PropertyAccessExpression, node.pos) as PropertyAccessEntityNameExpression;
prop.expression = node;
prop.name = parseJSDocIdentifierName();
prop.name = parseJSDocIdentifierName()!; // TODO: GH#18217
node = finishNode(prop);
}
return node;
@@ -6757,33 +6808,24 @@ namespace ts {
return finishNode(tag);
}
function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag {
function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();
const typedefTag = <JSDocTypedefTag>createNode(SyntaxKind.JSDocTypedefTag, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
if (typedefTag.fullName) {
let rightNode = typedefTag.fullName;
while (true) {
if (rightNode.kind === SyntaxKind.Identifier || !rightNode.body) {
// if node is identifier - use it as name
// otherwise use name of the rightmost part that we were able to parse
typedefTag.name = rightNode.kind === SyntaxKind.Identifier ? rightNode : rightNode.name;
break;
}
rightNode = rightNode.body;
}
}
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
skipWhitespace();
typedefTag.comment = parseTagComments(indent);
typedefTag.typeExpression = typeExpression;
let end: number | undefined;
if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
let child: JSDocTypeTag | JSDocPropertyTag | false;
let jsdocTypeLiteral: JSDocTypeLiteral;
let childTypeTag: JSDocTypeTag;
let jsdocTypeLiteral: JSDocTypeLiteral | undefined;
let childTypeTag: JSDocTypeTag | undefined;
const start = scanner.getStartPos();
while (child = tryParse(() => parseChildPropertyTag())) {
if (!jsdocTypeLiteral) {
@@ -6808,27 +6850,75 @@ namespace ts {
typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
childTypeTag.typeExpression :
finishNode(jsdocTypeLiteral);
end = typedefTag.typeExpression.end;
}
}
return finishNode(typedefTag);
// Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
}
function parseJSDocTypeNameWithNamespace(flags: NodeFlags) {
const pos = scanner.getTokenPos();
const typeNameOrNamespaceName = parseJSDocIdentifierName();
function parseJSDocTypeNameWithNamespace(nested?: boolean) {
const pos = scanner.getTokenPos();
const typeNameOrNamespaceName = parseJSDocIdentifierName();
if (typeNameOrNamespaceName && parseOptional(SyntaxKind.DotToken)) {
const jsDocNamespaceNode = <JSDocNamespaceDeclaration>createNode(SyntaxKind.ModuleDeclaration, pos);
jsDocNamespaceNode.flags |= flags;
jsDocNamespaceNode.name = typeNameOrNamespaceName;
jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(NodeFlags.NestedNamespace);
return finishNode(jsDocNamespaceNode);
if (typeNameOrNamespaceName && parseOptional(SyntaxKind.DotToken)) {
const jsDocNamespaceNode = <JSDocNamespaceDeclaration>createNode(SyntaxKind.ModuleDeclaration, pos);
if (nested) {
jsDocNamespaceNode.flags |= NodeFlags.NestedNamespace;
}
jsDocNamespaceNode.name = typeNameOrNamespaceName;
jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
return finishNode(jsDocNamespaceNode);
}
if (typeNameOrNamespaceName && flags & NodeFlags.NestedNamespace) {
typeNameOrNamespaceName.isInJSDocNamespace = true;
if (typeNameOrNamespaceName && nested) {
typeNameOrNamespaceName.isInJSDocNamespace = true;
}
return typeNameOrNamespaceName;
}
function parseCallbackTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocCallbackTag {
const callbackTag = createNode(SyntaxKind.JSDocCallbackTag, atToken.pos) as JSDocCallbackTag;
callbackTag.atToken = atToken;
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
let child: JSDocParameterTag | false;
const start = scanner.getStartPos();
const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature;
jsdocSignature.parameters = [];
while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter) as JSDocParameterTag)) {
jsdocSignature.parameters = append(jsdocSignature.parameters as MutableNodeArray<JSDocParameterTag>, child);
}
const returnTag = tryParse(() => {
if (token() === SyntaxKind.AtToken) {
nextJSDocToken();
const tag = parseTag(indent);
if (tag && tag.kind === SyntaxKind.JSDocReturnTag) {
return tag as JSDocReturnTag;
}
}
});
if (returnTag) {
jsdocSignature.type = returnTag;
}
callbackTag.typeExpression = finishNode(jsdocSignature);
return finishNode(callbackTag);
}
function getJSDocTypeAliasName(fullName: JSDocNamespaceBody | undefined) {
if (fullName) {
let rightNode = fullName;
while (true) {
if (ts.isIdentifier(rightNode) || !rightNode.body) {
return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
}
rightNode = rightNode.body;
}
return typeNameOrNamespaceName;
}
}
@@ -6858,7 +6948,8 @@ namespace ts {
if (canParseTag) {
const child = tryParseChildTag(target);
if (child && child.kind === SyntaxKind.JSDocParameterTag &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
target !== PropertyLikeParse.CallbackParameter &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name!, child.name.left))) { // TODO: GH#18217
return false;
}
return child;
@@ -6906,12 +6997,12 @@ namespace ts {
case "arg":
case "argument":
case "param":
t = PropertyLikeParse.Parameter;
t = PropertyLikeParse.Parameter | PropertyLikeParse.CallbackParameter;
break;
default:
return false;
}
if (target !== t) {
if (!(target & t)) {
return false;
}
const tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined);
@@ -7006,7 +7097,7 @@ namespace ts {
const pos = scanner.getTokenPos();
const end = scanner.getTextPos();
const result = <Identifier>createNode(SyntaxKind.Identifier, pos);
result.escapedText = escapeLeadingUnderscores(content.substring(pos, end));
result.escapedText = escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
@@ -7128,7 +7219,7 @@ namespace ts {
forEachChild(node, visitNode, visitArray);
if (hasJSDocNodes(node)) {
for (const jsDocComment of node.jsDoc) {
for (const jsDocComment of node.jsDoc!) {
visitNode(<IncrementalNode><Node>jsDocComment);
}
}
@@ -7240,7 +7331,7 @@ namespace ts {
pos = child.end;
};
if (hasJSDocNodes(node)) {
for (const jsDocComment of node.jsDoc) {
for (const jsDocComment of node.jsDoc!) {
visitNode(jsDocComment);
}
}
@@ -7283,7 +7374,7 @@ namespace ts {
adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
forEachChild(child, visitNode, visitArray);
if (hasJSDocNodes(child)) {
for (const jsDocComment of child.jsDoc) {
for (const jsDocComment of child.jsDoc!) {
visitNode(<IncrementalNode><Node>jsDocComment);
}
}
@@ -7359,7 +7450,7 @@ namespace ts {
function findNearestNodeStartingBeforeOrAtPosition(sourceFile: SourceFile, position: number): Node {
let bestResult: Node = sourceFile;
let lastNodeEntirelyBeforePosition: Node;
let lastNodeEntirelyBeforePosition: Node | undefined;
forEachChild(sourceFile, visit);
@@ -7460,10 +7551,10 @@ namespace ts {
}
interface IncrementalElement extends TextRange {
parent?: Node;
parent: Node;
intersectsChange: boolean;
length?: number;
_children: Node[];
_children: Node[] | undefined;
}
export interface IncrementalNode extends Node, IncrementalElement {
@@ -7529,9 +7620,9 @@ namespace ts {
// return it, we can easily return its next sibling in the list.
function findHighestListElementThatStartsAtPosition(position: number) {
// Clear out any cached state about the last node we found.
currentArray = undefined;
currentArray = undefined!;
currentArrayIndex = InvalidPosition.Value;
current = undefined;
current = undefined!;
// Recurse into the source file to find the highest node at this position.
forEachChild(sourceFile, visitNode, visitArray);
@@ -7629,17 +7720,17 @@ namespace ts {
context.pragmas = createMap() as PragmaMap;
for (const pragma of pragmas) {
if (context.pragmas.has(pragma.name)) {
const currentValue = context.pragmas.get(pragma.name);
if (context.pragmas.has(pragma!.name)) { // TODO: GH#18217
const currentValue = context.pragmas.get(pragma!.name);
if (currentValue instanceof Array) {
currentValue.push(pragma.args);
currentValue.push(pragma!.args);
}
else {
context.pragmas.set(pragma.name, [currentValue, pragma.args]);
context.pragmas.set(pragma!.name, [currentValue, pragma!.args]);
}
continue;
}
context.pragmas.set(pragma.name, pragma.args);
context.pragmas.set(pragma!.name, pragma!.args);
}
}
@@ -7653,7 +7744,7 @@ namespace ts {
context.typeReferenceDirectives = [];
context.amdDependencies = [];
context.hasNoDefaultLib = false;
context.pragmas.forEach((entryOrList, key) => {
context.pragmas!.forEach((entryOrList, key) => { // TODO: GH#18217
// TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
// key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
switch (key) {
@@ -7661,17 +7752,18 @@ namespace ts {
const referencedFiles = context.referencedFiles;
const typeReferenceDirectives = context.typeReferenceDirectives;
forEach(toArray(entryOrList), (arg: PragmaPsuedoMap["reference"]) => {
if (arg.arguments["no-default-lib"]) {
// TODO: GH#18217
if (arg!.arguments["no-default-lib"]) {
context.hasNoDefaultLib = true;
}
else if (arg.arguments.types) {
typeReferenceDirectives.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value });
else if (arg!.arguments.types) {
typeReferenceDirectives.push({ pos: arg!.arguments.types!.pos, end: arg!.arguments.types!.end, fileName: arg!.arguments.types!.value });
}
else if (arg.arguments.path) {
referencedFiles.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value });
else if (arg!.arguments.path) {
referencedFiles.push({ pos: arg!.arguments.path!.pos, end: arg!.arguments.path!.end, fileName: arg!.arguments.path!.value });
}
else {
reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax);
reportDiagnostic(arg!.range.pos, arg!.range.end - arg!.range.pos, Diagnostics.Invalid_reference_directive_syntax);
}
});
break;
@@ -7679,8 +7771,7 @@ namespace ts {
case "amd-dependency": {
context.amdDependencies = map(
toArray(entryOrList),
({ arguments: { name, path } }: PragmaPsuedoMap["amd-dependency"]) => ({ name, path })
);
(x: PragmaPsuedoMap["amd-dependency"]) => ({ name: x!.arguments.name!, path: x!.arguments.path })); // TODO: GH#18217
break;
}
case "amd-module": {
@@ -7688,13 +7779,13 @@ namespace ts {
for (const entry of entryOrList) {
if (context.moduleName) {
// TODO: It's probably fine to issue this diagnostic on all instances of the pragma
reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
reportDiagnostic(entry!.range.pos, entry!.range.end - entry!.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
}
context.moduleName = (entry as PragmaPsuedoMap["amd-module"]).arguments.name;
context.moduleName = (entry as PragmaPsuedoMap["amd-module"])!.arguments.name;
}
}
else {
context.moduleName = (entryOrList as PragmaPsuedoMap["amd-module"]).arguments.name;
context.moduleName = (entryOrList as PragmaPsuedoMap["amd-module"])!.arguments.name;
}
break;
}
@@ -7702,11 +7793,11 @@ namespace ts {
case "ts-check": {
// _last_ of either nocheck or check in a file is the "winner"
forEach(toArray(entryOrList), entry => {
if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
if (!context.checkJsDirective || entry!.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217
context.checkJsDirective = {
enabled: key === "ts-check",
end: entry.range.end,
pos: entry.range.pos
end: entry!.range.end,
pos: entry!.range.pos
};
}
});
@@ -7719,9 +7810,9 @@ namespace ts {
}
const namedArgRegExCache = createMap<RegExp>();
function getNamedArgRegEx(name: string) {
function getNamedArgRegEx(name: string): RegExp {
if (namedArgRegExCache.has(name)) {
return namedArgRegExCache.get(name);
return namedArgRegExCache.get(name)!;
}
const result = new RegExp(`(\\s${name}\\s*=\\s*)('|")(.+?)\\2`, "im");
namedArgRegExCache.set(name, result);
@@ -7735,7 +7826,7 @@ namespace ts {
if (tripleSlash) {
const name = tripleSlash[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks
const pragma = commentPragmas[name] as PragmaDefinition;
if (!pragma || !(pragma.kind & PragmaKindFlags.TripleSlashXML)) {
if (!pragma || !(pragma.kind! & PragmaKindFlags.TripleSlashXML)) {
return;
}
if (pragma.args) {
@@ -7775,7 +7866,7 @@ namespace ts {
if (range.kind === SyntaxKind.MultiLineCommentTrivia) {
const multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
let multiLineMatch: RegExpExecArray;
let multiLineMatch: RegExpExecArray | null;
while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
addPragmaForMatch(pragmas, range, PragmaKindFlags.MultiLine, multiLineMatch);
}
@@ -7786,7 +7877,7 @@ namespace ts {
if (!match) return;
const name = match[1].toLowerCase() as keyof PragmaPsuedoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks
const pragma = commentPragmas[name] as PragmaDefinition;
if (!pragma || !(pragma.kind & kind)) {
if (!pragma || !(pragma.kind! & kind)) {
return;
}
const args = match[2]; // Split on spaces and match up positionally with definition
+1 -1
View File
@@ -2,7 +2,7 @@
namespace ts {
declare const performance: { now?(): number } | undefined;
/** Gets a timestamp with (at least) ms resolution */
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now() : Date.now ? Date.now : () => +(new Date());
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now!() : Date.now ? Date.now : () => +(new Date());
}
/*@internal*/
Regular → Executable
+127 -118
View File
@@ -16,7 +16,7 @@ namespace ts {
/* @internal */
export function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): string {
let commonPathComponents: string[];
let commonPathComponents: string[] | undefined;
const failed = forEach(fileNames, sourceFile => {
// Each file contributes into common source file path
const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory);
@@ -75,8 +75,8 @@ namespace ts {
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined {
let text: string | undefined;
try {
performance.mark("beforeIORead");
text = sys.readFile(fileName, options.charset);
@@ -119,8 +119,8 @@ namespace ts {
outputFingerprints = createMap<OutputFingerprint>();
}
const hash = sys.createHash(data);
const mtimeBefore = sys.getModifiedTime(fileName);
const hash = sys.createHash!(data); // TODO: GH#18217
const mtimeBefore = sys.getModifiedTime!(fileName); // TODO: GH#18217
if (mtimeBefore) {
const fingerprint = outputFingerprints.get(fileName);
@@ -135,7 +135,7 @@ namespace ts {
sys.writeFile(fileName, data, writeByteOrderMark);
const mtimeAfter = sys.getModifiedTime(fileName);
const mtimeAfter = sys.getModifiedTime!(fileName); // TODO: GH#18217
outputFingerprints.set(fileName, {
hash,
@@ -171,7 +171,7 @@ namespace ts {
}
const newLine = getNewLineCharacter(options);
const realpath = sys.realpath && ((path: string) => sys.realpath(path));
const realpath = sys.realpath && ((path: string) => sys.realpath!(path));
return {
getSourceFile,
@@ -231,7 +231,7 @@ namespace ts {
const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`;
if (diagnostic.file) {
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start!); // TODO: GH#18217
const fileName = diagnostic.file.fileName;
const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName));
return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage;
@@ -279,8 +279,8 @@ namespace ts {
let context = "";
if (diagnostic.file) {
const { start, length, file } = diagnostic;
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start);
const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length);
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start!); // TODO: GH#18217
const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start! + length!);
const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line;
const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName;
@@ -352,7 +352,7 @@ namespace ts {
return output + host.getNewLine();
}
export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string {
export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string {
if (isString(messageText)) {
return messageText;
}
@@ -387,7 +387,7 @@ namespace ts {
for (const name of names) {
let result: T;
if (cache.has(name)) {
result = cache.get(name);
result = cache.get(name)!;
}
else {
cache.set(name, result = loader(name, containingFile));
@@ -397,8 +397,8 @@ namespace ts {
return resolutions;
}
interface DiagnosticCache {
perFile?: Map<Diagnostic[]>;
interface DiagnosticCache<T extends Diagnostic> {
perFile?: Map<T[]>;
allDiagnostics?: Diagnostic[];
}
@@ -410,7 +410,7 @@ namespace ts {
program: Program | undefined,
rootFileNames: string[],
newOptions: CompilerOptions,
getSourceVersion: (path: Path) => string,
getSourceVersion: (path: Path) => string | undefined,
fileExists: (fileName: string) => boolean,
hasInvalidatedResolution: HasInvalidatedResolution,
hasChangedAutomaticTypeDirectiveNames: boolean,
@@ -457,14 +457,14 @@ namespace ts {
export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray<Diagnostic> {
return configFileParseResult.options.configFile ?
configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) :
[...configFileParseResult.options.configFile.parseDiagnostics, ...configFileParseResult.errors] :
configFileParseResult.errors;
}
/**
* Determined if source file needs to be re-created even if its text hasn't changed
*/
function shouldProgramCreateNewSourceFiles(program: Program, newOptions: CompilerOptions) {
function shouldProgramCreateNewSourceFiles(program: Program | undefined, newOptions: CompilerOptions) {
// If any of these options change, we can't reuse old source file even if version match
// The change in options like these could result in change in syntax tree change
const oldOptions = program && program.getCompilerOptions();
@@ -508,9 +508,9 @@ namespace ts {
export function createProgram(createProgramOptions: CreateProgramOptions): Program;
export function createProgram(rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): Program;
export function createProgram(rootNamesOrOptions: ReadonlyArray<string> | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): Program {
const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
const { rootNames, options, configFileParsingDiagnostics, projectReferences } = createProgramOptions;
let { host, oldProgram } = createProgramOptions;
let { oldProgram } = createProgramOptions;
let program: Program;
let files: SourceFile[] = [];
@@ -520,8 +520,8 @@ namespace ts {
let classifiableNames: UnderscoreEscapedMap<true>;
let modifiedFilePaths: Path[] | undefined;
const cachedSemanticDiagnosticsForFile: DiagnosticCache = {};
const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {};
const cachedSemanticDiagnosticsForFile: DiagnosticCache<Diagnostic> = {};
const cachedDeclarationDiagnosticsForFile: DiagnosticCache<DiagnosticWithLocation> = {};
let resolvedTypeReferenceDirectives = createMap<ResolvedTypeReferenceDirective>();
let fileProcessingDiagnostics = createDiagnosticCollection();
@@ -545,7 +545,7 @@ namespace ts {
performance.mark("beforeProgram");
host = host || createCompilerHost(options);
const host = createProgramOptions.host || createCompilerHost(options);
const configParsingHost = parseConfigHostFromCompilerHost(host);
let skipDefaultLib = options.noLib;
@@ -557,14 +557,14 @@ namespace ts {
// Map storing if there is emit blocking diagnostics for given input
const hasEmitBlockingDiagnostics = createMap<boolean>();
let _compilerOptionsObjectLiteralSyntax: ObjectLiteralExpression;
let _referencesArrayLiteralSyntax: ArrayLiteralExpression;
let _compilerOptionsObjectLiteralSyntax: ObjectLiteralExpression | null | undefined;
let _referencesArrayLiteralSyntax: ArrayLiteralExpression | null | undefined;
let moduleResolutionCache: ModuleResolutionCache;
let moduleResolutionCache: ModuleResolutionCache | undefined;
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[]) => ResolvedModuleFull[];
const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse;
if (host.resolveModuleNames) {
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames(Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(resolved => {
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(resolved => {
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) {
return resolved as ResolvedModuleFull;
@@ -576,17 +576,17 @@ namespace ts {
}
else {
moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x));
const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule;
resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, loader);
const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule!; // TODO: GH#18217
resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache<ResolvedModuleFull>(Debug.assertEachDefined(moduleNames), containingFile, loader);
}
let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
if (host.resolveTypeReferenceDirectives) {
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives(Debug.assertEachDefined(typeDirectiveNames), containingFile);
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile);
}
else {
const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective;
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader);
const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective!; // TODO: GH#18217
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader);
}
// Map from a stringified PackageId to the source file with that id.
@@ -598,7 +598,7 @@ namespace ts {
let redirectTargetsSet = createMap<true>();
const filesByName = createMap<SourceFile | undefined>();
let missingFilePaths: ReadonlyArray<Path>;
let missingFilePaths: ReadonlyArray<Path> | undefined;
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createMap<SourceFile>() : undefined;
@@ -609,7 +609,7 @@ namespace ts {
if (projectReferences) {
for (const ref of projectReferences) {
const parsedRef = parseProjectReferenceConfigFile(ref);
resolvedProjectReferences.push(parsedRef);
resolvedProjectReferences!.push(parsedRef);
if (parsedRef) {
if (parsedRef.commandLine.options.outFile) {
const dtsOutfile = changeExtension(parsedRef.commandLine.options.outFile, ".d.ts");
@@ -680,7 +680,7 @@ namespace ts {
getSourceFile,
getSourceFileByPath,
getSourceFiles: () => files,
getMissingFilePaths: () => missingFilePaths,
getMissingFilePaths: () => missingFilePaths!, // TODO: GH#18217
getCompilerOptions: () => options,
getSyntacticDiagnostics,
getOptionsDiagnostics,
@@ -717,7 +717,7 @@ namespace ts {
return program;
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations {
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined {
return moduleResolutionCache && resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
}
@@ -734,7 +734,7 @@ namespace ts {
}
else if (options.composite) {
// Project compilations never infer their root from the input source paths
commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath));
commonSourceDirectory = getDirectoryPath(normalizeSlashes(options.configFilePath!)); // TODO: GH#18217
checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
}
else {
@@ -758,7 +758,7 @@ namespace ts {
classifiableNames = createUnderscoreEscapedMap<true>();
for (const sourceFile of files) {
copyEntries(sourceFile.classifiableNames, classifiableNames);
copyEntries(sourceFile.classifiableNames!, classifiableNames);
}
}
@@ -769,7 +769,7 @@ namespace ts {
program: Program | undefined;
oldSourceFile: SourceFile | undefined;
/** The collection of paths modified *since* the old program. */
modifiedFilePaths: Path[];
modifiedFilePaths: Path[] | undefined;
}
function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile, oldProgramState: OldProgramState) {
@@ -791,7 +791,7 @@ namespace ts {
// it is safe to reuse resolutions from the earlier call.
const result: ResolvedModuleFull[] = [];
for (const moduleName of moduleNames) {
const resolvedModule = file.resolvedModules.get(moduleName);
const resolvedModule = file.resolvedModules.get(moduleName)!;
result.push(resolvedModule);
}
return result;
@@ -802,7 +802,7 @@ namespace ts {
// With this information, we can infer some module resolutions without performing resolution.
/** An ordered list of module names for which we cannot recover the resolution. */
let unknownModuleNames: string[];
let unknownModuleNames: string[] | undefined;
/**
* The indexing of elements in this list matches that of `moduleNames`.
*
@@ -812,8 +812,8 @@ namespace ts {
* Needs to be reset to undefined before returning,
* * ResolvedModuleFull instance: can be reused.
*/
let result: ResolvedModuleFull[];
let reusedNames: string[];
let result: ResolvedModuleFull[] | undefined;
let reusedNames: string[] | undefined;
/** A transient placeholder used to mark predicted resolution in the result list. */
const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = <any>{};
@@ -821,7 +821,7 @@ namespace ts {
const moduleName = moduleNames[i];
// If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
const oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
const oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules!.get(moduleName);
if (oldResolvedModule) {
if (isTraceEnabled(options, host)) {
trace(host, Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
@@ -872,7 +872,7 @@ namespace ts {
// `result[i]` is either a `ResolvedModuleFull` or a marker.
// If it is the former, we can leave it as is.
if (result[i] === predictedToResolveToAmbientModuleMarker) {
result[i] = undefined;
result[i] = undefined!; // TODO: GH#18217
}
}
else {
@@ -887,7 +887,7 @@ namespace ts {
// If we change our policy of rechecking failed lookups on each program create,
// we should adjust the value returned here.
function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState: OldProgramState): boolean {
const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile, moduleName);
const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile!, moduleName); // TODO: GH#18217
const resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName);
if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) {
// In the old program, we resolved to an ambient module that was in the same
@@ -930,7 +930,7 @@ namespace ts {
return oldProgram.structureIsReused = StructureIsReused.Not;
}
Debug.assert(!(oldProgram.structureIsReused & (StructureIsReused.Completely | StructureIsReused.SafeModules)));
Debug.assert(!(oldProgram.structureIsReused! & (StructureIsReused.Completely | StructureIsReused.SafeModules)));
// there is an old program, check if we can reuse its structure
const oldRootNames = oldProgram.getRootFileNames();
@@ -990,8 +990,8 @@ namespace ts {
for (const oldSourceFile of oldSourceFiles) {
let newSourceFile = host.getSourceFileByPath
? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
: host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile);
? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile)
: host.getSourceFile(oldSourceFile.fileName, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
if (!newSourceFile) {
return oldProgram.structureIsReused = StructureIsReused.Not;
@@ -1137,7 +1137,7 @@ namespace ts {
for (let i = 0; i < newSourceFiles.length; i++) {
filesByName.set(filePaths[i], newSourceFiles[i]);
// Set the file as found during node modules search if it was found that way in old progra,
if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) {
if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i])!)) {
sourceFilesFoundSearchingNodeModules.set(filePaths[i], true);
}
}
@@ -1188,7 +1188,7 @@ namespace ts {
const nodes: InputFiles[] = [];
for (let i = 0; i < projectReferences.length; i++) {
const ref = projectReferences[i];
const resolvedRefOpts = resolvedProjectReferences[i].commandLine;
const resolvedRefOpts = resolvedProjectReferences![i]!.commandLine;
if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
// Upstream project didn't have outFile set -- skip (error will have been issued earlier)
if (!resolvedRefOpts.options.outFile) continue;
@@ -1204,7 +1204,7 @@ namespace ts {
}
function isSourceFileFromExternalLibrary(file: SourceFile): boolean {
return sourceFilesFoundSearchingNodeModules.get(file.path);
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
}
function isSourceFileDefaultLibrary(file: SourceFile): boolean {
@@ -1223,7 +1223,7 @@ namespace ts {
return equalityComparer(file.fileName, getDefaultLibraryFileName());
}
else {
return forEach(options.lib, libFileName => equalityComparer(file.fileName, combinePaths(defaultLibraryPath, libFileName)));
return some(options.lib, libFileName => equalityComparer(file.fileName, combinePaths(defaultLibraryPath, libFileName)));
}
}
@@ -1232,7 +1232,7 @@ namespace ts {
}
function dropDiagnosticsProducingTypeChecker() {
diagnosticsProducingTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined!;
}
function getTypeChecker() {
@@ -1247,7 +1247,7 @@ namespace ts {
return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
}
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult {
function emitWorker(program: Program, sourceFile: SourceFile | undefined, writeFileCallback: WriteFileCallback | undefined, cancellationToken: CancellationToken | undefined, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult {
let declarationDiagnostics: ReadonlyArray<Diagnostic> = [];
if (!emitOnlyDtsFiles) {
@@ -1297,7 +1297,7 @@ namespace ts {
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
sourceFile,
sourceFile!, // TODO: GH#18217
emitOnlyDtsFiles,
transformers,
customTransformers && customTransformers.afterDeclarations
@@ -1316,10 +1316,10 @@ namespace ts {
return filesByName.get(path);
}
function getDiagnosticsHelper(
function getDiagnosticsHelper<T extends Diagnostic>(
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => ReadonlyArray<Diagnostic>,
cancellationToken: CancellationToken): ReadonlyArray<Diagnostic> {
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => ReadonlyArray<T>,
cancellationToken: CancellationToken): ReadonlyArray<T> {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
@@ -1331,7 +1331,7 @@ namespace ts {
}));
}
function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<Diagnostic> {
function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<DiagnosticWithLocation> {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
@@ -1339,7 +1339,7 @@ namespace ts {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<Diagnostic> {
function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<DiagnosticWithLocation> {
const options = program.getCompilerOptions();
// collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
if (!sourceFile || options.out || options.outFile) {
@@ -1350,7 +1350,7 @@ namespace ts {
}
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray<Diagnostic> {
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray<DiagnosticWithLocation> {
// For JavaScript files, we report semantic errors for using TypeScript-only
// constructs from within a JavaScript file as syntactic errors.
if (isSourceFileJavaScript(sourceFile)) {
@@ -1377,19 +1377,19 @@ namespace ts {
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
noDiagnosticsTypeChecker = undefined!;
diagnosticsProducingTypeChecker = undefined!;
}
throw e;
}
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<Diagnostic> {
return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache);
}
function getSemanticDiagnosticsForFileNoCache(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
function getSemanticDiagnosticsForFileNoCache(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] | undefined {
return runWithCancellationToken(() => {
// If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
// If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
@@ -1406,15 +1406,22 @@ namespace ts {
// By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
const includeBindAndCheckDiagnostics = sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX ||
sourceFile.scriptKind === ScriptKind.External || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred;
const bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
const bindDiagnostics: ReadonlyArray<Diagnostic> = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray;
const checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
let diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
if (isCheckJs) {
diagnostics = concatenate(diagnostics, sourceFile.jsDocDiagnostics);
let diagnostics: Diagnostic[] | undefined;
for (const diags of [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]) {
if (diags) {
for (const diag of diags) {
if (shouldReportDiagnostic(diag)) {
diagnostics = append(diagnostics, diag);
}
}
}
}
return filter(diagnostics, shouldReportDiagnostic);
return diagnostics;
});
}
@@ -1425,7 +1432,7 @@ namespace ts {
const { file, start } = diagnostic;
if (file) {
const lineStarts = getLineStarts(file);
let { line } = computeLineAndCharacterOfPosition(lineStarts, start);
let { line } = computeLineAndCharacterOfPosition(lineStarts, start!); // TODO: GH#18217
while (line > 0) {
const previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
const result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
@@ -1443,9 +1450,9 @@ namespace ts {
return true;
}
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
const diagnostics: DiagnosticWithLocation[] = [];
let parent: Node = sourceFile;
walk(sourceFile);
@@ -1613,20 +1620,20 @@ namespace ts {
}
}
function createDiagnosticForNodeArray(nodes: NodeArray<Node>, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
function createDiagnosticForNodeArray(nodes: NodeArray<Node>, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): DiagnosticWithLocation {
const start = nodes.pos;
return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
}
// Since these are syntactic diagnostics, parent might not have been set
// this means the sourceFile cannot be infered from the node
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): DiagnosticWithLocation {
return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
}
});
}
function getDeclarationDiagnosticsWorker(sourceFile: SourceFile | undefined, cancellationToken: CancellationToken): Diagnostic[] {
function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<DiagnosticWithLocation> {
return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
}
@@ -1638,23 +1645,24 @@ namespace ts {
});
}
function getAndCacheDiagnostics(
function getAndCacheDiagnostics<T extends Diagnostic>(
sourceFile: SourceFile | undefined,
cancellationToken: CancellationToken,
cache: DiagnosticCache,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[]) {
cache: DiagnosticCache<T>,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => T[] | undefined,
): ReadonlyArray<T> {
const cachedResult = sourceFile
? cache.perFile && cache.perFile.get(sourceFile.path)
: cache.allDiagnostics;
: cache.allDiagnostics as T[];
if (cachedResult) {
return cachedResult;
}
const result = getDiagnostics(sourceFile, cancellationToken) || emptyArray;
const result = getDiagnostics(sourceFile!, cancellationToken) || emptyArray; // TODO: GH#18217
if (sourceFile) {
if (!cache.perFile) {
cache.perFile = createMap<Diagnostic[]>();
cache.perFile = createMap<T[]>();
}
cache.perFile.set(sourceFile.path, result);
}
@@ -1664,7 +1672,7 @@ namespace ts {
return result;
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray<DiagnosticWithLocation> {
return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
}
@@ -1710,8 +1718,8 @@ namespace ts {
// file.imports may not be undefined if there exists dynamic import
let imports: StringLiteralLike[] | undefined;
let moduleAugmentations: (StringLiteral | Identifier)[];
let ambientModules: string[];
let moduleAugmentations: (StringLiteral | Identifier)[] | undefined;
let ambientModules: string[] | undefined;
// If we are importing helpers, we need to add a synthetic reference to resolve the
// helpers library.
@@ -1862,7 +1870,7 @@ namespace ts {
/** This has side effects through `findSourceFile`. */
function processSourceFile(fileName: string, isDefaultLib: boolean, packageId: PackageId | undefined, refFile?: SourceFile, refPos?: number, refEnd?: number): void {
getSourceFileFromReferenceWorker(fileName,
fileName => findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId),
fileName => findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile!, refPos!, refEnd!, packageId), // TODO: GH#18217
(diagnostic, ...args) => {
fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined
? createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...args)
@@ -1888,12 +1896,12 @@ namespace ts {
redirect.redirectInfo = { redirectTarget, unredirected };
Object.defineProperties(redirect, {
id: {
get(this: SourceFile) { return this.redirectInfo.redirectTarget.id; },
set(this: SourceFile, value: SourceFile["id"]) { this.redirectInfo.redirectTarget.id = value; },
get(this: SourceFile) { return this.redirectInfo!.redirectTarget.id; },
set(this: SourceFile, value: SourceFile["id"]) { this.redirectInfo!.redirectTarget.id = value; },
},
symbol: {
get(this: SourceFile) { return this.redirectInfo.redirectTarget.symbol; },
set(this: SourceFile, value: SourceFile["symbol"]) { this.redirectInfo.redirectTarget.symbol = value; },
get(this: SourceFile) { return this.redirectInfo!.redirectTarget.symbol; },
set(this: SourceFile, value: SourceFile["symbol"]) { this.redirectInfo!.redirectTarget.symbol = value; },
},
});
return redirect;
@@ -1948,7 +1956,7 @@ namespace ts {
}
// We haven't looked for this file, do so now and cache result
const file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
const file = host.getSourceFile(fileName, options.target!, hostErrorMessage => { // TODO: GH#18217
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
@@ -1964,7 +1972,7 @@ namespace ts {
if (fileFromPackageId) {
// Some other SourceFile already exists with this package name and version.
// Instead of creating a duplicate, just redirect to the existing one.
const dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path);
const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path); // TODO: GH#18217
redirectTargetsSet.set(fileFromPackageId.path, true);
filesByName.set(path, dupFile);
sourceFileToPackageName.set(path, packageId.name);
@@ -1990,12 +1998,12 @@ namespace ts {
if (host.useCaseSensitiveFileNames()) {
const pathLowerCase = path.toLowerCase();
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
const existingFile = filesByNameIgnoreCase.get(pathLowerCase);
const existingFile = filesByNameIgnoreCase!.get(pathLowerCase);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
filesByNameIgnoreCase.set(pathLowerCase, file);
filesByNameIgnoreCase!.set(pathLowerCase, file);
}
}
@@ -2075,7 +2083,7 @@ namespace ts {
if (resolvedTypeReferenceDirective) {
if (resolvedTypeReferenceDirective.primary) {
// resolved from the primary path
processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd);
processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217
}
else {
// If we already resolved to this file, it must have been a secondary reference. Check file contents
@@ -2083,9 +2091,9 @@ namespace ts {
if (previousResolution) {
// Don't bother reading the file again if it's the same file.
if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName!);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName!)!.text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile!, refPos!, refEnd!, // TODO: GH#18217
Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict,
typeReferenceDirective,
resolvedTypeReferenceDirective.resolvedFileName,
@@ -2098,12 +2106,12 @@ namespace ts {
}
else {
// First resolution of this library
processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd);
processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd);
}
}
}
else {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
fileProcessingDiagnostics.add(createDiagnostic(refFile!, refPos!, refEnd!, Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217
}
if (saveResolution) {
@@ -2216,7 +2224,7 @@ namespace ts {
function parseProjectReferenceConfigFile(ref: ProjectReference): { commandLine: ParsedCommandLine, sourceFile: SourceFile } | undefined {
// The actual filename (i.e. add "/tsconfig.json" if necessary)
const refPath = resolveProjectReferencePath(host, ref);
const refPath = resolveProjectReferencePath(host, ref)!; // TODO: GH#18217
// An absolute path pointing to the containing directory of the config file
const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory());
const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile;
@@ -2229,14 +2237,14 @@ namespace ts {
}
function addProjectReferenceRedirects(referencedProject: ParsedCommandLine, target: Map<string>) {
const rootDir = normalizePath(referencedProject.options.rootDir || getDirectoryPath(referencedProject.options.configFilePath));
const rootDir = normalizePath(referencedProject.options.rootDir || getDirectoryPath(referencedProject.options.configFilePath!)); // TODO: GH#18217
target.set(rootDir, getDeclarationOutputDirectory(referencedProject));
}
function getDeclarationOutputDirectory(proj: ParsedCommandLine) {
return proj.options.declarationDir ||
proj.options.outDir ||
getDirectoryPath(proj.options.configFilePath);
getDirectoryPath(proj.options.configFilePath!); // TODO: GH#18217
}
function verifyCompilerOptions() {
@@ -2284,7 +2292,7 @@ namespace ts {
if (projectReferences) {
for (let i = 0; i < projectReferences.length; i++) {
const ref = projectReferences[i];
const resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
const resolvedRefOpts = resolvedProjectReferences![i] && resolvedProjectReferences![i]!.commandLine.options;
if (resolvedRefOpts === undefined) {
createDiagnosticForReference(i, Diagnostics.File_0_does_not_exist, ref.path);
continue;
@@ -2404,7 +2412,7 @@ namespace ts {
}
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator!);
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
}
@@ -2414,7 +2422,7 @@ namespace ts {
createDiagnosticForOptionName(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
}
else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator!);
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
@@ -2488,12 +2496,12 @@ namespace ts {
}
// Verify that all the emit files are unique and don't overwrite input files
function verifyEmitFilePath(emitFileName: string, emitFilesSeen: Map<true>) {
function verifyEmitFilePath(emitFileName: string | undefined, emitFilesSeen: Map<true>) {
if (emitFileName) {
const emitFilePath = toPath(emitFileName);
// Report error if the output overwrites input file
if (filesByName.has(emitFilePath)) {
let chain: DiagnosticMessageChain;
let chain: DiagnosticMessageChain | undefined;
if (!options.configFilePath) {
// The program is from either an inferred project or an external project
chain = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig);
@@ -2521,9 +2529,9 @@ namespace ts {
for (const pathProp of pathsSyntax) {
if (isObjectLiteralExpression(pathProp.initializer)) {
for (const keyProps of getPropertyAssignment(pathProp.initializer, key)) {
if (isArrayLiteralExpression(keyProps.initializer) &&
keyProps.initializer.elements.length > valueIndex) {
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2));
const initializer = keyProps.initializer;
if (isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile!, initializer.elements[valueIndex], message, arg0, arg1, arg2));
needCompilerDiagnostic = false;
}
}
@@ -2581,7 +2589,7 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1));
}
function createDiagnosticForOption(onKey: boolean, option1: string, option2: string, message: DiagnosticMessage, arg0: string | number, arg1?: string | number, arg2?: string | number) {
function createDiagnosticForOption(onKey: boolean, option1: string, option2: string | undefined, message: DiagnosticMessage, arg0: string | number, arg1?: string | number, arg2?: string | number) {
const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
const needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
!createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
@@ -2595,7 +2603,7 @@ namespace ts {
if (_referencesArrayLiteralSyntax === undefined) {
_referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
if (options.configFile) {
const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile);
const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile)!; // TODO: GH#18217
for (const prop of getPropertyAssignment(jsonObjectLiteral, "references")) {
if (isArrayLiteralExpression(prop.initializer)) {
_referencesArrayLiteralSyntax = prop.initializer;
@@ -2623,20 +2631,21 @@ namespace ts {
return _compilerOptionsObjectLiteralSyntax;
}
function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral: ObjectLiteralExpression, onKey: boolean, key1: string, key2: string, message: DiagnosticMessage, arg0: string | number, arg1?: string | number, arg2?: string | number): boolean {
function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral: ObjectLiteralExpression, onKey: boolean, key1: string, key2: string | undefined, message: DiagnosticMessage, arg0: string | number, arg1?: string | number, arg2?: string | number): boolean {
const props = getPropertyAssignment(objectLiteral, key1, key2);
for (const prop of props) {
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile!, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
}
return !!props.length;
}
function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral: ArrayLiteralExpression, index: number, message: DiagnosticMessage, arg0: string | number, arg1?: string | number, arg2?: string | number): boolean {
function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral: ArrayLiteralExpression, index: number, message: DiagnosticMessage, arg0: string | number | undefined, arg1?: string | number, arg2?: string | number): boolean {
if (arrayLiteral.elements.length <= index) {
// Out-of-bounds
return false;
}
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2));
programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile!, arrayLiteral.elements[index], message, arg0, arg1, arg2));
return false; // TODO: GH#18217 This function always returns `false`!`
}
function blockEmittingOfFile(emitFileName: string, diag: Diagnostic) {
@@ -2644,7 +2653,7 @@ namespace ts {
programDiagnostics.add(diag);
}
function isEmittedFile(file: string) {
function isEmittedFile(file: string): boolean {
if (options.noEmit) {
return false;
}
+31 -24
View File
@@ -3,9 +3,10 @@ namespace ts {
/** This is the cache of module/typedirectives resolution that can be retained across program */
export interface ResolutionCache {
startRecordingFilesWithChangedResolutions(): void;
finishRecordingFilesWithChangedResolutions(): Path[];
finishRecordingFilesWithChangedResolutions(): Path[] | undefined;
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[];
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined;
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
invalidateResolutionOfFile(filePath: Path): void;
@@ -73,15 +74,15 @@ namespace ts {
export const maxNumberOfFilesToIterateForInvalidation = 256;
type GetResolutionWithResolvedFileName<T extends ResolutionWithFailedLookupLocations = ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName = ResolutionWithResolvedFileName> =
(resolution: T) => R;
(resolution: T) => R | undefined;
export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string, logChangesWhenResolvingModule: boolean): ResolutionCache {
export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache {
let filesWithChangedSetOfUnresolvedImports: Path[] | undefined;
let filesWithInvalidatedResolutions: Map<true> | undefined;
let filesWithInvalidatedNonRelativeUnresolvedImports: Map<ReadonlyArray<string>> | undefined;
let allFilesHaveInvalidatedResolution = false;
const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory());
const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory!()); // TODO: GH#18217
const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
@@ -111,7 +112,7 @@ namespace ts {
const directoryWatchesOfFailedLookups = createMap<DirectoryWatchesOfFailedLookup>();
const rootDir = rootDirForResolution && removeTrailingDirectorySeparator(getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
const rootPath = rootDir && resolutionHost.toPath(rootDir);
const rootPath = (rootDir && resolutionHost.toPath(rootDir)) as Path; // TODO: GH#18217
// TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
const typeRootsWatches = createMap<FileWatcher>();
@@ -124,6 +125,7 @@ namespace ts {
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution,
resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives,
removeResolutionsOfFile,
invalidateResolutionOfFile,
@@ -142,7 +144,7 @@ namespace ts {
return resolution.resolvedTypeReferenceDirective;
}
function isInDirectoryPath(dir: Path, file: Path) {
function isInDirectoryPath(dir: Path | undefined, file: Path) {
if (dir === undefined || file.length <= dir.length) {
return false;
}
@@ -171,14 +173,14 @@ namespace ts {
return collected;
}
function isFileWithInvalidatedNonRelativeUnresolvedImports(path: Path) {
function isFileWithInvalidatedNonRelativeUnresolvedImports(path: Path): boolean {
if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
return false;
}
// Invalidated if file has unresolved imports
const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
return value && !!value.length;
return !!value && !!value.length;
}
function createHasInvalidatedResolution(forceAllFilesAsInvalidated?: boolean): HasInvalidatedResolution {
@@ -189,7 +191,7 @@ namespace ts {
}
const collected = filesWithInvalidatedResolutions;
filesWithInvalidatedResolutions = undefined;
return path => (collected && collected.has(path)) ||
return path => (!!collected && collected.has(path)) ||
isFileWithInvalidatedNonRelativeUnresolvedImports(path);
}
@@ -245,7 +247,7 @@ namespace ts {
logChanges: boolean): R[] {
const path = resolutionHost.toPath(containingFile);
const resolutionsInFile = cache.get(path) || cache.set(path, createMap()).get(path);
const resolutionsInFile = cache.get(path) || cache.set(path, createMap()).get(path)!;
const dirPath = getDirectoryPath(path);
let perDirectoryResolution = perDirectoryCache.get(dirPath);
if (!perDirectoryResolution) {
@@ -287,7 +289,7 @@ namespace ts {
}
Debug.assert(resolution !== undefined && !resolution.isInvalidated);
seenNamesInFile.set(name, true);
resolvedModules.push(getResolutionWithResolvedFileName(resolution));
resolvedModules.push(getResolutionWithResolvedFileName(resolution)!); // TODO: GH#18217
}
// Stop watching and remove the unused name
@@ -300,7 +302,7 @@ namespace ts {
return resolvedModules;
function resolutionIsEqualTo(oldResolution: T, newResolution: T): boolean {
function resolutionIsEqualTo(oldResolution: T | undefined, newResolution: T | undefined): boolean {
if (oldResolution === newResolution) {
return true;
}
@@ -320,7 +322,7 @@ namespace ts {
}
function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return resolveNamesWithLocalCache(
return resolveNamesWithLocalCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations, ResolvedTypeReferenceDirective>(
typeDirectiveNames, containingFile,
resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives,
resolveTypeReferenceDirective, getResolvedTypeReferenceDirective,
@@ -329,7 +331,7 @@ namespace ts {
}
function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[] {
return resolveNamesWithLocalCache(
return resolveNamesWithLocalCache<ResolvedModuleWithFailedLookupLocations, ResolvedModuleFull>(
moduleNames, containingFile,
resolvedModuleNames, perDirectoryResolvedModuleNames,
resolveModuleName, getResolvedModule,
@@ -337,6 +339,11 @@ namespace ts {
);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined {
const cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath: Path) {
return endsWith(dirPath, "/node_modules");
}
@@ -374,7 +381,7 @@ namespace ts {
function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch {
if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
return { dir: rootDir, dirPath: rootPath };
return { dir: rootDir!, dirPath: rootPath }; // TODO: GH#18217
}
return getDirectoryToWatchFromFailedLookupLocationDirectory(
@@ -450,7 +457,7 @@ namespace ts {
}
if (setAtRoot) {
setDirectoryWatcher(rootDir, rootPath);
setDirectoryWatcher(rootDir!, rootPath); // TODO: GH#18217
}
}
@@ -512,14 +519,14 @@ namespace ts {
}
function removeDirectoryWatcher(dirPath: string, subDirectory?: Path) {
const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath)!;
if (subDirectory) {
const existing = dirWatcher.subDirectoryMap.get(subDirectory);
const existing = dirWatcher.subDirectoryMap!.get(subDirectory)!;
if (existing === 1) {
dirWatcher.subDirectoryMap.delete(subDirectory);
dirWatcher.subDirectoryMap!.delete(subDirectory);
}
else {
dirWatcher.subDirectoryMap.set(subDirectory, existing - 1);
dirWatcher.subDirectoryMap!.set(subDirectory, existing - 1);
}
}
// Do not close the watcher yet since it might be needed by other failed lookup locations.
@@ -582,10 +589,10 @@ namespace ts {
seen.set(dirPath, seenInDir);
}
resolutions.forEach((resolution, name) => {
if (seenInDir.has(name)) {
if (seenInDir!.has(name)) {
return;
}
seenInDir.set(name, true);
seenInDir!.set(name, true);
if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) {
// Mark the file as needing re-evaluation of module resolution instead of using it blindly.
resolution.isInvalidated = true;
@@ -619,7 +626,7 @@ namespace ts {
// Resolution is invalidated if the resulting file name is same as the deleted file path
(resolution, getResolutionWithResolvedFileName) => {
const result = getResolutionWithResolvedFileName(resolution);
return result && resolutionHost.toPath(result.resolvedFileName) === filePath;
return !!result && resolutionHost.toPath(result.resolvedFileName!) === filePath; // TODO: GH#18217
}
);
}
@@ -682,7 +689,7 @@ namespace ts {
return rootPath;
}
const { dirPath, ignore } = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath;
return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined;
}
function createTypeRootsWatch(typeRootPath: Path, typeRoot: string): FileWatcher {
+29 -28
View File
@@ -37,8 +37,8 @@ namespace ts {
getText(): string;
// Sets the text for the scanner to scan. An optional subrange starting point and length
// can be provided to have the scanner only scan a portion of the text.
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
setText(text: string | undefined, start?: number, length?: number): void;
setOnError(onError: ErrorCallback | undefined): void;
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
@@ -266,14 +266,14 @@ namespace ts {
return false;
}
/* @internal */ export function isUnicodeIdentifierStart(code: number, languageVersion: ScriptTarget) {
return languageVersion >= ScriptTarget.ES5 ?
/* @internal */ export function isUnicodeIdentifierStart(code: number, languageVersion: ScriptTarget | undefined) {
return languageVersion! >= ScriptTarget.ES5 ?
lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
lookupInUnicodeMap(code, unicodeES3IdentifierStart);
}
function isUnicodeIdentifierPart(code: number, languageVersion: ScriptTarget) {
return languageVersion >= ScriptTarget.ES5 ?
function isUnicodeIdentifierPart(code: number, languageVersion: ScriptTarget | undefined) {
return languageVersion! >= ScriptTarget.ES5 ?
lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
lookupInUnicodeMap(code, unicodeES3IdentifierPart);
}
@@ -601,7 +601,7 @@ namespace ts {
}
function scanShebangTrivia(text: string, pos: number) {
const shebang = shebangTriviaRegex.exec(text)[0];
const shebang = shebangTriviaRegex.exec(text)![0];
pos = pos + shebang.length;
return pos;
}
@@ -626,11 +626,11 @@ namespace ts {
* @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
* return value of the callback.
*/
function iterateCommentRanges<T, U>(reduce: boolean, text: string, pos: number, trailing: boolean, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial?: U): U {
let pendingPos: number;
let pendingEnd: number;
let pendingKind: CommentKind;
let pendingHasTrailingNewLine: boolean;
function iterateCommentRanges<T, U>(reduce: boolean, text: string, pos: number, trailing: boolean, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U | undefined) => U, state: T, initial?: U): U | undefined {
let pendingPos!: number;
let pendingEnd!: number;
let pendingKind!: CommentKind;
let pendingHasTrailingNewLine!: boolean;
let hasPendingCommentRange = false;
let collecting = trailing || pos === 0;
let accumulator = initial;
@@ -769,20 +769,20 @@ namespace ts {
}
}
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierStart(ch, languageVersion);
}
export function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean {
export function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
export function isIdentifierText(name: string, languageVersion: ScriptTarget): boolean {
export function isIdentifierText(name: string, languageVersion: ScriptTarget | undefined): boolean {
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
}
@@ -800,13 +800,16 @@ namespace ts {
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
text?: string,
textInitial?: string,
onError?: ErrorCallback,
start?: number,
length?: number): Scanner {
let text = textInitial!;
// Current position (end position of text of current token)
let pos: number;
// end of text
let end: number;
@@ -817,7 +820,7 @@ namespace ts {
let tokenPos: number;
let token: SyntaxKind;
let tokenValue: string;
let tokenValue!: string;
let tokenFlags: TokenFlags;
setText(text, start, length);
@@ -907,8 +910,8 @@ namespace ts {
function scanNumber(): string {
const start = pos;
const mainFragment = scanNumberFragment();
let decimalFragment: string;
let scientificFragment: string;
let decimalFragment: string | undefined;
let scientificFragment: string | undefined;
if (text.charCodeAt(pos) === CharacterCodes.dot) {
pos++;
decimalFragment = scanNumberFragment();
@@ -1285,7 +1288,7 @@ namespace ts {
if (len >= 2 && len <= 11) {
const ch = tokenValue.charCodeAt(0);
if (ch >= CharacterCodes.a && ch <= CharacterCodes.z) {
token = textToToken.get(tokenValue);
token = textToToken.get(tokenValue)!;
if (token !== undefined) {
return token;
}
@@ -1305,7 +1308,7 @@ namespace ts {
let isPreviousTokenSeparator = false;
while (true) {
const ch = text.charCodeAt(pos);
// Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
// Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
if (ch === CharacterCodes._) {
tokenFlags |= TokenFlags.ContainsSeparator;
if (separatorAllowed) {
@@ -1928,13 +1931,11 @@ namespace ts {
}
function scanJSDocToken(): JsDocSyntaxKind {
startPos = tokenPos = pos;
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
}
startPos = pos;
tokenPos = pos;
const ch = text.charCodeAt(pos);
pos++;
switch (ch) {
@@ -2047,13 +2048,13 @@ namespace ts {
return text;
}
function setText(newText: string, start: number, length: number) {
function setText(newText: string | undefined, start: number | undefined, length: number | undefined) {
text = newText || "";
end = length === undefined ? text.length : start + length;
end = length === undefined ? text.length : start! + length;
setTextPos(start || 0);
}
function setOnError(errorCallback: ErrorCallback) {
function setOnError(errorCallback: ErrorCallback | undefined) {
onError = errorCallback;
}
@@ -2071,7 +2072,7 @@ namespace ts {
startPos = textPos;
tokenPos = textPos;
token = SyntaxKind.Unknown;
tokenValue = undefined;
tokenValue = undefined!;
tokenFlags = 0;
}
}
+27 -27
View File
@@ -8,7 +8,7 @@ namespace ts {
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFileOrBundle The input source file or bundle for the program.
*/
initialize(filePath: string, sourceMapFilePath: string, sourceFileOrBundle: SourceFile | Bundle, sourceMapOutput?: SourceMapData[]): void;
initialize(filePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, sourceMapOutput?: SourceMapData[]): void;
/**
* Reset the SourceMapWriter to an empty state.
@@ -90,13 +90,13 @@ namespace ts {
let sourceMapSourceIndex: number;
// Last recorded and encoded spans
let lastRecordedSourceMapSpan: SourceMapSpan;
let lastEncodedSourceMapSpan: SourceMapSpan;
let lastEncodedNameIndex: number;
let lastRecordedSourceMapSpan: SourceMapSpan | undefined;
let lastEncodedSourceMapSpan: SourceMapSpan | undefined;
let lastEncodedNameIndex: number | undefined;
// Source map data
let sourceMapData: SourceMapData;
let sourceMapDataList: SourceMapData[];
let sourceMapDataList: SourceMapData[] | undefined;
let disabled: boolean = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap);
return {
@@ -134,8 +134,8 @@ namespace ts {
}
sourceMapDataList = outputSourceMapDataList;
currentSource = undefined;
currentSourceText = undefined;
currentSource = undefined!;
currentSourceText = undefined!;
// Current source map file and its index in the sources list
sourceMapSourceIndex = -1;
@@ -148,7 +148,7 @@ namespace ts {
// Initialize source map data
sourceMapData = {
sourceMapFilePath,
jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined,
jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined!, // TODO: GH#18217
sourceMapFile: getBaseFileName(normalizeSlashes(filePath)),
sourceMapSourceRoot: compilerOptions.sourceRoot || "",
sourceMapSources: [],
@@ -206,14 +206,14 @@ namespace ts {
sourceMapDataList.push(sourceMapData);
}
currentSource = undefined;
sourceMapDir = undefined;
sourceMapSourceIndex = undefined;
currentSource = undefined!;
sourceMapDir = undefined!;
sourceMapSourceIndex = undefined!;
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = undefined!;
lastEncodedNameIndex = undefined;
sourceMapData = undefined;
sourceMapDataList = undefined;
sourceMapData = undefined!;
sourceMapDataList = undefined!;
}
// Encoding for sourcemap span
@@ -222,9 +222,9 @@ namespace ts {
return;
}
let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
let prevEncodedEmittedColumn = lastEncodedSourceMapSpan!.emittedColumn;
// Line/Comma delimiters
if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
if (lastEncodedSourceMapSpan!.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
// Emit comma to separate the entry
if (sourceMapData.sourceMapMappings) {
sourceMapData.sourceMapMappings += ",";
@@ -232,7 +232,7 @@ namespace ts {
}
else {
// Emit line delimiters
for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
for (let encodedLine = lastEncodedSourceMapSpan!.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
sourceMapData.sourceMapMappings += ";";
}
prevEncodedEmittedColumn = 1;
@@ -242,18 +242,18 @@ namespace ts {
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
// 2. Relative sourceIndex
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan!.sourceIndex);
// 3. Relative sourceLine 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan!.sourceLine);
// 4. Relative sourceColumn 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan!.sourceColumn);
// 5. Relative namePosition 0 based
if (lastRecordedSourceMapSpan.nameIndex >= 0) {
if (lastRecordedSourceMapSpan.nameIndex! >= 0) {
Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this");
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex! - lastEncodedNameIndex!);
lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
}
@@ -334,7 +334,7 @@ namespace ts {
if (node) {
const emitNode = node.emitNode;
const emitFlags = emitNode && emitNode.flags;
const emitFlags = emitNode && emitNode.flags || EmitFlags.None;
const range = emitNode && emitNode.sourceMapRange;
const { pos, end } = range || node;
let source = range && range.source;
@@ -386,7 +386,7 @@ namespace ts {
}
const emitNode = node && node.emitNode;
const emitFlags = emitNode && emitNode.flags;
const emitFlags = emitNode && emitNode.flags || EmitFlags.None;
const range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
tokenPos = skipSourceTrivia(range ? range.pos : tokenPos);
@@ -437,7 +437,7 @@ namespace ts {
sourceMapData.inputSourceFileNames.push(currentSource.fileName);
if (compilerOptions.inlineSources) {
sourceMapData.sourceMapSourcesContent.push(currentSource.text);
sourceMapData.sourceMapSourcesContent!.push(currentSource.text);
}
}
}
@@ -447,7 +447,7 @@ namespace ts {
*/
function getText() {
if (disabled) {
return;
return undefined!; // TODO: GH#18217
}
encodeLastRecordedSourceMapSpan();
@@ -468,7 +468,7 @@ namespace ts {
*/
function getSourceMappingURL() {
if (disabled) {
return;
return undefined!; // TODO: GH#18217
}
if (compilerOptions.inlineSourceMap) {
+8 -7
View File
@@ -8,8 +8,8 @@ namespace ts {
resolveStructuredTypeMembers: (type: ObjectType) => ResolvedType,
getTypeOfSymbol: (sym: Symbol) => Type,
getResolvedSymbol: (node: Node) => Symbol,
getIndexTypeOfStructuredType: (type: Type, kind: IndexKind) => Type,
getConstraintFromTypeParameter: (typeParameter: TypeParameter) => Type,
getIndexTypeOfStructuredType: (type: Type, kind: IndexKind) => Type | undefined,
getConstraintFromTypeParameter: (typeParameter: TypeParameter) => Type | undefined,
getFirstIdentifier: (node: EntityNameOrEntityNameExpression) => Identifier) {
return getSymbolWalker;
@@ -41,7 +41,7 @@ namespace ts {
},
};
function visitType(type: Type): void {
function visitType(type: Type | undefined): void {
if (!type) {
return;
}
@@ -157,13 +157,13 @@ namespace ts {
}
}
function visitSymbol(symbol: Symbol): boolean {
function visitSymbol(symbol: Symbol | undefined): boolean {
if (!symbol) {
return;
return false;
}
const symbolId = getSymbolId(symbol);
if (visitedSymbols[symbolId]) {
return;
return false;
}
visitedSymbols[symbolId] = symbol;
if (!accept(symbol)) {
@@ -172,7 +172,7 @@ namespace ts {
const t = getTypeOfSymbol(symbol);
visitType(t); // Should handle members on classes and such
if (symbol.flags & SymbolFlags.HasExports) {
symbol.exports.forEach(visitSymbol);
symbol.exports!.forEach(visitSymbol);
}
forEach(symbol.declarations, d => {
// Type queries are too far resolved when we just visit the symbol's type
@@ -185,6 +185,7 @@ namespace ts {
visitSymbol(entity);
}
});
return false;
}
}
}
+35 -23
View File
@@ -50,11 +50,11 @@ namespace ts {
/* @internal */
export function watchFileUsingPriorityPollingInterval(host: System, fileName: string, callback: FileWatcherCallback, watchPriority: PollingInterval): FileWatcher {
return host.watchFile(fileName, callback, pollingInterval(watchPriority));
return host.watchFile!(fileName, callback, pollingInterval(watchPriority));
}
/* @internal */
export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval) => FileWatcher;
export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval | undefined) => FileWatcher;
/* @internal */
export type HostWatchDirectory = (fileName: string, callback: DirectoryWatcherCallback, recursive?: boolean) => FileWatcher;
@@ -119,7 +119,7 @@ namespace ts {
return false;
function setLevel(level: keyof Levels) {
levels[level] = customLevels[level] || levels[level];
levels[level] = customLevels![level] || levels[level];
}
}
@@ -171,7 +171,7 @@ namespace ts {
}
function createPollingIntervalQueue(pollingInterval: PollingInterval): PollingIntervalQueue {
const queue = [] as PollingIntervalQueue;
const queue = [] as WatchedFile[] as PollingIntervalQueue;
queue.pollingInterval = pollingInterval;
queue.pollIndex = 0;
queue.pollScheduled = false;
@@ -203,7 +203,7 @@ namespace ts {
}
}
function pollQueue(queue: WatchedFile[], pollingInterval: PollingInterval, pollIndex: number, chunkSize: number) {
function pollQueue(queue: (WatchedFile | undefined)[], pollingInterval: PollingInterval, pollIndex: number, chunkSize: number) {
// Max visit would be all elements of the queue
let needsVisit = queue.length;
let definedValueCopyToIndex = pollIndex;
@@ -300,11 +300,11 @@ namespace ts {
}
function scheduleNextPoll(pollingInterval: PollingInterval) {
pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout!(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
}
function getModifiedTime(fileName: string) {
return host.getModifiedTime(fileName) || missingFileModifiedTime;
return host.getModifiedTime!(fileName) || missingFileModifiedTime;
}
}
@@ -369,7 +369,7 @@ namespace ts {
close: () => {
watcher.close();
result.childWatches.forEach(closeFileWatcher);
result = undefined;
result = undefined!;
},
dirName,
childWatches: emptyArray
@@ -423,6 +423,7 @@ namespace ts {
}
}
// TODO: GH#18217 Methods on System are often used as if they are certainly defined
export interface System {
args: string[];
newLine: string;
@@ -451,10 +452,11 @@ namespace ts {
setModifiedTime?(path: string, time: Date): void;
deleteFile?(path: string): void;
/**
* This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
/** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -482,7 +484,7 @@ namespace ts {
declare const global: any;
declare const __filename: string;
export function getNodeMajorVersion() {
export function getNodeMajorVersion(): number | undefined {
if (typeof process === "undefined") {
return undefined;
}
@@ -519,6 +521,7 @@ namespace ts {
getEnvironmentVariable?(name: string): string;
};
// TODO: this is used as if it's certainly defined in many places.
export let sys: System = (() => {
// NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
// byte order mark from the specified encoding. Using any other byte order mark does
@@ -530,7 +533,7 @@ namespace ts {
const _path = require("path");
const _os = require("os");
// crypto can be absent on reduced node installations
let _crypto: any;
let _crypto: typeof import("crypto") | undefined;
try {
_crypto = require("crypto");
}
@@ -544,7 +547,7 @@ namespace ts {
} = require("buffer").Buffer;
const nodeVersion = getNodeMajorVersion();
const isNode4OrLater = nodeVersion >= 4;
const isNode4OrLater = nodeVersion! >= 4;
const platform: string = _os.platform();
const useCaseSensitiveFileNames = isFileSystemCaseSensitive();
@@ -595,6 +598,7 @@ namespace ts {
setModifiedTime,
deleteFile,
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage() {
if (global.gc) {
global.gc();
@@ -635,12 +639,12 @@ namespace ts {
}
},
base64decode: Buffer.from ? input => {
return Buffer.from(input, "base64").toString("utf8");
return Buffer.from!(input, "base64").toString("utf8");
} : input => {
return new Buffer(input, "base64").toString("utf8");
},
base64encode: Buffer.from ? input => {
return Buffer.from(input).toString("base64");
return Buffer.from!(input).toString("base64");
} : input => {
return new Buffer(input).toString("base64");
}
@@ -715,6 +719,7 @@ namespace ts {
return watchDirectoryRecursively(directoryName, callback);
}
watchDirectory(directoryName, callback);
return undefined!; // TODO: GH#18217
};
}
@@ -751,7 +756,7 @@ namespace ts {
(_eventName: string, relativeFileName) => {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
const fileName = !isString(relativeFileName)
? undefined
? undefined! // TODO: GH#18217
: getNormalizedAbsolutePath(relativeFileName, dirName);
// Some applications save a working file via rename operations
const callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName));
@@ -841,7 +846,7 @@ namespace ts {
close: () => {
// Close the watcher (either existing file system entry watcher or missing file system entry watcher)
watcher.close();
watcher = undefined;
watcher = undefined!;
}
};
@@ -973,7 +978,7 @@ namespace ts {
data = byteOrderMarkIndicator + data;
}
let fd: number;
let fd: number | undefined;
try {
fd = _fs.openSync(fileName, "w");
@@ -1031,6 +1036,7 @@ namespace ts {
switch (entryKind) {
case FileSystemEntryKind.File: return stat.isFile();
case FileSystemEntryKind.Directory: return stat.isDirectory();
default: return false;
}
}
catch (e) {
@@ -1095,8 +1101,14 @@ namespace ts {
return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`;
}
function createMD5HashUsingNativeCrypto(data: string) {
const hash = _crypto.createHash("md5");
function createMD5HashUsingNativeCrypto(data: string): string {
const hash = _crypto!.createHash("md5");
hash.update(data);
return hash.digest("hex");
}
function createSHA256Hash(data: string): string {
const hash = _crypto!.createHash("sha256");
hash.update(data);
return hash.digest("hex");
}
@@ -1149,7 +1161,7 @@ namespace ts {
}
}
let sys: System;
let sys: System | undefined;
if (typeof ChakraHost !== "undefined") {
sys = getChakraSystem();
}
@@ -1163,13 +1175,13 @@ namespace ts {
const originalWriteFile = sys.writeFile;
sys.writeFile = (path, data, writeBom) => {
const directoryPath = getDirectoryPath(normalizeSlashes(path));
if (directoryPath && !sys.directoryExists(directoryPath)) {
recursiveCreateDirectory(directoryPath, sys);
if (directoryPath && !sys!.directoryExists(directoryPath)) {
recursiveCreateDirectory(directoryPath, sys!);
}
originalWriteFile.call(sys, path, data, writeBom);
};
}
return sys;
return sys!;
})();
if (sys && sys.getEnvironmentVariable) {
+15 -15
View File
@@ -78,7 +78,7 @@ namespace ts {
* @param transforms An array of `TransformerFactory` callbacks.
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
export function transformNodes<T extends Node>(resolver: EmitResolver, host: EmitHost, options: CompilerOptions, nodes: ReadonlyArray<T>, transformers: ReadonlyArray<TransformerFactory<T>>, allowDtsFiles: boolean): TransformationResult<T> {
export function transformNodes<T extends Node>(resolver: EmitResolver | undefined, host: EmitHost | undefined, options: CompilerOptions, nodes: ReadonlyArray<T>, transformers: ReadonlyArray<TransformerFactory<T>>, allowDtsFiles: boolean): TransformationResult<T> {
const enabledSyntaxKindFeatures = new Array<SyntaxKindFeatureFlags>(SyntaxKind.Count);
let lexicalEnvironmentVariableDeclarations: VariableDeclaration[];
let lexicalEnvironmentFunctionDeclarations: FunctionDeclaration[];
@@ -86,18 +86,18 @@ namespace ts {
let lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
let lexicalEnvironmentStackOffset = 0;
let lexicalEnvironmentSuspended = false;
let emitHelpers: EmitHelper[];
let emitHelpers: EmitHelper[] | undefined;
let onSubstituteNode: TransformationContext["onSubstituteNode"] = (_, node) => node;
let onEmitNode: TransformationContext["onEmitNode"] = (hint, node, callback) => callback(hint, node);
let state = TransformationState.Uninitialized;
const diagnostics: Diagnostic[] = [];
const diagnostics: DiagnosticWithLocation[] = [];
// The transformation context is provided to each transformer as part of transformer
// initialization.
const context: TransformationContext = {
getCompilerOptions: () => options,
getEmitResolver: () => resolver,
getEmitHost: () => host,
getEmitResolver: () => resolver!, // TODO: GH#18217
getEmitHost: () => host!, // TODO: GH#18217
startLexicalEnvironment,
suspendLexicalEnvironment,
resumeLexicalEnvironment,
@@ -270,8 +270,8 @@ namespace ts {
lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
lexicalEnvironmentStackOffset++;
lexicalEnvironmentVariableDeclarations = undefined;
lexicalEnvironmentFunctionDeclarations = undefined;
lexicalEnvironmentVariableDeclarations = undefined!;
lexicalEnvironmentFunctionDeclarations = undefined!;
}
/** Suspends the current lexical environment, usually after visiting a parameter list. */
@@ -294,12 +294,12 @@ namespace ts {
* Ends a lexical environment. The previous set of hoisted declarations are restored and
* any hoisted declarations added in this environment are returned.
*/
function endLexicalEnvironment(): Statement[] {
function endLexicalEnvironment(): Statement[] | undefined {
Debug.assert(state > TransformationState.Uninitialized, "Cannot modify the lexical environment during initialization.");
Debug.assert(state < TransformationState.Completed, "Cannot modify the lexical environment after transformation has completed.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
let statements: Statement[];
let statements: Statement[] | undefined;
if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
if (lexicalEnvironmentFunctionDeclarations) {
statements = [...lexicalEnvironmentFunctionDeclarations];
@@ -354,12 +354,12 @@ namespace ts {
}
// Release references to external entries for GC purposes.
lexicalEnvironmentVariableDeclarations = undefined;
lexicalEnvironmentVariableDeclarationsStack = undefined;
lexicalEnvironmentFunctionDeclarations = undefined;
lexicalEnvironmentFunctionDeclarationsStack = undefined;
onSubstituteNode = undefined;
onEmitNode = undefined;
lexicalEnvironmentVariableDeclarations = undefined!;
lexicalEnvironmentVariableDeclarationsStack = undefined!;
lexicalEnvironmentFunctionDeclarations = undefined!;
lexicalEnvironmentFunctionDeclarationsStack = undefined!;
onSubstituteNode = undefined!;
onEmitNode = undefined!;
emitHelpers = undefined;
// Prevent further use of the transformation result.
+53 -42
View File
@@ -1,6 +1,6 @@
/*@internal*/
namespace ts {
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): Diagnostic[] {
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined {
if (file && isSourceFileJavaScript(file)) {
return []; // No declaration diagnostics for js for now
}
@@ -32,28 +32,31 @@ namespace ts {
let needsScopeFixMarker = false;
let resultHasScopeMarker = false;
let enclosingDeclaration: Node;
let necessaryTypeRefernces: Map<true>;
let lateMarkedStatements: LateVisibilityPaintedStatement[];
let necessaryTypeRefernces: Map<true> | undefined;
let lateMarkedStatements: LateVisibilityPaintedStatement[] | undefined;
let lateStatementReplacementMap: Map<VisitResult<LateVisibilityPaintedStatement>>;
let suppressNewDiagnosticContexts: boolean;
const host = context.getEmitHost();
const symbolTracker: SymbolTracker = {
trackSymbol,
reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError,
reportPrivateInBaseOfClassExpression
reportPrivateInBaseOfClassExpression,
moduleResolverHost: host,
trackReferencedAmbientModule,
};
let errorNameNode: DeclarationName | undefined;
let currentSourceFile: SourceFile;
let refs: Map<SourceFile>;
const resolver = context.getEmitResolver();
const options = context.getCompilerOptions();
const newLine = getNewLineCharacter(options);
const { noResolve, stripInternal } = options;
const host = context.getEmitHost();
return transformRoot;
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void {
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[] | undefined): void {
if (!typeReferenceDirectives) {
return;
}
@@ -63,6 +66,11 @@ namespace ts {
}
}
function trackReferencedAmbientModule(node: ModuleDeclaration) {
const container = getSourceFileOfNode(node);
refs.set("" + getOriginalNodeId(container), container);
}
function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) {
// Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
@@ -143,7 +151,7 @@ namespace ts {
let hasNoDefaultLib = false;
const bundle = createBundle(map(node.sourceFiles,
sourceFile => {
if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return; // Omit declaration files from bundle results, too
if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217
hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib;
currentSourceFile = sourceFile;
enclosingDeclaration = sourceFile;
@@ -178,7 +186,7 @@ namespace ts {
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
bundle.hasNoDefaultLib = hasNoDefaultLib;
const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath!));
const referenceVisitor = mapReferencesIntoArray(bundle.syntheticFileReferences as FileReference[], outputFilePath);
refs.forEach(referenceVisitor);
return bundle;
@@ -197,13 +205,13 @@ namespace ts {
lateMarkedStatements = undefined;
lateStatementReplacementMap = createMap();
necessaryTypeRefernces = undefined;
const refs = collectReferences(currentSourceFile, createMap());
refs = collectReferences(currentSourceFile, createMap());
const references: FileReference[] = [];
const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath!));
const referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
refs.forEach(referenceVisitor);
const statements = visitNodes(node.statements, visitDeclarationStatements);
let combinedStatements = setTextRange(createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
refs.forEach(referenceVisitor);
const emittedImports = filter(combinedStatements, isAnyImportSyntax);
if (isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = setTextRange(createNodeArray([...combinedStatements, createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined)]), combinedStatements);
@@ -217,16 +225,18 @@ namespace ts {
function getFileReferenceForTypeName(typeName: string): FileReference | undefined {
// Elide type references for which we have imports
for (const importStatement of emittedImports) {
if (isImportEqualsDeclaration(importStatement) && isExternalModuleReference(importStatement.moduleReference)) {
const expr = importStatement.moduleReference.expression;
if (isStringLiteralLike(expr) && expr.text === typeName) {
if (emittedImports) {
for (const importStatement of emittedImports) {
if (isImportEqualsDeclaration(importStatement) && isExternalModuleReference(importStatement.moduleReference)) {
const expr = importStatement.moduleReference.expression;
if (isStringLiteralLike(expr) && expr.text === typeName) {
return undefined;
}
}
else if (isImportDeclaration(importStatement) && isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
return undefined;
}
}
else if (isImportDeclaration(importStatement) && isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
return undefined;
}
}
return { fileName: typeName, pos: -1, end: -1 };
}
@@ -294,7 +304,7 @@ namespace ts {
}
function ensureParameter(p: ParameterDeclaration, modifierMask?: ModifierFlags): ParameterDeclaration {
let oldDiag: typeof getSymbolAccessibilityDiagnostic;
let oldDiag: typeof getSymbolAccessibilityDiagnostic | undefined;
if (!suppressNewDiagnosticContexts) {
oldDiag = getSymbolAccessibilityDiagnostic;
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p);
@@ -310,7 +320,7 @@ namespace ts {
ensureNoInitializer(p)
);
if (!suppressNewDiagnosticContexts) {
getSymbolAccessibilityDiagnostic = oldDiag;
getSymbolAccessibilityDiagnostic = oldDiag!;
}
return newParam;
}
@@ -340,7 +350,7 @@ namespace ts {
| PropertyDeclaration
| PropertySignature;
function ensureType(node: HasInferredType, type: TypeNode, ignorePrivate?: boolean): TypeNode {
function ensureType(node: HasInferredType, type: TypeNode | undefined, ignorePrivate?: boolean): TypeNode | undefined {
if (!ignorePrivate && hasModifier(node, ModifierFlags.Private)) {
// Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
return;
@@ -417,7 +427,7 @@ namespace ts {
}
if (isBindingPattern(elem.name)) {
// If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
return forEach(elem.name.elements, getBindingNameVisible);
return some(elem.name.elements, getBindingNameVisible);
}
else {
return resolver.isDeclarationVisible(elem);
@@ -426,16 +436,16 @@ namespace ts {
function updateParamsList(node: Node, params: NodeArray<ParameterDeclaration>, modifierMask?: ModifierFlags) {
if (hasModifier(node, ModifierFlags.Private)) {
return undefined;
return undefined!; // TODO: GH#18217
}
const newParams = map(params, p => ensureParameter(p, modifierMask));
if (!newParams) {
return undefined;
return undefined!; // TODO: GH#18217
}
return createNodeArray(newParams, params.hasTrailingComma);
}
function ensureTypeParams(node: Node, params: NodeArray<TypeParameterDeclaration>) {
function ensureTypeParams(node: Node, params: NodeArray<TypeParameterDeclaration> | undefined) {
return hasModifier(node, ModifierFlags.Private) ? undefined : visitNodes(params, visitDeclarationSubtree);
}
@@ -463,8 +473,8 @@ namespace ts {
return setCommentRange(updated, getCommentRange(original));
}
function rewriteModuleSpecifier<T extends Node>(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode, input: T): T | StringLiteral {
if (!input) return;
function rewriteModuleSpecifier<T extends Node>(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode, input: T | undefined): T | StringLiteral {
if (!input) return undefined!; // TODO: GH#18217
resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== SyntaxKind.ModuleDeclaration && parent.kind !== SyntaxKind.ImportType);
if (input.kind === SyntaxKind.StringLiteral && isBundledEmit) {
const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
@@ -561,7 +571,7 @@ namespace ts {
// be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
// dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
while (length(lateMarkedStatements)) {
const i = lateMarkedStatements.shift();
const i = lateMarkedStatements!.shift()!;
if (!isLateVisibilityPaintedStatement(i)) {
return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[(i as any).kind] : (i as any).kind}`);
}
@@ -677,7 +687,8 @@ namespace ts {
const ctor = createSignatureDeclaration(
SyntaxKind.Constructor,
isPrivate ? undefined : ensureTypeParams(input, input.typeParameters),
isPrivate ? undefined : updateParamsList(input, input.parameters, ModifierFlags.None),
// TODO: GH#18217
isPrivate ? undefined! : updateParamsList(input, input.parameters, ModifierFlags.None),
/*type*/ undefined
);
ctor.modifiers = createNodeArray(ensureModifiers(input));
@@ -797,7 +808,7 @@ namespace ts {
return cleanup(visitEachChild(input, visitDeclarationSubtree, context));
function cleanup<T extends Node>(returnValue: T | undefined): T {
function cleanup<T extends Node>(returnValue: T | undefined): T | undefined {
if (returnValue && canProdiceDiagnostic && hasDynamicName(input as Declaration)) {
checkName(input as DeclarationDiagnosticProducing);
}
@@ -951,7 +962,7 @@ namespace ts {
needsDeclare = false;
visitNode(inner, visitDeclarationStatements);
// eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
const id = "" + getOriginalNodeId(inner);
const id = "" + getOriginalNodeId(inner!); // TODO: GH#18217
const body = lateStatementReplacementMap.get(id);
lateStatementReplacementMap.delete(id);
return cleanup(updateModuleDeclaration(
@@ -967,7 +978,7 @@ namespace ts {
const modifiers = createNodeArray(ensureModifiers(input, isPrivate));
const typeParameters = ensureTypeParams(input, input.typeParameters);
const ctor = getFirstConstructorWithBody(input);
let parameterProperties: PropertyDeclaration[];
let parameterProperties: PropertyDeclaration[] | undefined;
if (ctor) {
const oldDiag = getSymbolAccessibilityDiagnostic;
parameterProperties = compact(flatMap(ctor.parameters, param => {
@@ -988,7 +999,7 @@ namespace ts {
}
function walkBindingPattern(pattern: BindingPattern) {
let elems: PropertyDeclaration[];
let elems: PropertyDeclaration[] | undefined;
for (const elem of pattern.elements) {
if (isOmittedExpression(elem)) continue;
if (isBindingPattern(elem.name)) {
@@ -1015,7 +1026,7 @@ namespace ts {
if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== SyntaxKind.NullKeyword) {
// We must add a temporary declaration for the extends clause expression
const newId = createOptimisticUniqueName(`${unescapeLeadingUnderscores(input.name.escapedText)}_base`);
const newId = createOptimisticUniqueName(`${unescapeLeadingUnderscores(input.name!.escapedText)}_base`); // TODO: GH#18217
getSymbolAccessibilityDiagnostic = () => ({
diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
errorNode: extendsClause,
@@ -1041,7 +1052,7 @@ namespace ts {
typeParameters,
heritageClauses,
members
))];
))!]; // TODO: GH#18217
}
else {
const heritageClauses = transformHeritageClauses(input.heritageClauses);
@@ -1071,7 +1082,7 @@ namespace ts {
// Anything left unhandled is an error, so this should be unreachable
return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${(ts as any).SyntaxKind[(input as any).kind]}`);
function cleanup<T extends Node>(node: T | undefined): T {
function cleanup<T extends Node>(node: T | undefined): T | undefined {
if (isEnclosingDeclaration(input)) {
enclosingDeclaration = previousEnclosingDeclaration;
}
@@ -1115,7 +1126,7 @@ namespace ts {
}
function checkName(node: DeclarationDiagnosticProducing) {
let oldDiag: typeof getSymbolAccessibilityDiagnostic;
let oldDiag: typeof getSymbolAccessibilityDiagnostic | undefined;
if (!suppressNewDiagnosticContexts) {
oldDiag = getSymbolAccessibilityDiagnostic;
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node);
@@ -1126,7 +1137,7 @@ namespace ts {
const entityName = decl.name.expression;
checkEntityNameVisibility(entityName, enclosingDeclaration);
if (!suppressNewDiagnosticContexts) {
getSymbolAccessibilityDiagnostic = oldDiag;
getSymbolAccessibilityDiagnostic = oldDiag!;
}
errorNameNode = undefined;
}
@@ -1146,7 +1157,7 @@ namespace ts {
return false;
}
function ensureModifiers(node: Node, privateDeclaration?: boolean): ReadonlyArray<Modifier> {
function ensureModifiers(node: Node, privateDeclaration?: boolean): ReadonlyArray<Modifier> | undefined {
const currentFlags = getModifierFlags(node);
const newFlags = ensureModifierFlags(node, privateDeclaration);
if (currentFlags === newFlags) {
@@ -1201,7 +1212,7 @@ namespace ts {
return prop;
}
function transformHeritageClauses(nodes: NodeArray<HeritageClause>) {
function transformHeritageClauses(nodes: NodeArray<HeritageClause> | undefined) {
return createNodeArray(filter(map(nodes, clause => updateHeritageClause(clause, visitNodes(createNodeArray(filter(clause.types, t => {
return isEntityNameExpression(t.expression) || (clause.token === SyntaxKind.ExtendsKeyword && t.expression.kind === SyntaxKind.NullKeyword);
})), visitDeclarationSubtree))), clause => clause.types && !!clause.types.length));
@@ -1228,7 +1239,7 @@ namespace ts {
return flags;
}
function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode {
function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode | undefined {
if (accessor) {
return accessor.kind === SyntaxKind.GetAccessor
? accessor.type // Getter - return type
@@ -1325,4 +1336,4 @@ namespace ts {
}
return false;
}
}
}
@@ -90,7 +90,7 @@ namespace ts {
}
}
function getMethodNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
function getMethodNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic | undefined {
const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
@@ -122,7 +122,7 @@ namespace ts {
}
}
export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing) {
export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined {
if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
@@ -151,7 +151,7 @@ namespace ts {
return getTypeAliasDeclarationVisibilityError;
}
else {
Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${(ts as any).SyntaxKind[(node as any).kind]}`);
return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${(ts as any).SyntaxKind[(node as any).kind]}`);
}
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) {
@@ -190,7 +190,7 @@ namespace ts {
}
}
function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic | undefined {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
@@ -233,7 +233,7 @@ namespace ts {
}
return {
diagnosticMessage,
errorNode: (node as NamedDeclaration).name,
errorNode: (node as NamedDeclaration).name!,
typeName: (node as NamedDeclaration).name
};
}
@@ -295,7 +295,7 @@ namespace ts {
break;
default:
Debug.fail("This is unknown kind for signature: " + node.kind);
return Debug.fail("This is unknown kind for signature: " + node.kind);
}
return {
@@ -304,7 +304,7 @@ namespace ts {
};
}
function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic | undefined {
const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
@@ -373,7 +373,7 @@ namespace ts {
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
default:
Debug.fail(`Unknown parent for parameter: ${(ts as any).SyntaxKind[node.parent.kind]}`);
return Debug.fail(`Unknown parent for parameter: ${(ts as any).SyntaxKind[node.parent.kind]}`);
}
}
@@ -419,7 +419,7 @@ namespace ts {
break;
default:
Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
return Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
}
return {
+23 -23
View File
@@ -6,7 +6,7 @@ namespace ts {
downlevelIteration: boolean;
hoistTempVariables: boolean;
emitExpression: (value: Expression) => void;
emitBindingOrAssignment: (target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) => void;
emitBindingOrAssignment: (target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node | undefined) => void;
createArrayBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ArrayBindingOrAssignmentPattern;
createObjectBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ObjectBindingOrAssignmentPattern;
createArrayBindingOrAssignmentElement: (node: Identifier) => BindingOrAssignmentElement;
@@ -37,7 +37,7 @@ namespace ts {
needsValue?: boolean,
createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression {
let location: TextRange = node;
let value: Expression;
let value: Expression | undefined;
if (isDestructuringAssignment(node)) {
value = node.right;
while (isEmptyArrayLiteral(node.left) || isEmptyObjectLiteral(node.left)) {
@@ -51,11 +51,11 @@ namespace ts {
}
}
let expressions: Expression[];
let expressions: Expression[] | undefined;
const flattenContext: FlattenContext = {
context,
level,
downlevelIteration: context.getCompilerOptions().downlevelIteration,
downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
hoistTempVariables: true,
emitExpression,
emitBindingOrAssignment,
@@ -103,7 +103,7 @@ namespace ts {
expressions.push(value);
}
return aggregateTransformFlags(inlineExpressions(expressions)) || createOmittedExpression();
return aggregateTransformFlags(inlineExpressions(expressions!)) || createOmittedExpression();
function emitExpression(expression: Expression) {
// NOTE: this completely disables source maps, but aligns with the behavior of
@@ -127,7 +127,7 @@ namespace ts {
}
function bindingOrAssignmentElementAssignsToName(element: BindingOrAssignmentElement, escapedName: __String): boolean {
const target = getTargetOfBindingOrAssignmentElement(element);
const target = getTargetOfBindingOrAssignmentElement(element)!; // TODO: GH#18217
if (isBindingOrAssignmentPattern(target)) {
return bindingOrAssignmentPatternAssignsToName(target, escapedName);
}
@@ -164,15 +164,15 @@ namespace ts {
context: TransformationContext,
level: FlattenLevel,
rval?: Expression,
hoistTempVariables?: boolean,
hoistTempVariables = false,
skipInitializer?: boolean): VariableDeclaration[] {
let pendingExpressions: Expression[];
let pendingExpressions: Expression[] | undefined;
const pendingDeclarations: { pendingExpressions?: Expression[], name: BindingName, value: Expression, location?: TextRange, original?: Node; }[] = [];
const declarations: VariableDeclaration[] = [];
const flattenContext: FlattenContext = {
context,
level,
downlevelIteration: context.getCompilerOptions().downlevelIteration,
downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
hoistTempVariables,
emitExpression,
emitBindingOrAssignment,
@@ -202,7 +202,7 @@ namespace ts {
}
else {
context.hoistVariableDeclaration(temp);
const pendingDeclaration = lastOrUndefined(pendingDeclarations);
const pendingDeclaration = last(pendingDeclarations);
pendingDeclaration.pendingExpressions = append(
pendingDeclaration.pendingExpressions,
createAssignment(temp, pendingDeclaration.value)
@@ -231,7 +231,7 @@ namespace ts {
pendingExpressions = append(pendingExpressions, value);
}
function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) {
function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange | undefined, original: Node | undefined) {
Debug.assertNode(target, isBindingName);
if (pendingExpressions) {
value = inlineExpressions(append(pendingExpressions, value));
@@ -268,15 +268,15 @@ namespace ts {
value = createVoidZero();
}
}
const bindingTarget = getTargetOfBindingOrAssignmentElement(element);
const bindingTarget = getTargetOfBindingOrAssignmentElement(element)!; // TODO: GH#18217
if (isObjectBindingOrAssignmentPattern(bindingTarget)) {
flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value!, location);
}
else if (isArrayBindingOrAssignmentPattern(bindingTarget)) {
flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value!, location);
}
else {
flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element);
flattenContext.emitBindingOrAssignment(bindingTarget, value!, location, /*original*/ element); // TODO: GH#18217
}
}
@@ -300,15 +300,15 @@ namespace ts {
const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0;
value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
}
let bindingElements: BindingOrAssignmentElement[];
let computedTempVariables: Expression[];
let bindingElements: BindingOrAssignmentElement[] | undefined;
let computedTempVariables: Expression[] | undefined;
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (!getRestIndicatorOfBindingOrAssignmentElement(element)) {
const propertyName = getPropertyNameOfBindingOrAssignmentElement(element);
const propertyName = getPropertyNameOfBindingOrAssignmentElement(element)!;
if (flattenContext.level >= FlattenLevel.ObjectRest
&& !(element.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest))
&& !(getTargetOfBindingOrAssignmentElement(element).transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest))
&& !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRest | TransformFlags.ContainsObjectRest))
&& !isComputedPropertyName(propertyName)) {
bindingElements = append(bindingElements, element);
}
@@ -319,7 +319,7 @@ namespace ts {
}
const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
if (isComputedPropertyName(propertyName)) {
computedTempVariables = append(computedTempVariables, (rhsValue as ElementAccessExpression).argumentExpression);
computedTempVariables = append<Expression>(computedTempVariables, (rhsValue as ElementAccessExpression).argumentExpression);
}
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
}
@@ -329,7 +329,7 @@ namespace ts {
flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
bindingElements = undefined;
}
const rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern);
const rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables!, pattern); // TODO: GH#18217
flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
}
}
@@ -377,8 +377,8 @@ namespace ts {
const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0;
value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
}
let bindingElements: BindingOrAssignmentElement[];
let restContainingElements: [Identifier, BindingOrAssignmentElement][];
let bindingElements: BindingOrAssignmentElement[] | undefined;
let restContainingElements: [Identifier, BindingOrAssignmentElement][] | undefined;
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (flattenContext.level >= FlattenLevel.ObjectRest) {
+109 -110
View File
@@ -159,7 +159,7 @@ namespace ts {
ReplaceWithReturn,
}
type LoopConverter = (node: IterationStatement, outermostLabeledStatement: LabeledStatement, convertedLoopBodyStatements: Statement[]) => Statement;
type LoopConverter = (node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convertedLoopBodyStatements: Statement[] | undefined) => Statement;
// Facts we track as we traverse the tree
const enum HierarchyFacts {
@@ -286,7 +286,7 @@ namespace ts {
/**
* Used to track if we are emitting body of the converted loop
*/
let convertedLoopState: ConvertedLoopState;
let convertedLoopState: ConvertedLoopState | undefined;
/**
* Keeps track of whether substitutions have been enabled for specific cases.
@@ -308,9 +308,9 @@ namespace ts {
const visited = visitSourceFile(node);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
currentText = undefined;
taggedTemplateStringDeclarations = undefined;
currentSourceFile = undefined!;
currentText = undefined!;
taggedTemplateStringDeclarations = undefined!;
hierarchyFacts = HierarchyFacts.None;
return visited;
}
@@ -338,7 +338,7 @@ namespace ts {
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean {
return hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper
return (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper) !== 0
&& node.kind === SyntaxKind.ReturnStatement
&& !(<ReturnStatement>node).expression;
}
@@ -520,7 +520,7 @@ namespace ts {
const ancestorFacts = enterSubtree(HierarchyFacts.SourceFileExcludes, HierarchyFacts.SourceFileIncludes);
const statements: Statement[] = [];
startLexicalEnvironment();
let statementOffset = addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
let statementOffset: number | undefined = addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
addCaptureThisForNodeIfNeeded(statements, node);
statementOffset = addCustomPrologue(statements, node.statements, statementOffset, visitor);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
@@ -541,7 +541,7 @@ namespace ts {
if (convertedLoopState !== undefined) {
const savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
// for switch statement allow only non-labeled break
convertedLoopState.allowedNonLabeledJumps |= Jump.Break;
convertedLoopState.allowedNonLabeledJumps! |= Jump.Break;
const result = visitEachChild(node, visitor, context);
convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
return result;
@@ -562,7 +562,7 @@ namespace ts {
function visitReturnStatement(node: ReturnStatement): Statement {
if (convertedLoopState) {
convertedLoopState.nonLocalJumps |= Jump.Return;
convertedLoopState.nonLocalJumps! |= Jump.Return;
if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
node = returnCapturedThis(node);
}
@@ -619,45 +619,46 @@ namespace ts {
const jump = node.kind === SyntaxKind.BreakStatement ? Jump.Break : Jump.Continue;
const canUseBreakOrContinue =
(node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label))) ||
(!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
(!node.label && (convertedLoopState.allowedNonLabeledJumps! & jump));
if (!canUseBreakOrContinue) {
let labelMarker: string;
if (!node.label) {
const label = node.label;
if (!label) {
if (node.kind === SyntaxKind.BreakStatement) {
convertedLoopState.nonLocalJumps |= Jump.Break;
convertedLoopState.nonLocalJumps! |= Jump.Break;
labelMarker = "break";
}
else {
convertedLoopState.nonLocalJumps |= Jump.Continue;
convertedLoopState.nonLocalJumps! |= Jump.Continue;
// note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
labelMarker = "continue";
}
}
else {
if (node.kind === SyntaxKind.BreakStatement) {
labelMarker = `break-${node.label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ true, idText(node.label), labelMarker);
labelMarker = `break-${label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ true, idText(label), labelMarker);
}
else {
labelMarker = `continue-${node.label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ false, idText(node.label), labelMarker);
labelMarker = `continue-${label.escapedText}`;
setLabeledJump(convertedLoopState, /*isBreak*/ false, idText(label), labelMarker);
}
}
let returnExpression: Expression = createLiteral(labelMarker);
if (convertedLoopState.loopOutParameters.length) {
const outParams = convertedLoopState.loopOutParameters;
let expr: Expression;
if (convertedLoopState.loopOutParameters!.length) {
const outParams = convertedLoopState.loopOutParameters!;
let expr: Expression | undefined;
for (let i = 0; i < outParams.length; i++) {
const copyExpr = copyOutParameter(outParams[i], CopyDirection.ToOutParameter);
if (i === 0) {
expr = copyExpr;
}
else {
expr = createBinary(expr, SyntaxKind.CommaToken, copyExpr);
expr = createBinary(expr!, SyntaxKind.CommaToken, copyExpr);
}
}
returnExpression = createBinary(expr, SyntaxKind.CommaToken, returnExpression);
returnExpression = createBinary(expr!, SyntaxKind.CommaToken, returnExpression);
}
return createReturn(returnExpression);
}
@@ -814,7 +815,7 @@ namespace ts {
* @param node A ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function transformClassBody(node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments): Block {
function transformClassBody(node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): Block {
const statements: Statement[] = [];
startLexicalEnvironment();
addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
@@ -850,7 +851,7 @@ namespace ts {
* @param node The ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function addExtendsHelperIfNeeded(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments): void {
function addExtendsHelperIfNeeded(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): void {
if (extendsClauseElement) {
statements.push(
setTextRange(
@@ -870,7 +871,7 @@ namespace ts {
* @param node The ClassExpression or ClassDeclaration node.
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function addConstructor(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments): void {
function addConstructor(statements: Statement[], node: ClassExpression | ClassDeclaration, extendsClauseElement: ExpressionWithTypeArguments | undefined): void {
const savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
const ancestorFacts = enterSubtree(HierarchyFacts.ConstructorExcludes, HierarchyFacts.ConstructorIncludes);
@@ -904,13 +905,13 @@ namespace ts {
* @param hasSynthesizedSuper A value indicating whether the constructor starts with a
* synthesized `super` call.
*/
function transformConstructorParameters(constructor: ConstructorDeclaration, hasSynthesizedSuper: boolean) {
function transformConstructorParameters(constructor: ConstructorDeclaration | undefined, hasSynthesizedSuper: boolean) {
// If the TypeScript transformer needed to synthesize a constructor for property
// initializers, it would have also added a synthetic `...args` parameter and
// `super` call.
// If this is the case, we do not include the synthetic `...args` parameter and
// will instead use the `arguments` object in ES5/3.
return visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context)
return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| <ParameterDeclaration[]>[];
}
@@ -923,7 +924,7 @@ namespace ts {
* @param hasSynthesizedSuper A value indicating whether the constructor starts with a
* synthesized `super` call.
*/
function transformConstructorBody(constructor: ConstructorDeclaration | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments, hasSynthesizedSuper: boolean) {
function transformConstructorBody(constructor: ConstructorDeclaration | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments | undefined, hasSynthesizedSuper: boolean) {
const statements: Statement[] = [];
resumeLexicalEnvironment();
@@ -935,7 +936,7 @@ namespace ts {
statementOffset = 0;
}
else if (constructor) {
statementOffset = addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
statementOffset = addStandardPrologue(statements, constructor.body!.statements, /*ensureUseStrict*/ false);
}
if (constructor) {
@@ -943,7 +944,7 @@ namespace ts {
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
if (!hasSynthesizedSuper) {
// If no super call has been synthesized, emit custom prologue directives.
statementOffset = addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
statementOffset = addCustomPrologue(statements, constructor.body!.statements, statementOffset, visitor);
}
Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
@@ -951,7 +952,7 @@ namespace ts {
// determine whether the class is known syntactically to be a derived class (e.g. a
// class that extends a value that is not syntactically known to be `null`).
const isDerivedClass = extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword;
const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword;
const superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
// The last statement expression was replaced. Skip it.
@@ -964,14 +965,14 @@ namespace ts {
hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper;
}
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset));
addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, /*start*/ statementOffset));
}
// Return `_this` unless we're sure enough that it would be pointless to add a return statement.
// If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
if (isDerivedClass
&& superCaptureStatus !== SuperCaptureResult.ReplaceWithReturn
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body!))) {
statements.push(
createReturn(
createFileLevelUniqueName("_this")
@@ -990,7 +991,7 @@ namespace ts {
createNodeArray(
statements
),
/*location*/ constructor ? constructor.body.statements : node.members
/*location*/ constructor ? constructor.body!.statements : node.members
),
/*multiLine*/ true
);
@@ -1085,10 +1086,10 @@ namespace ts {
//
// return _super.call(...) || this;
//
let firstStatement: Statement;
let superCallExpression: Expression;
let firstStatement: Statement | undefined;
let superCallExpression: Expression | undefined;
const ctorStatements = ctor.body.statements;
const ctorStatements = ctor.body!.statements;
if (statementOffset < ctorStatements.length) {
firstStatement = ctorStatements[statementOffset];
@@ -1156,7 +1157,7 @@ namespace ts {
*
* @param node A ParameterDeclaration node.
*/
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
function visitParameter(node: ParameterDeclaration): ParameterDeclaration | undefined {
if (node.dotDotDotToken) {
// rest parameters are elided
return undefined;
@@ -1251,7 +1252,7 @@ namespace ts {
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
function addDefaultValueAssignmentForBindingPattern(statements: Statement[], parameter: ParameterDeclaration, name: BindingPattern, initializer: Expression): void {
function addDefaultValueAssignmentForBindingPattern(statements: Statement[], parameter: ParameterDeclaration, name: BindingPattern, initializer: Expression | undefined): void {
const temp = getGeneratedNameForNode(parameter);
// In cases where a binding pattern is simply '[]' or '{}',
@@ -1339,7 +1340,7 @@ namespace ts {
* part of a constructor declaration with a
* synthesized call to `super`
*/
function shouldAddRestParameter(node: ParameterDeclaration, inConstructorWithSynthesizedSuper: boolean) {
function shouldAddRestParameter(node: ParameterDeclaration | undefined, inConstructorWithSynthesizedSuper: boolean) {
return node && node.dotDotDotToken && node.name.kind === SyntaxKind.Identifier && !inConstructorWithSynthesizedSuper;
}
@@ -1359,11 +1360,11 @@ namespace ts {
}
// `declarationName` is the name of the local declaration for the parameter.
const declarationName = getMutableClone(<Identifier>parameter.name);
const declarationName = getMutableClone(<Identifier>parameter!.name);
setEmitFlags(declarationName, EmitFlags.NoSourceMap);
// `expressionName` is the name of the parameter used in expressions.
const expressionName = getSynthesizedClone(<Identifier>parameter.name);
const expressionName = getSynthesizedClone(<Identifier>parameter!.name);
const restIndex = node.parameters.length - 1;
const temp = createLoopVariable();
@@ -1640,7 +1641,7 @@ namespace ts {
// arguments are both mapped contiguously to the accessor name.
const target = getMutableClone(receiver);
setEmitFlags(target, EmitFlags.NoComments | EmitFlags.NoTrailingSourceMap);
setSourceMapRange(target, firstAccessor.name);
setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217
const propertyName = createExpressionForPropertyName(visitNode(firstAccessor.name, visitor, isPropertyName));
setEmitFlags(propertyName, EmitFlags.NoComments | EmitFlags.NoLeadingSourceMap);
@@ -1789,7 +1790,7 @@ namespace ts {
* @param location The source-map location for the new FunctionExpression.
* @param name The name of the new FunctionExpression.
*/
function transformFunctionLikeToExpression(node: FunctionLikeDeclaration, location: TextRange, name: Identifier, container: Node): FunctionExpression {
function transformFunctionLikeToExpression(node: FunctionLikeDeclaration, location: TextRange | undefined, name: Identifier | undefined, container: Node | undefined): FunctionExpression {
const savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
const ancestorFacts = container && isClassLike(container) && !hasModifier(node, ModifierFlags.Static)
@@ -1829,11 +1830,11 @@ namespace ts {
let multiLine = false; // indicates whether the block *must* be emitted as multiple lines
let singleLine = false; // indicates whether the block *may* be emitted as a single line
let statementsLocation: TextRange;
let closeBraceLocation: TextRange;
let closeBraceLocation: TextRange | undefined;
const statements: Statement[] = [];
const body = node.body;
let statementOffset: number;
const body = node.body!;
let statementOffset: number | undefined;
resumeLexicalEnvironment();
if (isBlock(body)) {
@@ -1885,6 +1886,7 @@ namespace ts {
const expression = visitNode(body, visitor, isExpression);
const returnStatement = createReturn(expression);
setTextRange(returnStatement, body);
moveSyntheticComments(returnStatement, body);
setEmitFlags(returnStatement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTrailingComments);
statements.push(returnStatement);
@@ -1918,7 +1920,7 @@ namespace ts {
}
function visitFunctionBodyDownLevel(node: FunctionDeclaration | FunctionExpression | AccessorDeclaration) {
const updated = visitFunctionBody(node.body, functionBodyVisitor, context);
const updated = visitFunctionBody(node.body, functionBodyVisitor, context)!;
return updateBlock(
updated,
setTextRange(
@@ -2002,12 +2004,12 @@ namespace ts {
return visitEachChild(node, visitor, context);
}
function visitVariableStatement(node: VariableStatement): Statement {
function visitVariableStatement(node: VariableStatement): Statement | undefined {
const ancestorFacts = enterSubtree(HierarchyFacts.None, hasModifier(node, ModifierFlags.Export) ? HierarchyFacts.ExportedVariableStatement : HierarchyFacts.None);
let updated: Statement;
let updated: Statement | undefined;
if (convertedLoopState && (node.declarationList.flags & NodeFlags.BlockScoped) === 0) {
// we are inside a converted loop - hoist variable declarations
let assignments: Expression[];
let assignments: Expression[] | undefined;
for (const decl of node.declarationList.declarations) {
hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
if (decl.initializer) {
@@ -2065,13 +2067,12 @@ namespace ts {
setCommentRange(declarationList, node);
if (node.transformFlags & TransformFlags.ContainsBindingPattern
&& (isBindingPattern(node.declarations[0].name) || isBindingPattern(lastOrUndefined(node.declarations).name))) {
&& (isBindingPattern(node.declarations[0].name) || isBindingPattern(last(node.declarations).name))) {
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
const firstDeclaration = firstOrUndefined(declarations);
if (firstDeclaration) {
const lastDeclaration = lastOrUndefined(declarations);
setSourceMapRange(declarationList, createRange(firstDeclaration.pos, lastDeclaration.end));
setSourceMapRange(declarationList, createRange(firstDeclaration.pos, last(declarations).end));
}
}
@@ -2197,11 +2198,11 @@ namespace ts {
}
function recordLabel(node: LabeledStatement) {
convertedLoopState.labels.set(idText(node.label), true);
convertedLoopState!.labels!.set(idText(node.label), true);
}
function resetLabel(node: LabeledStatement) {
convertedLoopState.labels.set(idText(node.label), false);
convertedLoopState!.labels!.set(idText(node.label), false);
}
function visitLabeledStatement(node: LabeledStatement): VisitResult<Statement> {
@@ -2228,14 +2229,14 @@ namespace ts {
}
}
function visitIterationStatementWithFacts(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts, node: IterationStatement, outermostLabeledStatement: LabeledStatement, convert?: LoopConverter) {
function visitIterationStatementWithFacts(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts, node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter) {
const ancestorFacts = enterSubtree(excludeFacts, includeFacts);
const updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert);
exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None);
return updated;
}
function visitDoOrWhileStatement(node: DoStatement | WhileStatement, outermostLabeledStatement: LabeledStatement) {
function visitDoOrWhileStatement(node: DoStatement | WhileStatement, outermostLabeledStatement: LabeledStatement | undefined) {
return visitIterationStatementWithFacts(
HierarchyFacts.DoOrWhileStatementExcludes,
HierarchyFacts.DoOrWhileStatementIncludes,
@@ -2243,7 +2244,7 @@ namespace ts {
outermostLabeledStatement);
}
function visitForStatement(node: ForStatement, outermostLabeledStatement: LabeledStatement) {
function visitForStatement(node: ForStatement, outermostLabeledStatement: LabeledStatement | undefined) {
return visitIterationStatementWithFacts(
HierarchyFacts.ForStatementExcludes,
HierarchyFacts.ForStatementIncludes,
@@ -2251,7 +2252,7 @@ namespace ts {
outermostLabeledStatement);
}
function visitForInStatement(node: ForInStatement, outermostLabeledStatement: LabeledStatement) {
function visitForInStatement(node: ForInStatement, outermostLabeledStatement: LabeledStatement | undefined) {
return visitIterationStatementWithFacts(
HierarchyFacts.ForInOrForOfStatementExcludes,
HierarchyFacts.ForInOrForOfStatementIncludes,
@@ -2259,7 +2260,7 @@ namespace ts {
outermostLabeledStatement);
}
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement): VisitResult<Statement> {
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult<Statement> {
return visitIterationStatementWithFacts(
HierarchyFacts.ForInOrForOfStatementExcludes,
HierarchyFacts.ForInOrForOfStatementIncludes,
@@ -2270,12 +2271,13 @@ namespace ts {
function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression, convertedLoopBodyStatements: Statement[]) {
const statements: Statement[] = [];
if (isVariableDeclarationList(node.initializer)) {
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
if (node.initializer.flags & NodeFlags.BlockScoped) {
enableSubstitutionsForBlockScopedBindings();
}
const firstOriginalDeclaration = firstOrUndefined(node.initializer.declarations);
const firstOriginalDeclaration = firstOrUndefined(initializer.declarations);
if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) {
// This works whether the declaration is a var, let, or const.
// It will use rhsIterationValue _a[_i] as the initializer.
@@ -2292,9 +2294,7 @@ namespace ts {
// Adjust the source map range for the first declaration to align with the old
// emitter.
const firstDeclaration = declarations[0];
const lastDeclaration = lastOrUndefined(declarations);
setSourceMapRange(declarationList, createRange(firstDeclaration.pos, lastDeclaration.end));
setSourceMapRange(declarationList, createRange(declarations[0].pos, last(declarations).end));
statements.push(
createVariableStatement(
@@ -2319,12 +2319,12 @@ namespace ts {
boundValue
)
]),
moveRangePos(node.initializer, -1)
moveRangePos(initializer, -1)
),
node.initializer
initializer
)
),
moveRangeEnd(node.initializer, -1)
moveRangeEnd(initializer, -1)
)
);
}
@@ -2332,14 +2332,14 @@ namespace ts {
else {
// Initializer is an expression. Emit the expression in the body, so that it's
// evaluated on every iteration.
const assignment = createAssignment(node.initializer, boundValue);
const assignment = createAssignment(initializer, boundValue);
if (isDestructuringAssignment(assignment)) {
aggregateTransformFlags(assignment);
statements.push(createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
}
else {
assignment.end = node.initializer.end;
statements.push(setTextRange(createStatement(visitNode(assignment, visitor, isExpression)), moveRangeEnd(node.initializer, -1)));
assignment.end = initializer.end;
statements.push(setTextRange(createStatement(visitNode(assignment, visitor, isExpression)), moveRangeEnd(initializer, -1)));
}
}
@@ -2564,7 +2564,7 @@ namespace ts {
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
if (property.name.kind === SyntaxKind.ComputedPropertyName) {
if (property.name!.kind === SyntaxKind.ComputedPropertyName) {
numInitialProperties = i;
break;
}
@@ -2624,7 +2624,7 @@ namespace ts {
function visit(node: Identifier | BindingPattern) {
if (node.kind === SyntaxKind.Identifier) {
state.hoistedLocalVariables.push(node);
state.hoistedLocalVariables!.push(node);
}
else {
for (const element of node.elements) {
@@ -2636,9 +2636,9 @@ namespace ts {
}
}
function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement, convert?: LoopConverter): VisitResult<Statement> {
function convertIterationStatementBodyIfNecessary(node: IterationStatement, outermostLabeledStatement: LabeledStatement | undefined, convert?: LoopConverter): VisitResult<Statement> {
if (!shouldConvertIterationStatementBody(node)) {
let saveAllowedNonLabeledJumps: Jump;
let saveAllowedNonLabeledJumps: Jump | undefined;
if (convertedLoopState) {
// we get here if we are trying to emit normal loop loop inside converted loop
// set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
@@ -2657,7 +2657,7 @@ namespace ts {
}
const functionName = createUniqueName("_loop");
let loopInitializer: VariableDeclarationList;
let loopInitializer: VariableDeclarationList | undefined;
switch (node.kind) {
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
@@ -2765,7 +2765,7 @@ namespace ts {
const statements: Statement[] = [convertedLoopVariable];
let extraVariableDeclarations: VariableDeclaration[];
let extraVariableDeclarations: VariableDeclaration[] | undefined;
// propagate state from the inner loop to the outer loop if necessary
if (currentState.argumentsName) {
// if alias for arguments is set
@@ -2850,7 +2850,7 @@ namespace ts {
else {
let clone = getMutableClone(node);
// clean statement part
clone.statement = undefined;
clone.statement = undefined!;
// visit childnodes to transform initializer/condition/incrementor parts
clone = visitEachChild(clone, visitor, context);
// set loop statement
@@ -2885,7 +2885,7 @@ namespace ts {
// simple loops are emitted as just 'loop()';
// NOTE: if loop uses only 'continue' it still will be emitted as simple loop
const isSimpleLoop =
!(state.nonLocalJumps & ~Jump.Continue) &&
!(state.nonLocalJumps! & ~Jump.Continue) &&
!state.labeledNonLocalBreaks &&
!state.labeledNonLocalContinues;
@@ -2898,7 +2898,7 @@ namespace ts {
: call;
if (isSimpleLoop) {
statements.push(createStatement(callResult));
copyOutParameters(state.loopOutParameters, CopyDirection.ToOriginal, statements);
copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements);
}
else {
const loopResultName = createUniqueName("state");
@@ -2909,12 +2909,12 @@ namespace ts {
)
);
statements.push(stateVariable);
copyOutParameters(state.loopOutParameters, CopyDirection.ToOriginal, statements);
copyOutParameters(state.loopOutParameters!, CopyDirection.ToOriginal, statements);
if (state.nonLocalJumps & Jump.Return) {
if (state.nonLocalJumps! & Jump.Return) {
let returnStatement: ReturnStatement;
if (outerConvertedLoopState) {
outerConvertedLoopState.nonLocalJumps |= Jump.Return;
outerConvertedLoopState.nonLocalJumps! |= Jump.Return;
returnStatement = createReturn(loopResultName);
}
else {
@@ -2932,7 +2932,7 @@ namespace ts {
);
}
if (state.nonLocalJumps & Jump.Break) {
if (state.nonLocalJumps! & Jump.Break) {
statements.push(
createIf(
createBinary(
@@ -2947,8 +2947,8 @@ namespace ts {
if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
const caseClauses: CaseClause[] = [];
processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses);
processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses);
processLabeledJumps(state.labeledNonLocalBreaks!, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses);
processLabeledJumps(state.labeledNonLocalContinues!, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses);
statements.push(
createSwitch(
loopResultName,
@@ -2975,7 +2975,7 @@ namespace ts {
}
}
function processLabeledJumps(table: Map<string>, isBreak: boolean, loopResultName: Identifier, outerLoop: ConvertedLoopState, caseClauses: CaseClause[]): void {
function processLabeledJumps(table: Map<string>, isBreak: boolean, loopResultName: Identifier, outerLoop: ConvertedLoopState | undefined, caseClauses: CaseClause[]): void {
if (!table) {
return;
}
@@ -3033,21 +3033,21 @@ namespace ts {
case SyntaxKind.SetAccessor:
const accessors = getAllAccessorDeclarations(node.properties, property);
if (property === accessors.firstAccessor) {
expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine));
expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
}
break;
case SyntaxKind.MethodDeclaration:
expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine!));
break;
case SyntaxKind.PropertyAssignment:
expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine!));
break;
case SyntaxKind.ShorthandPropertyAssignment:
expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine!));
break;
default:
@@ -3129,12 +3129,12 @@ namespace ts {
const ancestorFacts = enterSubtree(HierarchyFacts.BlockScopeExcludes, HierarchyFacts.BlockScopeIncludes);
let updated: CatchClause;
Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
if (isBindingPattern(node.variableDeclaration.name)) {
if (isBindingPattern(node.variableDeclaration!.name)) {
const temp = createTempVariable(/*recordTempVariable*/ undefined);
const newVariableDeclaration = createVariableDeclaration(temp);
setTextRange(newVariableDeclaration, node.variableDeclaration);
const vars = flattenDestructuringBinding(
node.variableDeclaration,
node.variableDeclaration!,
visitor,
context,
FlattenLevel.All,
@@ -3246,7 +3246,7 @@ namespace ts {
function visitArrayLiteralExpression(node: ArrayLiteralExpression): Expression {
if (node.transformFlags & TransformFlags.ES2015) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma);
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
return visitEachChild(node, visitor, context);
}
@@ -3311,16 +3311,16 @@ namespace ts {
// The class statements are the statements generated by visiting the first statement with initializer of the
// body (1), while all other statements are added to remainingStatements (2)
const isVariableStatementWithInitializer = (stmt: Statement) => isVariableStatement(stmt) && !!firstOrUndefined(stmt.declarationList.declarations).initializer;
const isVariableStatementWithInitializer = (stmt: Statement) => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer;
const bodyStatements = visitNodes(body.statements, visitor, isStatement);
const classStatements = filter(bodyStatements, isVariableStatementWithInitializer);
const remainingStatements = filter(bodyStatements, stmt => !isVariableStatementWithInitializer(stmt));
const varStatement = cast(firstOrUndefined(classStatements), isVariableStatement);
const varStatement = cast(first(classStatements), isVariableStatement);
// We know there is only one variable declaration here as we verified this in an
// earlier call to isTypeScriptClassWrapper
const variable = varStatement.declarationList.declarations[0];
const initializer = skipOuterExpressions(variable.initializer);
const initializer = skipOuterExpressions(variable.initializer!);
// Under certain conditions, the 'ts' transformer may introduce a class alias, which
// we see as an assignment, for example:
@@ -3373,7 +3373,7 @@ namespace ts {
}
// Find the trailing 'return' statement (4)
while (!isReturnStatement(elementAt(funcStatements, classBodyEnd))) {
while (!isReturnStatement(elementAt(funcStatements, classBodyEnd)!)) {
classBodyEnd--;
}
@@ -3516,7 +3516,7 @@ namespace ts {
createFunctionApply(
visitNode(target, visitor, isExpression),
thisArg,
transformAndSpreadElements(createNodeArray([createVoidZero(), ...node.arguments]), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)
transformAndSpreadElements(createNodeArray([createVoidZero(), ...node.arguments!]), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)
),
/*typeArguments*/ undefined,
[]
@@ -3570,7 +3570,7 @@ namespace ts {
}
// Rewrite using the pattern <segment0>.concat(<segment1>, <segment2>, ...)
return createArrayConcat(segments.shift(), segments);
return createArrayConcat(segments.shift()!, segments);
}
}
@@ -3649,7 +3649,7 @@ namespace ts {
// Build up the template arguments and the raw and cooked strings for the template.
// We start out with 'undefined' for the first argument and revisit later
// to avoid walking over the template string twice and shifting all our arguments over after the fact.
const templateArguments: Expression[] = [undefined];
const templateArguments: Expression[] = [undefined!];
const cookedStrings: Expression[] = [];
const rawStrings: Expression[] = [];
const template = node.template;
@@ -3733,7 +3733,7 @@ namespace ts {
// ("abc" + 1) << (2 + "")
// rather than
// "abc" + (1 << 2) + ""
const expression = reduceLeft(expressions, createAdd);
const expression = reduceLeft(expressions, createAdd)!;
if (nodeIsSynthesized(expression)) {
expression.pos = node.pos;
expression.end = node.end;
@@ -3920,14 +3920,13 @@ namespace ts {
* @param node An original source tree node.
*/
function isNameOfDeclarationWithCollidingName(node: Identifier) {
const parent = node.parent;
switch (parent.kind) {
switch (node.parent.kind) {
case SyntaxKind.BindingElement:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.VariableDeclaration:
return (<NamedDeclaration>parent).name === node
&& resolver.isDeclarationWithCollidingName(<Declaration>parent);
return (<NamedDeclaration>node.parent).name === node
&& resolver.isDeclarationWithCollidingName(<Declaration>node.parent);
}
return false;
@@ -3967,7 +3966,7 @@ namespace ts {
}
function isPartOfClassBody(declaration: ClassLikeDeclaration, node: Identifier) {
let currentNode = getParseTreeNode(node);
let currentNode: Node | undefined = getParseTreeNode(node);
if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
// if the node has no correlation to a parse tree node, its definitely not
// part of the body.
@@ -4009,7 +4008,7 @@ namespace ts {
: createPropertyAccess(getInternalName(node), "prototype");
}
function hasSynthesizedDefaultSuperCall(constructor: ConstructorDeclaration, hasExtendsClause: boolean) {
function hasSynthesizedDefaultSuperCall(constructor: ConstructorDeclaration | undefined, hasExtendsClause: boolean) {
if (!constructor || !hasExtendsClause) {
return false;
}
@@ -4018,7 +4017,7 @@ namespace ts {
return false;
}
const statement = firstOrUndefined(constructor.body.statements);
const statement = firstOrUndefined(constructor.body!.statements);
if (!statement || !nodeIsSynthesized(statement) || statement.kind !== SyntaxKind.ExpressionStatement) {
return false;
}
+14 -13
View File
@@ -116,10 +116,10 @@ namespace ts {
function visitCatchClauseInAsyncBody(node: CatchClause) {
const catchClauseNames = createUnderscoreEscapedMap<true>();
recordDeclarationName(node.variableDeclaration, catchClauseNames);
recordDeclarationName(node.variableDeclaration!, catchClauseNames); // TODO: GH#18217
// names declared in a catch variable are block scoped
let catchClauseUnshadowedNames: UnderscoreEscapedMap<true>;
let catchClauseUnshadowedNames: UnderscoreEscapedMap<true> | undefined;
catchClauseNames.forEach((_, escapedName) => {
if (enclosingFunctionParameterNames.has(escapedName)) {
if (!catchClauseUnshadowedNames) {
@@ -153,7 +153,7 @@ namespace ts {
return updateForIn(
node,
isVariableDeclarationListWithCollidingName(node.initializer)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)!
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.expression, visitor, isExpression),
visitNode(node.statement, asyncBodyVisitor, isStatement, liftToBlock)
@@ -165,7 +165,7 @@ namespace ts {
node,
visitNode(node.awaitModifier, visitor, isToken),
isVariableDeclarationListWithCollidingName(node.initializer)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)!
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.expression, visitor, isExpression),
visitNode(node.statement, asyncBodyVisitor, isStatement, liftToBlock)
@@ -173,10 +173,11 @@ namespace ts {
}
function visitForStatementInAsyncBody(node: ForStatement) {
const initializer = node.initializer!; // TODO: GH#18217
return updateFor(
node,
isVariableDeclarationListWithCollidingName(node.initializer)
? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false)
isVariableDeclarationListWithCollidingName(initializer)
? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
: visitNode(node.initializer, visitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
@@ -312,10 +313,10 @@ namespace ts {
}
function isVariableDeclarationListWithCollidingName(node: ForInitializer): node is VariableDeclarationList {
return node
return !!node
&& isVariableDeclarationList(node)
&& !(node.flags & NodeFlags.BlockScoped)
&& forEach(node.declarations, collidesWithParameterName);
&& node.declarations.some(collidesWithParameterName);
}
function visitVariableDeclarationListWithCollidingNames(node: VariableDeclarationList, hasReceiver: boolean) {
@@ -353,7 +354,7 @@ namespace ts {
const converted = setSourceMapRange(
createAssignment(
convertToAssignmentElementTarget(node.name),
node.initializer
node.initializer!
),
node
);
@@ -437,7 +438,7 @@ namespace ts {
context,
hasLexicalArguments,
promiseConstructor,
transformAsyncFunctionBodyWorker(node.body)
transformAsyncFunctionBodyWorker(node.body!)
);
const declarations = endLexicalEnvironment();
@@ -463,7 +464,7 @@ namespace ts {
}
}
function getPromiseConstructor(type: TypeNode) {
function getPromiseConstructor(type: TypeNode | undefined) {
const typeName = type && getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
@@ -634,7 +635,7 @@ namespace ts {
};`
};
function createAwaiterHelper(context: TransformationContext, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) {
function createAwaiterHelper(context: TransformationContext, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression | undefined, body: Block) {
context.requestEmitHelper(awaiterHelper);
const generatorFunc = createFunctionExpression(
@@ -648,7 +649,7 @@ namespace ts {
);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= EmitFlags.AsyncFunctionBody | EmitFlags.ReuseTempVariableScope;
(generatorFunc.emitNode || (generatorFunc.emitNode = {} as EmitNode)).flags |= EmitFlags.AsyncFunctionBody | EmitFlags.ReuseTempVariableScope;
return createCall(
getHelperName("__awaiter"),
+1 -1
View File
@@ -109,7 +109,7 @@ namespace ts {
*/
function trySubstituteReservedName(name: Identifier) {
const token = name.originalKeywordKind || (nodeIsSynthesized(name) ? stringToToken(idText(name)) : undefined);
if (token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord) {
if (token !== undefined && token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord) {
return setTextRange(createLiteral(name), name);
}
return undefined;
+14 -14
View File
@@ -294,7 +294,7 @@ namespace ts {
*
* @param node A ForOfStatement.
*/
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement): VisitResult<Statement> {
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult<Statement> {
if (node.initializer.transformFlags & TransformFlags.ContainsObjectRest) {
node = transformForOfStatementWithObjectRest(node);
}
@@ -309,8 +309,8 @@ namespace ts {
function transformForOfStatementWithObjectRest(node: ForOfStatement) {
const initializerWithoutParens = skipParentheses(node.initializer) as ForInitializer;
if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) {
let bodyLocation: TextRange;
let statementsLocation: TextRange;
let bodyLocation: TextRange | undefined;
let statementsLocation: TextRange | undefined;
const temp = createTempVariable(/*recordTempVariable*/ undefined);
const statements: Statement[] = [createForOfBindingStatement(initializerWithoutParens, temp)];
if (isBlock(node.statement)) {
@@ -351,8 +351,8 @@ namespace ts {
function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression) {
const binding = createForOfBindingStatement(node.initializer, boundValue);
let bodyLocation: TextRange;
let statementsLocation: TextRange;
let bodyLocation: TextRange | undefined;
let statementsLocation: TextRange | undefined;
const statements: Statement[] = [visitNode(binding, visitor, isStatement)];
const statement = visitNode(node.statement, visitor, isStatement);
if (isBlock(statement)) {
@@ -382,7 +382,7 @@ namespace ts {
: createAwait(expression);
}
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) {
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined) {
const expression = visitNode(node.expression, visitor, isExpression);
const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined);
const result = isIdentifier(expression) ? getGeneratedNameForNode(iterator) : createTempVariable(/*recordTempVariable*/ undefined);
@@ -562,7 +562,7 @@ namespace ts {
? undefined
: node.asteriskToken,
visitNode(node.name, visitor, isPropertyName),
visitNode(/*questionToken*/ undefined, visitor, isToken),
visitNode<Token<SyntaxKind.QuestionToken>>(/*questionToken*/ undefined, visitor, isToken),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
@@ -640,7 +640,7 @@ namespace ts {
function transformAsyncGeneratorFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
resumeLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
const statementOffset = addPrologue(statements, node.body!.statements, /*ensureUseStrict*/ false, visitor);
appendObjectRestAssignmentsIfNeeded(statements, node);
statements.push(
@@ -655,8 +655,8 @@ namespace ts {
/*parameters*/ [],
/*type*/ undefined,
updateBlock(
node.body,
visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)
node.body!,
visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset)
)
)
)
@@ -664,7 +664,7 @@ namespace ts {
);
prependRange(statements, endLexicalEnvironment());
const block = updateBlock(node.body, statements);
const block = updateBlock(node.body!, statements);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
@@ -702,7 +702,7 @@ namespace ts {
return body;
}
function appendObjectRestAssignmentsIfNeeded(statements: Statement[], node: FunctionLikeDeclaration): Statement[] {
function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined {
for (const parameter of node.parameters) {
if (parameter.transformFlags & TransformFlags.ContainsObjectRest) {
const temp = getGeneratedNameForNode(parameter);
@@ -889,7 +889,7 @@ namespace ts {
};
export function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]) {
if (context.getCompilerOptions().target >= ScriptTarget.ES2015) {
if (context.getCompilerOptions().target! >= ScriptTarget.ES2015) {
return createCall(createPropertyAccess(createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined,
attributesSegments);
@@ -936,7 +936,7 @@ namespace ts {
context.requestEmitHelper(asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= EmitFlags.AsyncFunctionBody;
(generatorFunc.emitNode || (generatorFunc.emitNode = {} as EmitNode)).flags |= EmitFlags.AsyncFunctionBody;
return createCall(
getHelperName("__asyncGenerator"),
+70 -68
View File
@@ -135,7 +135,7 @@ namespace ts {
Endfinally // Marks the end of a `finally` block
}
type OperationArguments = [Label] | [Label, Expression] | [Statement] | [Expression] | [Expression, Expression];
type OperationArguments = [Label] | [Label, Expression] | [Statement] | [Expression | undefined] | [Expression, Expression];
// whether a generated code block is opening or closing at the current operation for a FunctionBuilder
const enum BlockAction {
@@ -224,6 +224,7 @@ namespace ts {
case Instruction.Yield: return "yield";
case Instruction.YieldStar: return "yield*";
case Instruction.Endfinally: return "endfinally";
default: return undefined!; // TODO: GH#18217
}
}
@@ -251,18 +252,18 @@ namespace ts {
// All three arrays are correlated by their index. This approach is used over allocating
// objects to store the same information to avoid GC overhead.
//
let blocks: CodeBlock[]; // Information about the code block
let blockOffsets: number[]; // The operation offset at which a code block begins or ends
let blockActions: BlockAction[]; // Whether the code block is opened or closed
let blockStack: CodeBlock[]; // A stack of currently open code blocks
let blocks: CodeBlock[] | undefined; // Information about the code block
let blockOffsets: number[] | undefined; // The operation offset at which a code block begins or ends
let blockActions: BlockAction[] | undefined; // Whether the code block is opened or closed
let blockStack: CodeBlock[] | undefined; // A stack of currently open code blocks
// Labels are used to mark locations in the code that can be the target of a Break (jump)
// operation. These are translated into case clauses in a switch statement.
// The following two arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
let labelOffsets: number[]; // The operation offset at which the label is defined.
let labelExpressions: LiteralExpression[][]; // The NumericLiteral nodes bound to each label.
let labelOffsets: number[] | undefined; // The operation offset at which the label is defined.
let labelExpressions: LiteralExpression[][] | undefined; // The NumericLiteral nodes bound to each label.
let nextLabelId = 1; // The next label id to use.
// Operations store information about generated code for the function body. This
@@ -270,9 +271,9 @@ namespace ts {
// The following three arrays are correlated by their index. This approach is used over
// allocating objects to store the same information to avoid GC overhead.
//
let operations: OpCode[]; // The operation to perform.
let operationArguments: OperationArguments[]; // The arguments to the operation.
let operationLocations: TextRange[]; // The source map location for the operation.
let operations: OpCode[] | undefined; // The operation to perform.
let operationArguments: (OperationArguments | undefined)[] | undefined; // The arguments to the operation.
let operationLocations: (TextRange | undefined)[] | undefined; // The source map location for the operation.
let state: Identifier; // The name of the state object used by the generator at runtime.
@@ -280,14 +281,14 @@ namespace ts {
//
let blockIndex = 0; // The index of the current block.
let labelNumber = 0; // The current label number.
let labelNumbers: number[][];
let labelNumbers: number[][] | undefined;
let lastOperationWasAbrupt: boolean; // Indicates whether the last operation was abrupt (break/continue).
let lastOperationWasCompletion: boolean; // Indicates whether the last operation was a completion (return/throw).
let clauses: CaseClause[]; // The case clauses generated for labels.
let statements: Statement[]; // The statements for the current label.
let exceptionBlockStack: ExceptionBlock[]; // A stack of containing exception blocks.
let currentExceptionBlock: ExceptionBlock; // The current exception block.
let withBlockStack: WithBlock[]; // A stack containing `with` blocks.
let clauses: CaseClause[] | undefined; // The case clauses generated for labels.
let statements: Statement[] | undefined; // The statements for the current label.
let exceptionBlockStack: ExceptionBlock[] | undefined; // A stack of containing exception blocks.
let currentExceptionBlock: ExceptionBlock | undefined; // The current exception block.
let withBlockStack: WithBlock[] | undefined; // A stack containing `with` blocks.
return chainBundle(transformSourceFile);
@@ -440,7 +441,7 @@ namespace ts {
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): Statement {
function visitFunctionDeclaration(node: FunctionDeclaration): Statement | undefined {
// Currently, we only support generators that were originally async functions.
if (node.asteriskToken) {
node = setOriginalNode(
@@ -453,7 +454,7 @@ namespace ts {
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformGeneratorFunctionBody(node.body)
transformGeneratorFunctionBody(node.body!)
),
/*location*/ node
),
@@ -615,7 +616,7 @@ namespace ts {
*
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): Statement {
function visitVariableStatement(node: VariableStatement): Statement | undefined {
if (node.transformFlags & TransformFlags.ContainsYield) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
@@ -655,13 +656,14 @@ namespace ts {
* @param node The node to visit.
*/
function visitBinaryExpression(node: BinaryExpression): Expression {
switch (getExpressionAssociativity(node)) {
const assoc = getExpressionAssociativity(node);
switch (assoc) {
case Associativity.Left:
return visitLeftAssociativeBinaryExpression(node);
case Associativity.Right:
return visitRightAssociativeBinaryExpression(node);
default:
Debug.fail("Unknown associativity.");
return Debug.assertNever(assoc);
}
}
@@ -934,9 +936,9 @@ namespace ts {
// x = %sent%;
const resumeLabel = defineLabel();
const expression = visitNode(node.expression, visitor, isExpression);
const expression = visitNode(node.expression!, visitor, isExpression);
if (node.asteriskToken) {
const iterator = (getEmitFlags(node.expression) & EmitFlags.Iterator) === 0
const iterator = (getEmitFlags(node.expression!) & EmitFlags.Iterator) === 0
? createValuesHelper(context, expression, /*location*/ node)
: expression;
emitYieldStar(iterator, /*location*/ node);
@@ -978,7 +980,7 @@ namespace ts {
const numInitialElements = countInitialNodesWithoutYield(elements);
let temp: Identifier;
let temp: Identifier | undefined;
if (numInitialElements > 0) {
temp = declareLocal();
const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements);
@@ -1155,7 +1157,7 @@ namespace ts {
cacheExpression(visitNode(target, visitor, isExpression)),
thisArg,
visitElements(
node.arguments,
node.arguments!,
/*leadingElement*/ createVoidZero()
)
),
@@ -1246,7 +1248,7 @@ namespace ts {
emitStatement(visitNode(node, visitor, isStatement));
}
function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList {
function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList | undefined {
for (const variable of node.declarations) {
const name = getSynthesizedClone(<Identifier>variable.name);
setCommentRange(name, variable.name);
@@ -1260,7 +1262,7 @@ namespace ts {
while (variablesWritten < numVariables) {
for (let i = variablesWritten; i < numVariables; i++) {
const variable = variables[i];
if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
if (containsYield(variable.initializer!) && pendingExpressions.length > 0) {
break;
}
@@ -1281,7 +1283,7 @@ namespace ts {
return setSourceMapRange(
createAssignment(
setSourceMapRange(<Identifier>getSynthesizedClone(node.name), node.name),
visitNode(node.initializer, visitor, isExpression)
visitNode(node.initializer!, visitor, isExpression)
),
node
);
@@ -1306,11 +1308,11 @@ namespace ts {
if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
const endLabel = defineLabel();
const elseLabel = node.elseStatement ? defineLabel() : undefined;
emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, visitNode(node.expression, visitor, isExpression), /*location*/ node.expression);
emitBreakWhenFalse(node.elseStatement ? elseLabel! : endLabel, visitNode(node.expression, visitor, isExpression), /*location*/ node.expression);
transformAndEmitEmbeddedStatement(node.thenStatement);
if (node.elseStatement) {
emitBreak(endLabel);
markLabel(elseLabel);
markLabel(elseLabel!);
transformAndEmitEmbeddedStatement(node.elseStatement);
}
markLabel(endLabel);
@@ -1866,7 +1868,7 @@ namespace ts {
function transformAndEmitThrowStatement(node: ThrowStatement): void {
emitThrow(
visitNode(node.expression, visitor, isExpression),
visitNode(node.expression!, visitor, isExpression),
/*location*/ node
);
}
@@ -1906,7 +1908,7 @@ namespace ts {
beginExceptionBlock();
transformAndEmitEmbeddedStatement(node.tryBlock);
if (node.catchClause) {
beginCatchBlock(node.catchClause.variableDeclaration);
beginCatchBlock(node.catchClause.variableDeclaration!); // TODO: GH#18217
transformAndEmitEmbeddedStatement(node.catchClause.block);
}
@@ -1922,8 +1924,8 @@ namespace ts {
}
}
function containsYield(node: Node) {
return node && (node.transformFlags & TransformFlags.ContainsYield) !== 0;
function containsYield(node: Node | undefined): boolean {
return !!node && (node.transformFlags & TransformFlags.ContainsYield) !== 0;
}
function countInitialNodesWithoutYield(nodes: NodeArray<Node>) {
@@ -2010,7 +2012,7 @@ namespace ts {
*/
function markLabel(label: Label): void {
Debug.assert(labelOffsets !== undefined, "No labels were defined.");
labelOffsets[label] = operations ? operations.length : 0;
labelOffsets![label] = operations ? operations.length : 0;
}
/**
@@ -2026,11 +2028,11 @@ namespace ts {
blockStack = [];
}
const index = blockActions.length;
blockActions[index] = BlockAction.Open;
blockOffsets[index] = operations ? operations.length : 0;
const index = blockActions!.length;
blockActions![index] = BlockAction.Open;
blockOffsets![index] = operations ? operations.length : 0;
blocks[index] = block;
blockStack.push(block);
blockStack!.push(block);
return index;
}
@@ -2039,13 +2041,13 @@ namespace ts {
*/
function endBlock(): CodeBlock {
const block = peekBlock();
Debug.assert(block !== undefined, "beginBlock was never called.");
if (block === undefined) return Debug.fail("beginBlock was never called.");
const index = blockActions.length;
blockActions[index] = BlockAction.Close;
blockOffsets[index] = operations ? operations.length : 0;
blocks[index] = block;
blockStack.pop();
const index = blockActions!.length;
blockActions![index] = BlockAction.Close;
blockOffsets![index] = operations ? operations.length : 0;
blocks![index] = block;
blockStack!.pop();
return block;
}
@@ -2053,13 +2055,13 @@ namespace ts {
* Gets the current open block.
*/
function peekBlock() {
return lastOrUndefined(blockStack);
return lastOrUndefined(blockStack!);
}
/**
* Gets the kind of the current open block.
*/
function peekBlockKind(): CodeBlockKind {
function peekBlockKind(): CodeBlockKind | undefined {
const block = peekBlock();
return block && block.kind;
}
@@ -2331,7 +2333,7 @@ namespace ts {
function hasImmediateContainingLabeledBlock(labelText: string, start: number) {
for (let j = start; j >= 0; j--) {
const containingBlock = blockStack[j];
const containingBlock = blockStack![j];
if (supportsLabeledBreakOrContinue(containingBlock)) {
if (containingBlock.labelText === labelText) {
return true;
@@ -2407,8 +2409,8 @@ namespace ts {
*
* @param label A label.
*/
function createLabel(label: Label): Expression {
if (label > 0) {
function createLabel(label: Label | undefined): Expression {
if (label !== undefined && label > 0) {
if (labelExpressions === undefined) {
labelExpressions = [];
}
@@ -2620,8 +2622,8 @@ namespace ts {
const operationIndex = operations.length;
operations[operationIndex] = code;
operationArguments[operationIndex] = args;
operationLocations[operationIndex] = location;
operationArguments![operationIndex] = args;
operationLocations![operationIndex] = location;
}
/**
@@ -2869,9 +2871,9 @@ namespace ts {
*/
function tryEnterOrLeaveBlock(operationIndex: number): void {
if (blocks) {
for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
for (; blockIndex < blockActions!.length && blockOffsets![blockIndex] <= operationIndex; blockIndex++) {
const block = blocks[blockIndex];
const blockAction = blockActions[blockIndex];
const blockAction = blockActions![blockIndex];
switch (block.kind) {
case CodeBlockKind.Exception:
if (blockAction === BlockAction.Open) {
@@ -2883,11 +2885,11 @@ namespace ts {
statements = [];
}
exceptionBlockStack.push(currentExceptionBlock);
exceptionBlockStack.push(currentExceptionBlock!);
currentExceptionBlock = block;
}
else if (blockAction === BlockAction.Close) {
currentExceptionBlock = exceptionBlockStack.pop();
currentExceptionBlock = exceptionBlockStack!.pop();
}
break;
case CodeBlockKind.With:
@@ -2899,7 +2901,7 @@ namespace ts {
withBlockStack.push(block);
}
else if (blockAction === BlockAction.Close) {
withBlockStack.pop();
withBlockStack!.pop();
}
break;
// default: do nothing
@@ -2925,7 +2927,7 @@ namespace ts {
lastOperationWasAbrupt = false;
lastOperationWasCompletion = false;
const opcode = operations[operationIndex];
const opcode = operations![operationIndex];
if (opcode === OpCode.Nop) {
return;
}
@@ -2933,12 +2935,12 @@ namespace ts {
return writeEndfinally();
}
const args = operationArguments[operationIndex];
const args = operationArguments![operationIndex]!;
if (opcode === OpCode.Statement) {
return writeStatement(<Statement>args[0]);
}
const location = operationLocations[operationIndex];
const location = operationLocations![operationIndex];
switch (opcode) {
case OpCode.Assign:
return writeAssign(<Expression>args[0], <Expression>args[1], location);
@@ -2982,7 +2984,7 @@ namespace ts {
* @param right The right-hand side of the assignment.
* @param operationLocation The source map location for the operation.
*/
function writeAssign(left: Expression, right: Expression, operationLocation: TextRange): void {
function writeAssign(left: Expression, right: Expression, operationLocation: TextRange | undefined): void {
writeStatement(setTextRange(createStatement(createAssignment(left, right)), operationLocation));
}
@@ -2992,7 +2994,7 @@ namespace ts {
* @param expression The value to throw.
* @param operationLocation The source map location for the operation.
*/
function writeThrow(expression: Expression, operationLocation: TextRange): void {
function writeThrow(expression: Expression, operationLocation: TextRange | undefined): void {
lastOperationWasAbrupt = true;
lastOperationWasCompletion = true;
writeStatement(setTextRange(createThrow(expression), operationLocation));
@@ -3004,7 +3006,7 @@ namespace ts {
* @param expression The value to return.
* @param operationLocation The source map location for the operation.
*/
function writeReturn(expression: Expression, operationLocation: TextRange): void {
function writeReturn(expression: Expression | undefined, operationLocation: TextRange | undefined): void {
lastOperationWasAbrupt = true;
lastOperationWasCompletion = true;
writeStatement(
@@ -3029,7 +3031,7 @@ namespace ts {
* @param label The label for the Break.
* @param operationLocation The source map location for the operation.
*/
function writeBreak(label: Label, operationLocation: TextRange): void {
function writeBreak(label: Label, operationLocation: TextRange | undefined): void {
lastOperationWasAbrupt = true;
writeStatement(
setEmitFlags(
@@ -3054,7 +3056,7 @@ namespace ts {
* @param condition The condition for the Break.
* @param operationLocation The source map location for the operation.
*/
function writeBreakWhenTrue(label: Label, condition: Expression, operationLocation: TextRange): void {
function writeBreakWhenTrue(label: Label, condition: Expression, operationLocation: TextRange | undefined): void {
writeStatement(
setEmitFlags(
createIf(
@@ -3084,7 +3086,7 @@ namespace ts {
* @param condition The condition for the Break.
* @param operationLocation The source map location for the operation.
*/
function writeBreakWhenFalse(label: Label, condition: Expression, operationLocation: TextRange): void {
function writeBreakWhenFalse(label: Label, condition: Expression, operationLocation: TextRange | undefined): void {
writeStatement(
setEmitFlags(
createIf(
@@ -3113,7 +3115,7 @@ namespace ts {
* @param expression The expression to yield.
* @param operationLocation The source map location for the operation.
*/
function writeYield(expression: Expression, operationLocation: TextRange): void {
function writeYield(expression: Expression, operationLocation: TextRange | undefined): void {
lastOperationWasAbrupt = true;
writeStatement(
setEmitFlags(
@@ -3138,7 +3140,7 @@ namespace ts {
* @param expression The expression to yield.
* @param operationLocation The source map location for the operation.
*/
function writeYieldStar(expression: Expression, operationLocation: TextRange): void {
function writeYieldStar(expression: Expression, operationLocation: TextRange | undefined): void {
lastOperationWasAbrupt = true;
writeStatement(
setEmitFlags(
+7 -7
View File
@@ -50,7 +50,7 @@ namespace ts {
}
}
function transformJsxChildToExpression(node: JsxChild): Expression {
function transformJsxChildToExpression(node: JsxChild): Expression | undefined {
switch (node.kind) {
case SyntaxKind.JsxText:
return visitJsxText(node);
@@ -84,9 +84,9 @@ namespace ts {
return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
}
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: ReadonlyArray<JsxChild>, isChild: boolean, location: TextRange) {
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: ReadonlyArray<JsxChild> | undefined, isChild: boolean, location: TextRange) {
const tagName = getTagName(node);
let objectProperties: Expression;
let objectProperties: Expression | undefined;
const attrs = node.attributes.properties;
if (attrs.length === 0) {
// When there are no attributes, React wants "null"
@@ -118,7 +118,7 @@ namespace ts {
const element = createExpressionForJsxElement(
context.getEmitResolver().getJsxFactoryEntity(currentSourceFile),
compilerOptions.reactNamespace,
compilerOptions.reactNamespace!, // TODO: GH#18217
tagName,
objectProperties,
mapDefined(children, transformJsxChildToExpression),
@@ -136,7 +136,7 @@ namespace ts {
function visitJsxOpeningFragment(node: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, isChild: boolean, location: TextRange) {
const element = createExpressionForJsxFragment(
context.getEmitResolver().getJsxFactoryEntity(currentSourceFile),
compilerOptions.reactNamespace,
compilerOptions.reactNamespace!, // TODO: GH#18217
mapDefined(children, transformJsxChildToExpression),
node,
location
@@ -159,7 +159,7 @@ namespace ts {
return createPropertyAssignment(name, expression);
}
function transformJsxAttributeInitializer(node: StringLiteral | JsxExpression) {
function transformJsxAttributeInitializer(node: StringLiteral | JsxExpression | undefined): Expression {
if (node === undefined) {
return createTrue();
}
@@ -563,4 +563,4 @@ namespace ts {
hearts: 0x2665,
diams: 0x2666
});
}
}
+2 -2
View File
@@ -9,7 +9,7 @@ namespace ts {
context.enableEmitNotification(SyntaxKind.SourceFile);
context.enableSubstitution(SyntaxKind.Identifier);
let currentSourceFile: SourceFile;
let currentSourceFile: SourceFile | undefined;
return chainBundle(transformSourceFile);
function transformSourceFile(node: SourceFile) {
@@ -104,7 +104,7 @@ namespace ts {
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile!);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
+18 -18
View File
@@ -38,7 +38,7 @@ namespace ts {
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: Statement[][] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const deferredExports: (Statement[] | undefined)[] = []; // Exports to defer until an EndOfDeclarationMarker is found.
let currentSourceFile: SourceFile; // The current file.
let currentModuleInfo: ExternalModuleInfo; // The ExternalModuleInfo for the current file.
@@ -64,8 +64,8 @@ namespace ts {
// Perform the transformation.
const transformModule = getTransformModuleDelegate(moduleKind);
const updated = transformModule(node);
currentSourceFile = undefined;
currentModuleInfo = undefined;
currentSourceFile = undefined!;
currentModuleInfo = undefined!;
needUMDDynamicImportHelper = false;
return aggregateTransformFlags(updated);
}
@@ -391,7 +391,7 @@ namespace ts {
if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
return undefined;
}
const name = getLocalNameForExternalImport(node, currentSourceFile);
const name = getLocalNameForExternalImport(node, currentSourceFile)!; // TODO: GH#18217
const expr = getHelperExpressionForImport(node, name);
if (expr === name) {
return undefined;
@@ -605,7 +605,7 @@ namespace ts {
}
}
function createImportCallExpressionUMD(arg: Expression | undefined, containsLexicalThis: boolean): Expression {
function createImportCallExpressionUMD(arg: Expression, containsLexicalThis: boolean): Expression {
// (function (factory) {
// ... (regular UMD)
// }
@@ -762,7 +762,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[];
let statements: Statement[] | undefined;
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (moduleKind !== ModuleKind.AMD) {
if (!node.importClause) {
@@ -876,7 +876,7 @@ namespace ts {
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[];
let statements: Statement[] | undefined;
if (moduleKind !== ModuleKind.AMD) {
if (hasModifier(node, ModifierFlags.Export)) {
statements = append(statements,
@@ -1009,7 +1009,7 @@ namespace ts {
return undefined;
}
let statements: Statement[];
let statements: Statement[] | undefined;
const original = node.original;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -1029,7 +1029,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
let statements: Statement[];
let statements: Statement[] | undefined;
if (hasModifier(node, ModifierFlags.Export)) {
statements = append(statements,
setOriginalNode(
@@ -1072,7 +1072,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
let statements: Statement[];
let statements: Statement[] | undefined;
if (hasModifier(node, ModifierFlags.Export)) {
statements = append(statements,
setOriginalNode(
@@ -1113,12 +1113,12 @@ namespace ts {
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
let statements: Statement[];
let variables: VariableDeclaration[];
let expressions: Expression[];
let statements: Statement[] | undefined;
let variables: VariableDeclaration[] | undefined;
let expressions: Expression[] | undefined;
if (hasModifier(node, ModifierFlags.Export)) {
let modifiers: NodeArray<Modifier>;
let modifiers: NodeArray<Modifier> | undefined;
// If we're exporting these variables, then these just become assignments to 'exports.x'.
// We only want to emit assignments for variables with initializers.
@@ -1219,7 +1219,7 @@ namespace ts {
//
// To balance the declaration, add the exports of the elided variable
// statement.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) {
if (hasAssociatedEndOfDeclarationMarker(node) && node.original!.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original);
}
@@ -1532,9 +1532,9 @@ namespace ts {
previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
currentModuleInfo = undefined;
noSubstitution = undefined;
currentSourceFile = undefined!;
currentModuleInfo = undefined!;
noSubstitution = undefined!;
}
else {
previousOnEmitNode(hint, node, emitCallback);
+33 -37
View File
@@ -27,7 +27,7 @@ namespace ts {
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: Statement[][] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const deferredExports: (Statement[] | undefined)[] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap: Identifier[] = []; // The export function associated with a source file.
const noSubstitutionMap: boolean[][] = []; // Set of nodes for which substitution rules should be ignored for each file.
@@ -35,9 +35,9 @@ namespace ts {
let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file.
let exportFunction: Identifier; // The export function for the current file.
let contextObject: Identifier; // The context object for the current file.
let hoistedStatements: Statement[];
let hoistedStatements: Statement[] | undefined;
let enclosingBlockScopedContainer: Node;
let noSubstitution: boolean[]; // Set of nodes for which substitution rules should be ignored.
let noSubstitution: boolean[] | undefined; // Set of nodes for which substitution rules should be ignored.
return chainBundle(transformSourceFile);
@@ -126,12 +126,12 @@ namespace ts {
noSubstitution = undefined;
}
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
contextObject = undefined;
hoistedStatements = undefined;
enclosingBlockScopedContainer = undefined;
currentSourceFile = undefined!;
moduleInfo = undefined!;
exportFunction = undefined!;
contextObject = undefined!;
hoistedStatements = undefined!;
enclosingBlockScopedContainer = undefined!;
return aggregateTransformFlags(updated);
}
@@ -259,7 +259,7 @@ namespace ts {
// - Temporary variables will appear at the top rather than at the bottom of the file
prependRange(statements, endLexicalEnvironment());
const exportStarFunction = addExportStarIfNeeded(statements);
const exportStarFunction = addExportStarIfNeeded(statements)!; // TODO: GH#18217
const moduleObject = createObjectLiteral([
createPropertyAssignment("setters",
createSettersArray(exportStarFunction, dependencyGroups)
@@ -464,7 +464,7 @@ namespace ts {
const parameterName = localName ? getGeneratedNameForNode(localName) : createUniqueName("");
const statements: Statement[] = [];
for (const entry of group.externalImports) {
const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile);
const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile)!; // TODO: GH#18217
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!entry.importClause) {
@@ -590,9 +590,9 @@ namespace ts {
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[];
let statements: Statement[] | undefined;
if (node.importClause) {
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)!); // TODO: GH#18217
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
@@ -615,13 +615,13 @@ namespace ts {
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[];
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
let statements: Statement[] | undefined;
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile)!); // TODO: GH#18217
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id]!, node);
}
else {
statements = appendExportsOfImportEqualsDeclaration(statements, node);
@@ -694,7 +694,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
let statements: Statement[];
let statements: Statement[] | undefined;
// Hoist the name of the class declaration to the outer module body function.
const name = getLocalName(node);
@@ -745,7 +745,7 @@ namespace ts {
return visitNode(node, destructuringAndImportCallVisitor, isStatement);
}
let expressions: Expression[];
let expressions: Expression[] | undefined;
const isExportedDeclaration = hasModifier(node, ModifierFlags.Export);
const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
for (const variable of node.declarationList.declarations) {
@@ -757,7 +757,7 @@ namespace ts {
}
}
let statements: Statement[];
let statements: Statement[] | undefined;
if (expressions) {
statements = append(statements, setTextRange(createStatement(inlineExpressions(expressions)), node));
}
@@ -854,7 +854,7 @@ namespace ts {
* @param location The source map location for the assignment.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function createVariableAssignment(name: Identifier, value: Expression, location: TextRange, isExportedDeclaration: boolean) {
function createVariableAssignment(name: Identifier, value: Expression, location: TextRange | undefined, isExportedDeclaration: boolean) {
hoistVariableDeclaration(getSynthesizedClone(name));
return isExportedDeclaration
? createExportExpression(name, preventSubstitution(setTextRange(createAssignment(name, value), location)))
@@ -875,9 +875,9 @@ namespace ts {
//
// To balance the declaration, we defer the exports of the elided variable
// statement until we visit this declaration's `EndOfDeclarationMarker`.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) {
if (hasAssociatedEndOfDeclarationMarker(node) && node.original!.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
const isExportedDeclaration = hasModifier(node.original, ModifierFlags.Export);
const isExportedDeclaration = hasModifier(node.original!, ModifierFlags.Export);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original, isExportedDeclaration);
}
@@ -928,7 +928,7 @@ namespace ts {
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportDeclaration(statements: Statement[], decl: ImportDeclaration) {
function appendExportsOfImportDeclaration(statements: Statement[] | undefined, decl: ImportDeclaration) {
if (moduleInfo.exportEquals) {
return statements;
}
@@ -970,7 +970,7 @@ namespace ts {
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportEqualsDeclaration(statements: Statement[], decl: ImportEqualsDeclaration): Statement[] | undefined {
function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, decl: ImportEqualsDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
@@ -1026,7 +1026,7 @@ namespace ts {
}
}
else if (!isGeneratedIdentifier(decl.name)) {
let excludeName: string;
let excludeName: string | undefined;
if (exportSelf) {
statements = appendExportStatement(statements, decl.name, getLocalName(decl));
excludeName = idText(decl.name);
@@ -1052,9 +1052,9 @@ namespace ts {
return statements;
}
let excludeName: string;
let excludeName: string | undefined;
if (hasModifier(decl, ModifierFlags.Export)) {
const exportName = hasModifier(decl, ModifierFlags.Default) ? createLiteral("default") : decl.name;
const exportName = hasModifier(decl, ModifierFlags.Default) ? createLiteral("default") : decl.name!;
statements = appendExportStatement(statements, exportName, getLocalName(decl));
excludeName = getTextOfIdentifierOrLiteral(exportName);
}
@@ -1221,7 +1221,7 @@ namespace ts {
node = updateFor(
node,
visitForInitializer(node.initializer),
node.initializer && visitForInitializer(node.initializer),
visitNode(node.condition, destructuringAndImportCallVisitor, isExpression),
visitNode(node.incrementor, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement)
@@ -1289,12 +1289,8 @@ namespace ts {
* @param node The node to visit.
*/
function visitForInitializer(node: ForInitializer): ForInitializer {
if (!node) {
return node;
}
if (shouldHoistForInitializer(node)) {
let expressions: Expression[];
let expressions: Expression[] | undefined;
for (const variable of node.declarations) {
expressions = append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
if (!variable.initializer) {
@@ -1598,9 +1594,9 @@ namespace ts {
previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
currentSourceFile = undefined!;
moduleInfo = undefined!;
exportFunction = undefined!;
noSubstitution = undefined;
}
else {
@@ -1841,7 +1837,7 @@ namespace ts {
* @param name The name.
*/
function getExports(name: Identifier) {
let exportedNames: Identifier[];
let exportedNames: Identifier[] | undefined;
if (!isGeneratedIdentifier(name)) {
const valueDeclaration = resolver.getReferencedImportDeclaration(name)
|| resolver.getReferencedValueDeclaration(name);
+46 -44
View File
@@ -62,7 +62,7 @@ namespace ts {
let currentNamespace: ModuleDeclaration;
let currentNamespaceContainerName: Identifier;
let currentScope: SourceFile | Block | ModuleBlock | CaseBlock;
let currentScopeFirstDeclarationsOfName: UnderscoreEscapedMap<Node>;
let currentScopeFirstDeclarationsOfName: UnderscoreEscapedMap<Node> | undefined;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
@@ -121,7 +121,7 @@ namespace ts {
const visited = saveStateAndInvoke(node, visitSourceFile);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
currentSourceFile = undefined!;
return visited;
}
@@ -625,7 +625,7 @@ namespace ts {
// Write any pending expressions from elided or moved computed property names
if (some(pendingExpressions)) {
statements.push(createStatement(inlineExpressions(pendingExpressions)));
statements.push(createStatement(inlineExpressions(pendingExpressions!)));
}
pendingExpressions = savedPendingExpressions;
@@ -723,7 +723,7 @@ namespace ts {
* @param name The name of the class.
* @param facts Precomputed facts about the class.
*/
function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier, facts: ClassFacts) {
function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier | undefined, facts: ClassFacts) {
// ${modifiers} class ${name} ${heritageClauses} {
// ${members}
// }
@@ -759,7 +759,7 @@ namespace ts {
* Transforms a decorated class declaration and appends the resulting statements. If
* the class requires an alias to avoid issues with double-binding, the alias is returned.
*/
function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier, facts: ClassFacts) {
function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier | undefined, facts: ClassFacts) {
// When we emit an ES6 class that has a class decorator, we must tailor the
// emit to certain specific cases.
//
@@ -998,7 +998,7 @@ namespace ts {
*
* @param constructor The constructor declaration.
*/
function transformConstructorParameters(constructor: ConstructorDeclaration) {
function transformConstructorParameters(constructor: ConstructorDeclaration | undefined) {
// The ES2015 spec specifies in 14.5.14. Runtime Semantics: ClassDefinitionEvaluation:
// If constructor is empty, then
// If ClassHeritag_eopt is present and protoParent is not null, then
@@ -1026,7 +1026,7 @@ namespace ts {
* @param constructor The current class constructor.
* @param isDerivedClass A value indicating whether the class has an extends clause that does not extend 'null'.
*/
function transformConstructorBody(node: ClassExpression | ClassDeclaration, constructor: ConstructorDeclaration, isDerivedClass: boolean) {
function transformConstructorBody(node: ClassExpression | ClassDeclaration, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) {
let statements: Statement[] = [];
let indexOfFirstStatement = 0;
@@ -1081,7 +1081,7 @@ namespace ts {
if (constructor) {
// The class already had a constructor, so we should add the existing statements, skipping the initial super call.
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, indexOfFirstStatement));
addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatement));
}
// End the lexical environment.
@@ -1090,7 +1090,7 @@ namespace ts {
createBlock(
setTextRange(
createNodeArray(statements),
/*location*/ constructor ? constructor.body.statements : node.members
/*location*/ constructor ? constructor.body!.statements : node.members
),
/*multiLine*/ true
),
@@ -1266,7 +1266,7 @@ namespace ts {
const propertyName = isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
? updateComputedPropertyName(property.name, getGeneratedNameForNode(property.name))
: property.name;
const initializer = visitNode(property.initializer, visitor, isExpression);
const initializer = visitNode(property.initializer!, visitor, isExpression);
const memberAccess = createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
return createAssignment(memberAccess, initializer);
@@ -1319,8 +1319,8 @@ namespace ts {
* A structure describing the decorators for a class element.
*/
interface AllDecorators {
decorators: ReadonlyArray<Decorator>;
parameters?: ReadonlyArray<ReadonlyArray<Decorator>>;
decorators: ReadonlyArray<Decorator> | undefined;
parameters?: ReadonlyArray<ReadonlyArray<Decorator> | undefined>;
}
/**
@@ -1329,8 +1329,8 @@ namespace ts {
*
* @param node The function-like node.
*/
function getDecoratorsOfParameters(node: FunctionLikeDeclaration) {
let decorators: ReadonlyArray<Decorator>[];
function getDecoratorsOfParameters(node: FunctionLikeDeclaration | undefined) {
let decorators: (ReadonlyArray<Decorator> | undefined)[] | undefined;
if (node) {
const parameters = node.parameters;
for (let i = 0; i < parameters.length; i++) {
@@ -1354,7 +1354,7 @@ namespace ts {
*
* @param node The class node.
*/
function getAllDecoratorsOfConstructor(node: ClassExpression | ClassDeclaration): AllDecorators {
function getAllDecoratorsOfConstructor(node: ClassExpression | ClassDeclaration): AllDecorators | undefined {
const decorators = node.decorators;
const parameters = getDecoratorsOfParameters(getFirstConstructorWithBody(node));
if (!decorators && !parameters) {
@@ -1373,7 +1373,7 @@ namespace ts {
* @param node The class node that contains the member.
* @param member The class member.
*/
function getAllDecoratorsOfClassElement(node: ClassExpression | ClassDeclaration, member: ClassElement): AllDecorators {
function getAllDecoratorsOfClassElement(node: ClassExpression | ClassDeclaration, member: ClassElement): AllDecorators | undefined {
switch (member.kind) {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
@@ -1396,7 +1396,7 @@ namespace ts {
* @param node The class node that contains the accessor.
* @param accessor The class accessor member.
*/
function getAllDecoratorsOfAccessors(node: ClassExpression | ClassDeclaration, accessor: AccessorDeclaration): AllDecorators {
function getAllDecoratorsOfAccessors(node: ClassExpression | ClassDeclaration, accessor: AccessorDeclaration): AllDecorators | undefined {
if (!accessor.body) {
return undefined;
}
@@ -1421,7 +1421,7 @@ namespace ts {
*
* @param method The class method member.
*/
function getAllDecoratorsOfMethod(method: MethodDeclaration): AllDecorators {
function getAllDecoratorsOfMethod(method: MethodDeclaration): AllDecorators | undefined {
if (!method.body) {
return undefined;
}
@@ -1440,7 +1440,7 @@ namespace ts {
*
* @param property The class property member.
*/
function getAllDecoratorsOfProperty(property: PropertyDeclaration): AllDecorators {
function getAllDecoratorsOfProperty(property: PropertyDeclaration): AllDecorators | undefined {
const decorators = property.decorators;
if (!decorators) {
return undefined;
@@ -1456,7 +1456,7 @@ namespace ts {
* @param node The declaration node.
* @param allDecorators An object containing all of the decorators for the declaration.
*/
function transformAllDecoratorsOfDeclaration(node: Declaration, container: ClassLikeDeclaration, allDecorators: AllDecorators) {
function transformAllDecoratorsOfDeclaration(node: Declaration, container: ClassLikeDeclaration, allDecorators: AllDecorators | undefined) {
if (!allDecorators) {
return undefined;
}
@@ -1490,7 +1490,7 @@ namespace ts {
*/
function generateClassElementDecorationExpressions(node: ClassExpression | ClassDeclaration, isStatic: boolean) {
const members = getDecoratedClassElements(node, isStatic);
let expressions: Expression[];
let expressions: Expression[] | undefined;
for (const member of members) {
const expression = generateClassElementDecorationExpression(node, member);
if (expression) {
@@ -1624,7 +1624,7 @@ namespace ts {
* @param parameterOffset The offset of the parameter.
*/
function transformDecoratorsOfParameter(decorators: Decorator[], parameterOffset: number) {
let expressions: Expression[];
let expressions: Expression[] | undefined;
if (decorators) {
expressions = [];
for (const decorator of decorators) {
@@ -1672,7 +1672,7 @@ namespace ts {
function addNewTypeMetadata(node: Declaration, container: ClassLikeDeclaration, decoratorExpressions: Expression[]) {
if (compilerOptions.emitDecoratorMetadata) {
let properties: ObjectLiteralElementLike[];
let properties: ObjectLiteralElementLike[] | undefined;
if (shouldAddTypeMetadata(node)) {
(properties || (properties = [])).push(createPropertyAssignment("type", createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, createToken(SyntaxKind.EqualsGreaterThanToken), serializeTypeOfNode(node))));
}
@@ -1837,7 +1837,7 @@ namespace ts {
*
* @param node The type node to serialize.
*/
function serializeTypeNode(node: TypeNode): SerializedTypeNode {
function serializeTypeNode(node: TypeNode | undefined): SerializedTypeNode {
if (node === undefined) {
return createIdentifier("Object");
}
@@ -1920,7 +1920,7 @@ namespace ts {
function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode {
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
let serializedUnion: SerializedTypeNode;
let serializedUnion: SerializedTypeNode | undefined;
for (let typeNode of node.types) {
while (typeNode.kind === SyntaxKind.ParenthesizedType) {
typeNode = (typeNode as ParenthesizedTypeNode).type; // Skip parens if need be
@@ -1964,7 +1964,8 @@ namespace ts {
* @param node The type reference node.
*/
function serializeTypeReferenceNode(node: TypeReferenceNode): SerializedTypeNode {
switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) {
const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope);
switch (kind) {
case TypeReferenceSerializationKind.Unknown:
const serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true);
const temp = createTempVariable(hoistVariableDeclaration);
@@ -2006,8 +2007,9 @@ namespace ts {
return createIdentifier("Promise");
case TypeReferenceSerializationKind.ObjectType:
default:
return createIdentifier("Object");
default:
return Debug.assertNever(kind);
}
}
@@ -2102,7 +2104,7 @@ namespace ts {
* @param member The member whose name should be converted into an expression.
*/
function getExpressionForPropertyName(member: ClassElement | EnumMember, generateNameForComputedPropertyName: boolean): Expression {
const name = member.name;
const name = member.name!;
if (isComputedPropertyName(name)) {
return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
? getGeneratedNameForNode(name)
@@ -2122,7 +2124,7 @@ namespace ts {
* @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
* @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal)
*/
function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean, omitSimple: boolean): Expression {
function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean, omitSimple: boolean): Expression | undefined {
if (isComputedPropertyName(name)) {
const expression = visitNode(name.expression, visitor, isExpression);
const innerExpression = skipPartiallyEmittedExpressions(expression);
@@ -2144,7 +2146,7 @@ namespace ts {
* @param member The member whose name should be visited.
*/
function visitPropertyNameOfClassElement(member: ClassElement): PropertyName {
const name = member.name;
const name = member.name!;
let expr = getPropertyNameExpressionIfNeeded(name, some(member.decorators), /*omitSimple*/ false);
if (expr) { // expr only exists if `name` is a computed property name
// Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
@@ -2168,7 +2170,7 @@ namespace ts {
*
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node: HeritageClause): HeritageClause {
function visitHeritageClause(node: HeritageClause): HeritageClause | undefined {
if (node.token === SyntaxKind.ExtendsKeyword) {
const types = visitNodes(node.types, visitor, isExpressionWithTypeArguments, 0, 1);
return setTextRange(
@@ -2455,7 +2457,7 @@ namespace ts {
* This function will be called when one of the following conditions are met:
* - The node is exported from a TypeScript namespace.
*/
function visitVariableStatement(node: VariableStatement): Statement {
function visitVariableStatement(node: VariableStatement): Statement | undefined {
if (isExportOfNamespace(node)) {
const variables = getInitializedVariables(node.declarationList);
if (variables.length === 0) {
@@ -2493,7 +2495,7 @@ namespace ts {
return setTextRange(
createAssignment(
getNamespaceMemberNameWithSourceMapsAndWithoutComments(name),
visitNode(node.initializer, visitor, isExpression)
visitNode(node.initializer!, visitor, isExpression)
),
/*location*/ node
);
@@ -2766,7 +2768,7 @@ namespace ts {
* @param node The module declaration node.
*/
function shouldEmitModuleDeclaration(node: ModuleDeclaration) {
return isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
return isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
}
/**
@@ -2984,8 +2986,8 @@ namespace ts {
startLexicalEnvironment();
let statementsLocation: TextRange;
let blockLocation: TextRange;
const body = node.body;
let blockLocation: TextRange | undefined;
const body = node.body!;
if (body.kind === SyntaxKind.ModuleBlock) {
saveStateAndInvoke(body, body => addRange(statements, visitNodes((<ModuleBlock>body).statements, namespaceElementVisitor, isStatement)));
statementsLocation = body.statements;
@@ -3002,7 +3004,7 @@ namespace ts {
}
}
const moduleBlock = <ModuleBlock>getInnerMostModuleDeclarationFromDottedModule(node).body;
const moduleBlock = <ModuleBlock>getInnerMostModuleDeclarationFromDottedModule(node)!.body;
statementsLocation = moveRangePos(moduleBlock.statements, -1);
}
@@ -3046,8 +3048,8 @@ namespace ts {
return block;
}
function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration {
if (moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) {
function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration | undefined {
if (moduleDeclaration.body!.kind === SyntaxKind.ModuleDeclaration) {
const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(<ModuleDeclaration>moduleDeclaration.body);
return recursiveInnerModule || <ModuleDeclaration>moduleDeclaration.body;
}
@@ -3138,7 +3140,7 @@ namespace ts {
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
if (!node.exportClause) {
// Elide a star export if the module it references does not export a value.
return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier!) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
@@ -3494,7 +3496,7 @@ namespace ts {
|| node;
}
function trySubstituteClassAlias(node: Identifier): Expression {
function trySubstituteClassAlias(node: Identifier): Expression | undefined {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.ClassAliases) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ConstructorReferenceInClass) {
// Due to the emit for class decorators, any reference to the class from inside of the class body
@@ -3504,7 +3506,7 @@ namespace ts {
// constructor references in static property initializers.
const declaration = resolver.getReferencedValueDeclaration(node);
if (declaration) {
const classAlias = classAliases[declaration.id];
const classAlias = classAliases[declaration.id!]; // TODO: GH#18217
if (classAlias) {
const clone = getSynthesizedClone(classAlias);
setSourceMapRange(clone, node);
@@ -3518,7 +3520,7 @@ namespace ts {
return undefined;
}
function trySubstituteNamespaceExportedName(node: Identifier): Expression {
function trySubstituteNamespaceExportedName(node: Identifier): Expression | undefined {
// If this is explicitly a local name, do not substitute.
if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) {
// If we are nested within a namespace declaration, we may need to qualifiy
@@ -3569,7 +3571,7 @@ namespace ts {
return node;
}
function tryGetConstEnumValue(node: Node): string | number {
function tryGetConstEnumValue(node: Node): string | number | undefined {
if (compilerOptions.isolatedModules) {
return undefined;
}
+12 -12
View File
@@ -10,19 +10,19 @@ namespace ts {
externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers
exportSpecifiers: Map<ExportSpecifier[]>; // export specifiers by name
exportedBindings: Identifier[][]; // exported names of local declarations
exportedNames: Identifier[]; // all exported names local to module
exportedNames: Identifier[] | undefined; // all exported names local to module
exportEquals: ExportAssignment | undefined; // an export= declaration if one was present
hasExportStarsToExportValues: boolean; // whether this module contains export*
}
function containsDefaultReference(node: NamedImportBindings) {
function containsDefaultReference(node: NamedImportBindings | undefined) {
if (!node) return false;
if (!isNamedImports(node)) return false;
return some(node.elements, isNamedDefaultReference);
}
function isNamedDefaultReference(e: ImportSpecifier) {
return e.propertyName && e.propertyName.escapedText === InternalSymbolName.Default;
function isNamedDefaultReference(e: ImportSpecifier): boolean {
return e.propertyName !== undefined && e.propertyName.escapedText === InternalSymbolName.Default;
}
export function chainBundle(transformSourceFile: (x: SourceFile) => SourceFile): (x: SourceFile | Bundle) => SourceFile | Bundle {
@@ -37,7 +37,7 @@ namespace ts {
}
}
export function getImportNeedsImportStarHelper(node: ImportDeclaration) {
export function getImportNeedsImportStarHelper(node: ImportDeclaration): boolean {
if (!!getNamespaceDeclarationNode(node)) {
return true;
}
@@ -56,9 +56,9 @@ namespace ts {
return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && isDefaultImport(node));
}
export function getImportNeedsImportDefaultHelper(node: ImportDeclaration) {
export function getImportNeedsImportDefaultHelper(node: ImportDeclaration): boolean {
// Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
return !getImportNeedsImportStarHelper(node) && (isDefaultImport(node) || (node.importClause && isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)));
return !getImportNeedsImportStarHelper(node) && (isDefaultImport(node) || (!!node.importClause && isNamedImports(node.importClause.namedBindings!) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
}
export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo {
@@ -66,9 +66,9 @@ namespace ts {
const exportSpecifiers = createMultiMap<ExportSpecifier>();
const exportedBindings: Identifier[][] = [];
const uniqueExports = createMap<boolean>();
let exportedNames: Identifier[];
let exportedNames: Identifier[] | undefined;
let hasExportDefault = false;
let exportEquals: ExportAssignment;
let exportEquals: ExportAssignment | undefined;
let hasExportStarsToExportValues = false;
let hasImportStarOrImportDefault = false;
@@ -105,7 +105,7 @@ namespace ts {
}
else {
// export { x, y }
for (const specifier of (<ExportDeclaration>node).exportClause.elements) {
for (const specifier of (<ExportDeclaration>node).exportClause!.elements) {
if (!uniqueExports.get(idText(specifier.name))) {
const name = specifier.propertyName || specifier.name;
exportSpecifiers.add(idText(name), specifier);
@@ -150,7 +150,7 @@ namespace ts {
}
else {
// export function x() { }
const name = (<FunctionDeclaration>node).name;
const name = (<FunctionDeclaration>node).name!;
if (!uniqueExports.get(idText(name))) {
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
uniqueExports.set(idText(name), true);
@@ -198,7 +198,7 @@ namespace ts {
return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, externalHelpersImportDeclaration };
}
function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map<boolean>, exportedNames: Identifier[]) {
function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map<boolean>, exportedNames: Identifier[] | undefined) {
if (isBindingPattern(decl.name)) {
for (const element of decl.name.elements) {
if (!isOmittedExpression(element)) {
+7 -7
View File
@@ -54,7 +54,7 @@ namespace ts {
const commandLine = parseCommandLine(args);
// Configuration file name (if any)
let configFileName: string;
let configFileName: string | undefined;
if (commandLine.options.locale) {
validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors);
}
@@ -78,7 +78,7 @@ namespace ts {
if (commandLine.options.help || commandLine.options.all) {
printVersion();
printHelp(commandLine.options.all);
printHelp(!!commandLine.options.all);
return sys.exit(ExitStatus.Success);
}
@@ -111,13 +111,13 @@ namespace ts {
if (commandLine.fileNames.length === 0 && !configFileName) {
printVersion();
printHelp(commandLine.options.all);
printHelp(!!commandLine.options.all);
return sys.exit(ExitStatus.Success);
}
const commandLineOptions = commandLine.options;
if (configFileName) {
const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic);
const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic)!; // TODO: GH#18217
updateReportDiagnostic(configParseResult.options);
if (isWatchSet(configParseResult.options)) {
reportWatchModeWithoutSysSupport();
@@ -172,7 +172,7 @@ namespace ts {
}
return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics);
};
const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate;
const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217
watchCompilerHost.afterProgramCreate = builderProgram => {
emitFilesUsingBuilder(builderProgram);
reportStatistics(builderProgram.getProgram());
@@ -184,7 +184,7 @@ namespace ts {
}
function createWatchOfConfigFile(configParseResult: ParsedCommandLine, optionsToExtend: CompilerOptions) {
const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options));
const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath!, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); // TODO: GH#18217
updateWatchCompilationHost(watchCompilerHost);
watchCompilerHost.configFileParsingResult = configParseResult;
createWatchProgram(watchCompilerHost);
@@ -306,7 +306,7 @@ namespace ts {
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
const optsList = showAllOptions ?
sort(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) :
filter(optionDeclarations.slice(), v => v.showInSimplifiedHelpView);
filter(optionDeclarations.slice(), v => !!v.showInSimplifiedHelpView);
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
+217 -169
View File
File diff suppressed because it is too large Load Diff
+241 -190
View File
File diff suppressed because it is too large Load Diff
+28 -28
View File
@@ -9,7 +9,7 @@ namespace ts {
* @param test A callback to execute to verify the Node is valid.
* @param lift An optional callback to execute to lift a NodeArray into a valid Node.
*/
export function visitNode<T extends Node>(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T;
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T;
/**
* Visits a Node using the supplied visitor, possibly returning a new Node in its place.
@@ -19,9 +19,9 @@ namespace ts {
* @param test A callback to execute to verify the Node is valid.
* @param lift An optional callback to execute to lift a NodeArray into a valid Node.
*/
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined;
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined;
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined {
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined {
if (node === undefined || visitor === undefined) {
return node;
}
@@ -32,7 +32,7 @@ namespace ts {
return node;
}
let visitedNode: Node;
let visitedNode: Node | undefined;
if (visited === undefined) {
return undefined;
}
@@ -44,7 +44,7 @@ namespace ts {
}
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
aggregateTransformFlags(visitedNode!);
return <T>visitedNode;
}
@@ -57,7 +57,7 @@ namespace ts {
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node>(nodes: NodeArray<T>, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T>;
export function visitNodes<T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T>;
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
@@ -84,7 +84,7 @@ namespace ts {
return nodes;
}
let updated: MutableNodeArray<T>;
let updated: MutableNodeArray<T> | undefined;
// Ensure start and count have valid values
const length = nodes.length;
@@ -152,7 +152,7 @@ namespace ts {
* Starts a new lexical environment and visits a parameter list, suspending the lexical
* environment upon completion.
*/
export function visitParameterList(nodes: NodeArray<ParameterDeclaration>, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes) {
export function visitParameterList(nodes: NodeArray<ParameterDeclaration> | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes) {
context.startLexicalEnvironment();
const updated = nodesVisitor(nodes, visitor, isParameterDeclaration);
context.suspendLexicalEnvironment();
@@ -174,7 +174,7 @@ namespace ts {
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody;
export function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody {
export function visitFunctionBody(node: ConciseBody | undefined, visitor: Visitor, context: TransformationContext): ConciseBody | undefined {
context.resumeLexicalEnvironment();
const updated = visitNode(node, visitor, isConciseBody);
const declarations = context.endLexicalEnvironment();
@@ -204,7 +204,7 @@ namespace ts {
*/
export function visitEachChild<T extends Node>(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined;
export function visitEachChild(node: Node, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes, tokenVisitor?: Visitor): Node {
export function visitEachChild(node: Node | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes, tokenVisitor?: Visitor): Node | undefined {
if (node === undefined) {
return undefined;
}
@@ -290,14 +290,14 @@ namespace ts {
nodesVisitor((<MethodDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList((<MethodDeclaration>node).parameters, visitor, context, nodesVisitor),
visitNode((<MethodDeclaration>node).type, visitor, isTypeNode),
visitFunctionBody((<MethodDeclaration>node).body, visitor, context));
visitFunctionBody((<MethodDeclaration>node).body!, visitor, context));
case SyntaxKind.Constructor:
return updateConstructor(<ConstructorDeclaration>node,
nodesVisitor((<ConstructorDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ConstructorDeclaration>node).modifiers, visitor, isModifier),
visitParameterList((<ConstructorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((<ConstructorDeclaration>node).body, visitor, context));
visitFunctionBody((<ConstructorDeclaration>node).body!, visitor, context));
case SyntaxKind.GetAccessor:
return updateGetAccessor(<GetAccessorDeclaration>node,
@@ -306,7 +306,7 @@ namespace ts {
visitNode((<GetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<GetAccessorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitNode((<GetAccessorDeclaration>node).type, visitor, isTypeNode),
visitFunctionBody((<GetAccessorDeclaration>node).body, visitor, context));
visitFunctionBody((<GetAccessorDeclaration>node).body!, visitor, context));
case SyntaxKind.SetAccessor:
return updateSetAccessor(<SetAccessorDeclaration>node,
@@ -314,7 +314,7 @@ namespace ts {
nodesVisitor((<SetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<SetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<SetAccessorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((<SetAccessorDeclaration>node).body, visitor, context));
visitFunctionBody((<SetAccessorDeclaration>node).body!, visitor, context));
case SyntaxKind.CallSignature:
return updateCallSignature(<CallSignatureDeclaration>node,
@@ -333,7 +333,7 @@ namespace ts {
nodesVisitor((<IndexSignatureDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<IndexSignatureDeclaration>node).modifiers, visitor, isModifier),
nodesVisitor((<IndexSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<IndexSignatureDeclaration>node).type, visitor, isTypeNode));
visitNode((<IndexSignatureDeclaration>node).type!, visitor, isTypeNode));
// Types
@@ -555,7 +555,7 @@ namespace ts {
case SyntaxKind.YieldExpression:
return updateYield(<YieldExpression>node,
visitNode((<YieldExpression>node).asteriskToken, tokenVisitor, isToken),
visitNode((<YieldExpression>node).expression, visitor, isExpression));
visitNode((<YieldExpression>node).expression!, visitor, isExpression));
case SyntaxKind.SpreadElement:
return updateSpread(<SpreadElement>node,
@@ -674,7 +674,7 @@ namespace ts {
case SyntaxKind.ThrowStatement:
return updateThrow(<ThrowStatement>node,
visitNode((<ThrowStatement>node).expression, visitor, isExpression));
visitNode((<ThrowStatement>node).expression!, visitor, isExpression));
case SyntaxKind.TryStatement:
return updateTry(<TryStatement>node,
@@ -848,7 +848,7 @@ namespace ts {
case SyntaxKind.JsxAttribute:
return updateJsxAttribute(<JsxAttribute>node,
visitNode((<JsxAttribute>node).name, visitor, isIdentifier),
visitNode((<JsxAttribute>node).initializer, visitor, isStringLiteralOrJsxExpression));
visitNode((<JsxAttribute>node).initializer!, visitor, isStringLiteralOrJsxExpression));
case SyntaxKind.JsxAttributes:
return updateJsxAttributes(<JsxAttributes>node,
@@ -930,7 +930,7 @@ namespace ts {
*
* @param nodes The NodeArray.
*/
function extractSingleNode(nodes: ReadonlyArray<Node>): Node {
function extractSingleNode(nodes: ReadonlyArray<Node>): Node | undefined {
Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
return singleOrUndefined(nodes);
}
@@ -938,11 +938,11 @@ namespace ts {
/* @internal */
namespace ts {
function reduceNode<T>(node: Node, f: (memo: T, node: Node) => T, initial: T) {
function reduceNode<T>(node: Node | undefined, f: (memo: T, node: Node) => T, initial: T) {
return node ? f(initial, node) : initial;
}
function reduceNodeArray<T>(nodes: NodeArray<Node>, f: (memo: T, nodes: NodeArray<Node>) => T, initial: T) {
function reduceNodeArray<T>(nodes: NodeArray<Node> | undefined, f: (memo: T, nodes: NodeArray<Node>) => T, initial: T) {
return nodes ? f(initial, nodes) : initial;
}
@@ -954,12 +954,12 @@ namespace ts {
* @param initial The initial value to supply to the reduction.
* @param f The callback function
*/
export function reduceEachChild<T>(node: Node, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: NodeArray<Node>) => T): T {
export function reduceEachChild<T>(node: Node | undefined, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: NodeArray<Node>) => T): T {
if (node === undefined) {
return initial;
}
const reduceNodes: (nodes: NodeArray<Node>, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray<Node>) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const reduceNodes: (nodes: NodeArray<Node> | undefined, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray<Node>) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const cbNodes = cbNodeArray || cbNode;
const kind = node.kind;
@@ -1456,13 +1456,13 @@ namespace ts {
/**
* Merges generated lexical declarations into a new statement list.
*/
export function mergeLexicalEnvironment(statements: NodeArray<Statement>, declarations: ReadonlyArray<Statement>): NodeArray<Statement>;
export function mergeLexicalEnvironment(statements: NodeArray<Statement>, declarations: ReadonlyArray<Statement> | undefined): NodeArray<Statement>;
/**
* Appends generated lexical declarations to an array of statements.
*/
export function mergeLexicalEnvironment(statements: Statement[], declarations: ReadonlyArray<Statement>): Statement[];
export function mergeLexicalEnvironment(statements: Statement[] | NodeArray<Statement>, declarations: ReadonlyArray<Statement>) {
export function mergeLexicalEnvironment(statements: Statement[], declarations: ReadonlyArray<Statement> | undefined): Statement[];
export function mergeLexicalEnvironment(statements: Statement[] | NodeArray<Statement>, declarations: ReadonlyArray<Statement> | undefined) {
if (!some(declarations)) {
return statements;
}
@@ -1566,10 +1566,10 @@ namespace ts {
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
assertNode)
: noop;
+44 -41
View File
@@ -4,7 +4,7 @@ namespace ts {
getCurrentDirectory: () => sys.getCurrentDirectory(),
getNewLine: () => sys.newLine,
getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames)
} : undefined;
} : undefined!; // TODO: GH#18217
/**
* Create a function that reports error by writing to the system and handles the formating of the diagnostic
@@ -23,7 +23,7 @@ namespace ts {
return diagnostic => {
diagnostics[0] = diagnostic;
system.write(formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
diagnostics[0] = undefined;
diagnostics[0] = undefined!; // TODO: GH#18217
};
}
@@ -91,7 +91,7 @@ namespace ts {
const host: ParseConfigFileHost = <any>system;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic);
const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined;
host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217
return result;
}
@@ -177,9 +177,9 @@ namespace ts {
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
function createWatchCompilerHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost<T> {
function createWatchCompilerHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram: CreateProgram<T> | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost<T> {
if (!createProgram) {
createProgram = createEmitAndSemanticDiagnosticsBuilderProgram as any;
createProgram = createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram<T>;
}
let host: DirectoryStructureHost = system;
@@ -197,18 +197,18 @@ namespace ts {
directoryExists: path => system.directoryExists(path),
getDirectories: path => system.getDirectories(path),
readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth),
realpath: system.realpath && (path => system.realpath(path)),
realpath: system.realpath && (path => system.realpath!(path)),
getEnvironmentVariable: system.getEnvironmentVariable && (name => system.getEnvironmentVariable(name)),
watchFile: system.watchFile ? ((path, callback, pollingInterval) => system.watchFile(path, callback, pollingInterval)) : () => noopFileWatcher,
watchDirectory: system.watchDirectory ? ((path, callback, recursive) => system.watchDirectory(path, callback, recursive)) : () => noopFileWatcher,
setTimeout: system.setTimeout ? ((callback, ms, ...args: any[]) => system.setTimeout.call(system, callback, ms, ...args)) : noop,
clearTimeout: system.clearTimeout ? (timeoutId => system.clearTimeout(timeoutId)) : noop,
watchFile: system.watchFile ? ((path, callback, pollingInterval) => system.watchFile!(path, callback, pollingInterval)) : () => noopFileWatcher,
watchDirectory: system.watchDirectory ? ((path, callback, recursive) => system.watchDirectory!(path, callback, recursive)) : () => noopFileWatcher,
setTimeout: system.setTimeout ? ((callback, ms, ...args: any[]) => system.setTimeout!.call(system, callback, ms, ...args)) : noop,
clearTimeout: system.clearTimeout ? (timeoutId => system.clearTimeout!(timeoutId)) : noop,
trace: s => system.write(s),
onWatchStatusChange,
createDirectory: path => system.createDirectory(path),
writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
onCachedDirectoryStructureHostCreate: cacheHost => host = cacheHost || system,
createHash: system.createHash && (s => system.createHash(s)),
createHash: system.createHash && (s => system.createHash!(s)),
createProgram,
afterProgramCreate: emitFilesAndReportErrorUsingBuilder
};
@@ -246,9 +246,9 @@ namespace ts {
* Creates the watch compiler host from system for config file in watch mode
*/
export function createWatchCompilerHostOfConfigFile<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile<T> {
reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system);
const host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) as WatchCompilerHostOfConfigFile<T>;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic);
const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
const host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus) as WatchCompilerHostOfConfigFile<T>;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic);
host.configFileName = configFileName;
host.optionsToExtend = optionsToExtend;
return host;
@@ -270,6 +270,8 @@ namespace ts {
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
export type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>) => T;
export interface WatchCompilerHost<T extends BuilderProgram> {
// TODO: GH#18217 Optional methods are frequently asserted
/**
* Used to create the program when need for program creation or recreation detected
*/
@@ -314,12 +316,12 @@ namespace ts {
/** If provided would be used to write log about compilation */
trace?(s: string): void;
/** If provided is used to get the environment variable */
getEnvironmentVariable?(name: string): string;
getEnvironmentVariable?(name: string): string | undefined;
/** If provided, used to resolve the module names, otherwise typescript's default module resolution */
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
/** If provided, used to resolve type reference directives, otherwise typescript's default resolution */
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[];
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
/** Used to watch changes in source files, missing files needed to update the program or config file */
watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher;
@@ -334,6 +336,7 @@ namespace ts {
/** Internal interface used to wire emit through same host */
/*@internal*/
export interface WatchCompilerHost<T extends BuilderProgram> {
// TODO: GH#18217 Optional methods are frequently asserted
createDirectory?(path: string): void;
writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void;
onCachedDirectoryStructureHostCreate?(host: CachedDirectoryStructureHost): void;
@@ -405,7 +408,7 @@ namespace ts {
export function createWatchCompilerHost<T extends BuilderProgram>(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile<T>;
export function createWatchCompilerHost<T extends BuilderProgram>(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions<T> | WatchCompilerHostOfConfigFile<T> {
if (isArray(rootFilesOrConfigFileName)) {
return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus);
return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217
}
else {
return createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus);
@@ -442,7 +445,7 @@ namespace ts {
let timerToUpdateProgram: any; // timer callback to recompile the program
const sourceFilesCache = createMap<HostFileInfo>(); // Cache that stores the source file and version info
let missingFilePathsRequestedForRelease: Path[]; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
let missingFilePathsRequestedForRelease: Path[] | undefined; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
let hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
let hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
@@ -456,14 +459,14 @@ namespace ts {
let configFileParsingDiagnostics: ReadonlyArray<Diagnostic> | undefined;
let hasChangedConfigFileParsingErrors = false;
const cachedDirectoryStructureHost = configFileName && createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
const cachedDirectoryStructureHost = configFileName === undefined ? undefined : createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) {
host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost);
}
const directoryStructureHost: DirectoryStructureHost = cachedDirectoryStructureHost || host;
const parseConfigFileHost: ParseConfigFileHost = {
useCaseSensitiveFileNames,
readDirectory: (path, extensions, exclude, include, depth) => directoryStructureHost.readDirectory(path, extensions, exclude, include, depth),
readDirectory: (path, extensions, exclude, include, depth) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth),
fileExists: path => host.fileExists(path),
readFile,
getCurrentDirectory,
@@ -485,10 +488,10 @@ namespace ts {
newLine = updateNewLine();
}
const trace = host.trace && ((s: string) => { host.trace(s + newLine); });
const trace = host.trace && ((s: string) => { host.trace!(s + newLine); });
const watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? WatchLogLevel.Verbose :
compilerOptions.diagnostis ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None;
const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? trace : noop;
const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? trace! : noop; // TODO: GH#18217
const { watchFile, watchFilePath, watchDirectory } = getWatchFactory<string>(watchLogLevel, writeLog);
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
@@ -502,7 +505,7 @@ namespace ts {
// Members for CompilerHost
getSourceFile: (fileName, languageVersion, onError?, shouldCreateNewSourceFile?) => getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile),
getSourceFileByPath: getVersionedSourceFileByPath,
getDefaultLibLocation: host.getDefaultLibLocation && (() => host.getDefaultLibLocation()),
getDefaultLibLocation: host.getDefaultLibLocation && (() => host.getDefaultLibLocation!()),
getDefaultLibFileName: options => host.getDefaultLibFileName(options),
writeFile,
getCurrentDirectory,
@@ -512,12 +515,12 @@ namespace ts {
fileExists,
readFile,
trace,
directoryExists: directoryStructureHost.directoryExists && (path => directoryStructureHost.directoryExists(path)),
getDirectories: directoryStructureHost.getDirectories && (path => directoryStructureHost.getDirectories(path)),
realpath: host.realpath && (s => host.realpath(s)),
getEnvironmentVariable: host.getEnvironmentVariable ? (name => host.getEnvironmentVariable(name)) : (() => ""),
directoryExists: directoryStructureHost.directoryExists && (path => directoryStructureHost.directoryExists!(path)),
getDirectories: (directoryStructureHost.getDirectories && ((path: string) => directoryStructureHost.getDirectories!(path)))!, // TODO: GH#18217
realpath: host.realpath && (s => host.realpath!(s)),
getEnvironmentVariable: host.getEnvironmentVariable ? (name => host.getEnvironmentVariable!(name)) : (() => ""),
onReleaseOldSourceFile,
createHash: host.createHash && (data => host.createHash(data)),
createHash: host.createHash && (data => host.createHash!(data)),
// Members for ResolutionCacheHost
toPath,
getCompilationSettings: () => compilerOptions,
@@ -541,10 +544,10 @@ namespace ts {
);
// Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
compilerHost.resolveModuleNames = host.resolveModuleNames ?
((moduleNames, containingFile, reusedNames) => host.resolveModuleNames(moduleNames, containingFile, reusedNames)) :
((moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames)) :
((moduleNames, containingFile, reusedNames) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames));
compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
((typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile)) :
((typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(typeDirectiveNames, containingFile)) :
((typeDirectiveNames, containingFile) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile));
const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
@@ -659,15 +662,15 @@ namespace ts {
const path = toPath(fileName);
// If file is missing on host from cache, we can definitely say file doesnt exist
// otherwise we need to ensure from the disk
if (isFileMissingOnHost(sourceFilesCache.get(path))) {
if (isFileMissingOnHost(sourceFilesCache.get(path)!)) {
return true;
}
return directoryStructureHost.fileExists(fileName);
}
function getVersionedSourceFileByPath(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile {
const hostSourceFile = sourceFilesCache.get(path);
function getVersionedSourceFileByPath(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined {
const hostSourceFile = sourceFilesCache.get(path)!;
// No source file on the host
if (isFileMissingOnHost(hostSourceFile)) {
return undefined;
@@ -712,7 +715,7 @@ namespace ts {
return hostSourceFile.sourceFile;
function getNewSourceFile() {
let text: string;
let text: string | undefined;
try {
performance.mark("beforeIORead");
text = host.readFile(fileName, compilerOptions.charset);
@@ -742,7 +745,7 @@ namespace ts {
}
}
function getSourceVersion(path: Path): string {
function getSourceVersion(path: Path): string | undefined {
const hostSourceFile = sourceFilesCache.get(path);
return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
}
@@ -843,13 +846,13 @@ namespace ts {
}
function parseConfigFile() {
setConfigFileParsingResult(getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost));
setConfigFileParsingResult(getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)!); // TODO: GH#18217
}
function setConfigFileParsingResult(configFileParseResult: ParsedCommandLine) {
rootFileNames = configFileParseResult.fileNames;
compilerOptions = configFileParseResult.options;
configFileSpecs = configFileParseResult.configFileSpecs;
configFileSpecs = configFileParseResult.configFileSpecs!; // TODO: GH#18217
configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult);
hasChangedConfigFileParsingErrors = true;
}
@@ -881,7 +884,7 @@ namespace ts {
updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
if (eventKind === FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
missingFilesMap.get(missingFilePath).close();
missingFilesMap.get(missingFilePath)!.close();
missingFilesMap.delete(missingFilePath);
// Delete the entry in the source files cache so that new source file is created
@@ -941,10 +944,10 @@ namespace ts {
}
function ensureDirectoriesExist(directoryPath: string) {
if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists(directoryPath)) {
if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists!(directoryPath)) {
const parentDirectory = getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
host.createDirectory(directoryPath);
host.createDirectory!(directoryPath);
}
}
@@ -953,7 +956,7 @@ namespace ts {
performance.mark("beforeIOWrite");
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
host.writeFile(fileName, text, writeByteOrderMark);
host.writeFile!(fileName, text, writeByteOrderMark);
performance.mark("afterIOWrite");
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");

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