Merge branch 'master' into release-3.3

This commit is contained in:
Daniel Rosenwasser
2019-01-28 09:44:50 -08:00
135 changed files with 4032 additions and 801 deletions
+1
View File
@@ -121,6 +121,7 @@ Ken Howard <ken@simplicatedweb.com>
Kevin Lang <klang2012@gmail.com>
kimamula <kenji.imamula@gmail.com> # Kenji Imamula
Kitson Kelly <me@kitsonkelly.com>
Krishnadas Babu <krishnadas100033@gmail.com>
Klaus Meinhardt <klaus.meinhardt1@gmail.com>
Kyle Kelley <rgbkrk@gmail.com>
Lorant Pinter <lorant.pinter@prezi.com>
+10
View File
@@ -47,6 +47,16 @@ In general, things we find useful when reviewing suggestions are:
# Instructions for Contributing Code
## Tips
### Faster clones
The TypeScript repository is relatively large. To save some time, you might want to clone it without the repo's full history using `git clone --depth=1`.
### Using local builds
Run `gulp build` to build a version of the compiler/language service that reflects changes you've made. You can then run `node <repo-root>/built/local/tsc.js` in place of `tsc` in your project. For example, to run `tsc --watch` from within the root of the repository on a file called `test.ts`, you can run `node ./built/local/tsc.js --watch test.ts`.
## Contributing bug fixes
TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort.
+45 -31
View File
@@ -138,7 +138,7 @@ gulp.task(typescriptServicesProject, /*help*/ false, () => {
compilerOptions: {
"removeComments": false,
"stripInternal": true,
"declarationMap": false,
"declaration": true,
"outFile": "typescriptServices.out.js" // must align with same task in jakefile. We fix this name below.
}
});
@@ -215,6 +215,11 @@ const tsserverProject = "src/tsserver/tsconfig.json";
const tsserverJs = "built/local/tsserver.js";
gulp.task(tsserverJs, /*help*/ false, useCompilerDeps, () => project.compile(tsserverProject, { typescript: useCompiler }));
gulp.task(
"tsserver",
"Builds the language server",
[tsserverJs]);
const watchGuardProject = "src/watchGuard/tsconfig.json";
const watchGuardJs = "built/local/watchGuard.js";
gulp.task(watchGuardJs, /*help*/ false, useCompilerDeps, () => project.compile(watchGuardProject, { typescript: useCompiler }));
@@ -274,7 +279,7 @@ gulp.task(
// Generate Markdown spec
const specMd = "doc/spec.md";
gulp.task(specMd, /*help*/ false, [word2mdJs], () =>
exec("cscript", ["//nologo", word2mdJs, path.resolve(specMd), path.resolve("doc/TypeScript Language Specification.docx")]));
exec("cscript", ["//nologo", word2mdJs, path.resolve("doc/TypeScript Language Specification.docx"), path.resolve(specMd)]));
gulp.task(
"generate-spec",
@@ -488,29 +493,28 @@ gulp.task(
"Runs 'local'",
["local"]);
gulp.task(
"watch-diagnostics",
/*help*/ false,
[processDiagnosticMessagesJs],
() => gulp.watch([diagnosticMessagesJson], [diagnosticInformationMapTs, builtGeneratedDiagnosticMessagesJson]));
gulp.task(
"watch-lib",
/*help*/ false,
() => gulp.watch(["src/lib/**/*"], ["lib"]));
const watchTscPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/tsc/**/*",
];
gulp.task(
"watch-tsc",
/*help*/ false,
["watch-diagnostics", "watch-lib"].concat(useCompilerDeps),
() => project.watch(tscProject, { typescript: useCompiler }));
useCompilerDeps,
() => gulp.watch(watchTscPatterns, ["tsc"]));
const watchServicesPatterns = [
"src/compiler/**/*",
"src/jsTypings/**/*",
"src/services/**/*"
];
gulp.task(
"watch-services",
/*help*/ false,
@@ -522,39 +526,49 @@ const watchLsslPatterns = [
"src/server/**/*",
"src/tsserver/tsconfig.json"
];
gulp.task(
"watch-lssl",
/*help*/ false,
() => gulp.watch(watchLsslPatterns, ["lssl"]));
gulp.task(
"watch-server",
/*help*/ false,
["watch-diagnostics", "watch-lib"].concat(useCompilerDeps),
() => project.watch(tsserverProject, { typescript: useCompiler }));
gulp.task(
"watch-runner",
/*help*/ false,
useCompilerDeps,
() => project.watch(testRunnerProject, { typescript: useCompiler }));
const watchLocalPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/tsc/**/*",
"src/services/**/*",
"src/jsTyping/**/*",
"src/server/**/*",
"src/tsserver/**/*",
"src/typingsInstallerCore/**/*",
"src/harness/**/*",
"src/testRunner/**/*",
];
gulp.task(
"watch-local",
"Watches for changes to projects in src/ (but does not execute tests).",
["watch-lib", "watch-tsc", "watch-services", "watch-server", "watch-runner", "watch-lssl"]);
() => gulp.watch(watchLocalPatterns, ["local"]));
const watchPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/services/**/*",
"src/jsTyping/**/*",
"src/server/**/*",
"src/tsserver/**/*",
"src/typingsInstallerCore/**/*",
"src/harness/**/*",
"src/testRunner/**/*",
];
gulp.task(
"watch",
"Watches for changes to the build inputs for built/local/run.js, then runs tests.",
["build-rules", "watch-runner", "watch-services", "watch-lssl"],
["build-rules"],
() => {
const sem = new Semaphore(1);
gulp.watch([runJs, typescriptDts, tsserverlibraryDts], () => {
runTests();
});
gulp.watch(watchPatterns, () => { runTests(); });
// NOTE: gulp.watch is far too slow when watching tests/cases/**/* as it first enumerates *every* file
const testFilePattern = /(\.ts|[\\/]tsconfig\.json)$/;
@@ -586,7 +600,7 @@ gulp.task(
project.waitForWorkToStart().then(() => {
source.cancel();
});
if (cmdLineOptions.tests || cmdLineOptions.failed) {
await runConsoleTests(runJs, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ true, source.token);
}
@@ -623,4 +637,4 @@ gulp.task(
"clean:scripts",
"clean-rules",
"clean-built"
]);
]);
+1 -1
View File
@@ -361,7 +361,7 @@ file(ConfigFileFor.tsserverLibrary, [], function () {
compilerOptions: {
"removeComments": false,
"stripInternal": true,
"declarationMap": false,
"declaration": true,
"outFile": "tsserverlibrary.out.js"
}
})
+1 -1
View File
@@ -1,5 +1,5 @@
[![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript)
[![VSTS Build Status](https://typescript.visualstudio.com/_apis/public/build/definitions/cf7ac146-d525-443c-b23c-0d58337efebc/4/badge)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=4&view=logs)
[![VSTS Build Status](https://dev.azure.com/typescript/TypeScript/_apis/build/status/Typescript/node10)](https://dev.azure.com/typescript/TypeScript/_build/latest?definitionId=4&view=logs)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
+5 -5
View File
@@ -239,7 +239,7 @@ TypeScript is a trademark of Microsoft Corporation.
# <a name="1"/>1 Introduction
JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring.
JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code refactoring.
TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development.
@@ -263,7 +263,7 @@ function f() {
}
```
To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot.
To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screenshot.
&emsp;&emsp;![](images/image1.png)
@@ -411,7 +411,7 @@ We mentioned above that the '$' function behaves differently depending on the ty
This signature denotes that a function may be passed as the parameter of the '$' function. When a function is passed to '$', the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature.
A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot.
A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screenshot.
&emsp;&emsp;![](images/image2.png)
@@ -628,7 +628,7 @@ JavaScript implementations can use these explicit constants to generate efficien
An important goal of TypeScript is to provide accurate and straightforward types for existing JavaScript programming patterns. To that end, TypeScript includes generic types, discussed in the next section, and *overloading on string parameters*, the topic of this section.
JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method.
JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screenshot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method.
&emsp;&emsp;![](images/image3.png)
@@ -639,7 +639,7 @@ var span = document.createElement("span");
span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property
```
In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property.
In the following screenshot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property.
&emsp;&emsp;![](images/image4.png)
+1 -1
View File
@@ -34,7 +34,7 @@ module.exports = minimist(process.argv.slice(2), {
workers: process.env.workerCount || os.cpus().length,
failed: false,
keepFailed: false,
lkg: false,
lkg: true,
dirty: false
}
});
+39 -67
View File
@@ -14,71 +14,14 @@ const ts = require("../../lib/typescript");
const del = require("del");
const needsUpdate = require("./needsUpdate");
const mkdirp = require("./mkdirp");
const prettyTime = require("pretty-hrtime");
const { reportDiagnostics } = require("./diagnostics");
const { CountdownEvent, ManualResetEvent } = require("prex");
const { CountdownEvent, ManualResetEvent, Semaphore } = require("prex");
const workStartedEvent = new ManualResetEvent();
const countdown = new CountdownEvent(0);
class CompilationGulp extends gulp.Gulp {
/**
* @param {boolean} [verbose]
*/
fork(verbose) {
const child = new ForkedGulp(this.tasks);
child.on("task_start", e => {
if (countdown.remainingCount === 0) {
countdown.reset(1);
workStartedEvent.set();
workStartedEvent.reset();
}
else {
countdown.add();
}
if (verbose) {
log('Starting', `'${chalk.cyan(e.task)}' ${chalk.gray(`(${countdown.remainingCount} remaining)`)}...`);
}
});
child.on("task_stop", e => {
countdown.signal();
if (verbose) {
log('Finished', `'${chalk.cyan(e.task)}' after ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`);
}
});
child.on("task_err", e => {
countdown.signal();
if (verbose) {
log(`'${chalk.cyan(e.task)}' ${chalk.red("errored after")} ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`);
log(e.err ? e.err.stack : e.message);
}
});
return child;
}
// @ts-ignore
start() {
throw new Error("Not supported, use fork.");
}
}
class ForkedGulp extends gulp.Gulp {
/**
* @param {gulp.Gulp["tasks"]} tasks
*/
constructor(tasks) {
super();
this.tasks = tasks;
}
// Do not reset tasks
_resetAllTasks() {}
_resetSpecificTasks() {}
_resetTask() {}
}
// internal `Gulp` instance for compilation artifacts.
const compilationGulp = new CompilationGulp();
const compilationGulp = new gulp.Gulp();
/** @type {Map<ResolvedProjectSpec, ProjectGraph>} */
const projectGraphCache = new Map();
@@ -86,6 +29,39 @@ const projectGraphCache = new Map();
/** @type {Map<string, { typescript: string, alias: string, paths: ResolvedPathOptions }>} */
const typescriptAliasMap = new Map();
// TODO: allow concurrent outer builds to be run in parallel
const sem = new Semaphore(1);
/**
* @param {string|string[]} taskName
* @param {() => any} [cb]
*/
function start(taskName, cb) {
return sem.wait().then(() => new Promise((resolve, reject) => {
compilationGulp.start(taskName, err => {
if (err) {
reject(err);
}
else if (cb) {
try {
resolve(cb());
}
catch (e) {
reject(err);
}
}
else {
resolve();
}
});
})).then(() => {
sem.release()
}, e => {
sem.release();
throw e;
});
}
/**
* Defines a gulp orchestration for a TypeScript project, returning a callback that can be used to trigger compilation.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
@@ -98,9 +74,7 @@ function createCompiler(projectSpec, options) {
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, resolvedOptions.paths);
projectGraph.isRoot = true;
const taskName = compileTaskName(ensureCompileTask(projectGraph, resolvedOptions), resolvedOptions.typescript);
return () => new Promise((resolve, reject) => compilationGulp
.fork(resolvedOptions.verbose)
.start(taskName, err => err ? reject(err) : resolve()));
return () => start(taskName);
}
exports.createCompiler = createCompiler;
@@ -139,9 +113,7 @@ function createCleaner(projectSpec, options) {
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, paths);
projectGraph.isRoot = true;
const taskName = cleanTaskName(ensureCleanTask(projectGraph));
return () => new Promise((resolve, reject) => compilationGulp
.fork()
.start(taskName, err => err ? reject(err) : resolve()));
return () => start(taskName);
}
exports.createCleaner = createCleaner;
@@ -811,7 +783,7 @@ function possiblyTriggerRecompilation(config, task) {
function triggerRecompilation(task, config) {
compilationGulp._resetTask(task);
if (config.watchers && config.watchers.size) {
compilationGulp.fork().start(task.name, () => {
start(task.name, () => {
/** @type {Set<string>} */
const taskNames = new Set();
/** @type {((err?: any) => void)[]} */
@@ -831,7 +803,7 @@ function triggerRecompilation(task, config) {
});
}
else {
compilationGulp.fork(/*verbose*/ true).start(task.name);
start(task.name);
}
}
+2 -2
View File
@@ -165,7 +165,7 @@ exports.cleanTestDirs = cleanTestDirs;
function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed) {
const testConfigContents = JSON.stringify({
test: tests ? [tests] : undefined,
runner: runners ? runners.split(",") : undefined,
runners: runners ? runners.split(",") : undefined,
light,
workerCount,
stackTraceLimit,
@@ -192,4 +192,4 @@ function restoreSavedNodeEnv() {
function deleteTemporaryProjectOutput() {
return del(path.join(exports.localBaseline, "projectOutput/"));
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"outDir": "../../built/local/",
"rootDir": ".",
+39 -6
View File
@@ -100,6 +100,8 @@ namespace ts {
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
}
let flowNodeCreated: <T extends FlowNode>(node: T) => T = identity;
const binder = createBinder();
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
@@ -530,6 +532,7 @@ namespace ts {
blockScopeContainer.locals = undefined;
}
if (containerFlags & ContainerFlags.IsControlFlowContainer) {
const saveFlowNodeCreated = flowNodeCreated;
const saveCurrentFlow = currentFlow;
const saveBreakTarget = currentBreakTarget;
const saveContinueTarget = currentContinueTarget;
@@ -553,6 +556,7 @@ namespace ts {
currentContinueTarget = undefined;
activeLabels = undefined;
hasExplicitReturn = false;
flowNodeCreated = identity;
bindChildren(node);
// Reset all reachability check related flags on node (for incremental scenarios)
node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
@@ -579,6 +583,7 @@ namespace ts {
currentReturnTarget = saveReturnTarget;
activeLabels = saveActiveLabels;
hasExplicitReturn = saveHasExplicitReturn;
flowNodeCreated = saveFlowNodeCreated;
}
else if (containerFlags & ContainerFlags.IsInterface) {
seenThisKeyword = false;
@@ -858,7 +863,7 @@ namespace ts {
return antecedent;
}
setFlowNodeReferenced(antecedent);
return { flags, expression, antecedent };
return flowNodeCreated({ flags, expression, antecedent });
}
function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode {
@@ -866,17 +871,17 @@ namespace ts {
return antecedent;
}
setFlowNodeReferenced(antecedent);
return { flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent };
return flowNodeCreated({ flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent });
}
function createFlowAssignment(antecedent: FlowNode, node: Expression | VariableDeclaration | BindingElement): FlowNode {
setFlowNodeReferenced(antecedent);
return { flags: FlowFlags.Assignment, antecedent, node };
return flowNodeCreated({ flags: FlowFlags.Assignment, antecedent, node });
}
function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode {
setFlowNodeReferenced(antecedent);
const res: FlowArrayMutation = { flags: FlowFlags.ArrayMutation, antecedent, node };
const res: FlowArrayMutation = flowNodeCreated({ flags: FlowFlags.ArrayMutation, antecedent, node });
return res;
}
@@ -1080,8 +1085,16 @@ namespace ts {
function bindTryStatement(node: TryStatement): void {
const preFinallyLabel = createBranchLabel();
const preTryFlow = currentFlow;
// TODO: Every statement in try block is potentially an exit point!
const tryPriors: FlowNode[] = [];
const oldFlowNodeCreated = flowNodeCreated;
// We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them
// as possible antecedents of the start of the `catch` or `finally` blocks.
// Don't bother intercepting the call if there's no finally or catch block that needs the information
if (node.catchClause || node.finallyBlock) {
flowNodeCreated = node => (tryPriors.push(node), node);
}
bind(node.tryBlock);
flowNodeCreated = oldFlowNodeCreated;
addAntecedent(preFinallyLabel, currentFlow);
const flowAfterTry = currentFlow;
@@ -1089,12 +1102,32 @@ namespace ts {
if (node.catchClause) {
currentFlow = preTryFlow;
if (tryPriors.length) {
const preCatchFlow = createBranchLabel();
addAntecedent(preCatchFlow, currentFlow);
for (const p of tryPriors) {
addAntecedent(preCatchFlow, p);
}
currentFlow = finishFlowLabel(preCatchFlow);
}
bind(node.catchClause);
addAntecedent(preFinallyLabel, currentFlow);
flowAfterCatch = currentFlow;
}
if (node.finallyBlock) {
// We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block
// (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will
// have the end of the `try` block and the end of the `catch` block)
if (!node.catchClause) {
if (tryPriors.length) {
for (const p of tryPriors) {
addAntecedent(preFinallyLabel, p);
}
}
}
// in finally flow is combined from pre-try/flow from try/flow from catch
// pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
@@ -1142,7 +1175,7 @@ namespace ts {
}
}
if (!(currentFlow.flags & FlowFlags.Unreachable)) {
const afterFinallyFlow: AfterFinallyFlow = { flags: FlowFlags.AfterFinally, antecedent: currentFlow };
const afterFinallyFlow: AfterFinallyFlow = flowNodeCreated({ flags: FlowFlags.AfterFinally, antecedent: currentFlow });
preFinallyFlow.lock = afterFinallyFlow;
currentFlow = afterFinallyFlow;
}
+110 -101
View File
@@ -4855,7 +4855,7 @@ namespace ts {
function getLiteralPropertyNameText(name: PropertyName) {
const type = getLiteralTypeFromPropertyName(name);
return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + (<LiteralType>type).value : undefined;
return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + (<StringLiteralType | NumberLiteralType>type).value : undefined;
}
/** Return the inferred type for a binding element */
@@ -5280,17 +5280,18 @@ namespace ts {
let objectFlags = ObjectFlags.ObjectLiteral;
forEach(pattern.elements, e => {
const name = e.propertyName || <Identifier>e.name;
if (isComputedNonLiteralName(name)) {
// do not include computed properties in the implied type
objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
return;
}
if (e.dotDotDotToken) {
stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
return;
}
const text = getTextOfPropertyName(name);
const exprType = getLiteralTypeFromPropertyName(name);
if (!isTypeUsableAsPropertyName(exprType)) {
// do not include computed properties in the implied type
objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
return;
}
const text = getPropertyNameFromType(exprType);
const flags = SymbolFlags.Property | (e.initializer ? SymbolFlags.Optional : 0);
const symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
@@ -6399,9 +6400,9 @@ namespace ts {
}
/**
* Indicates whether a type can be used as a late-bound name.
* Indicates whether a type can be used as a property name.
*/
function isTypeUsableAsLateBoundName(type: Type): type is LiteralType | UniqueESSymbolType {
function isTypeUsableAsPropertyName(type: Type): type is StringLiteralType | NumberLiteralType | UniqueESSymbolType {
return !!(type.flags & TypeFlags.StringOrNumberLiteralOrUnique);
}
@@ -6416,7 +6417,7 @@ namespace ts {
function isLateBindableName(node: DeclarationName): node is LateBoundName {
return isComputedPropertyName(node)
&& isEntityNameExpression(node.expression)
&& isTypeUsableAsLateBoundName(checkComputedPropertyName(node));
&& isTypeUsableAsPropertyName(checkComputedPropertyName(node));
}
function isLateBoundName(name: __String): boolean {
@@ -6448,14 +6449,14 @@ namespace ts {
}
/**
* Gets the symbolic name for a late-bound member from its type.
* Gets the symbolic name for a member from its type.
*/
function getLateBoundNameFromType(type: LiteralType | UniqueESSymbolType): __String {
function getPropertyNameFromType(type: StringLiteralType | NumberLiteralType | UniqueESSymbolType): __String {
if (type.flags & TypeFlags.UniqueESSymbol) {
return `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}` as __String;
return (<UniqueESSymbolType>type).escapedName;
}
if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) {
return escapeLeadingUnderscores("" + (<LiteralType>type).value);
return escapeLeadingUnderscores("" + (<StringLiteralType | NumberLiteralType>type).value);
}
return Debug.fail();
}
@@ -6518,8 +6519,8 @@ namespace ts {
// fall back to the early-bound name of this member.
links.resolvedSymbol = decl.symbol;
const type = checkComputedPropertyName(decl.name);
if (isTypeUsableAsLateBoundName(type)) {
const memberName = getLateBoundNameFromType(type);
if (isTypeUsableAsPropertyName(type)) {
const memberName = getPropertyNameFromType(type);
const symbolFlags = decl.symbol.flags;
// Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
@@ -6534,9 +6535,9 @@ namespace ts {
// If we have an existing early-bound member, combine its declarations so that we can
// report an error at each declaration.
const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
const name = declarationNameToString(decl.name);
forEach(declarations, declaration => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_declaration_0, name));
error(decl.name || decl, Diagnostics.Duplicate_declaration_0, name);
const name = !(type.flags & TypeFlags.UniqueESSymbol) && unescapeLeadingUnderscores(memberName) || declarationNameToString(decl.name);
forEach(declarations, declaration => error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name));
error(decl.name || decl, Diagnostics.Duplicate_property_0, name);
lateSymbol = createSymbol(SymbolFlags.None, memberName, CheckFlags.Late);
}
lateSymbol.nameType = type;
@@ -7168,8 +7169,8 @@ namespace ts {
const propType = instantiateType(templateType, templateMapper);
// If the current iteration type constituent is a string literal type, create a property.
// Otherwise, for type string create a string index signature.
if (t.flags & TypeFlags.StringOrNumberLiteralOrUnique) {
const propName = getLateBoundNameFromType(t as LiteralType);
if (isTypeUsableAsPropertyName(t)) {
const propName = getPropertyNameFromType(t);
const modifiersProp = getPropertyOfType(modifiersType, propName);
const isOptional = !!(templateModifiers & MappedTypeModifiers.IncludeOptional ||
!(templateModifiers & MappedTypeModifiers.ExcludeOptional) && modifiersProp && modifiersProp.flags & SymbolFlags.Optional);
@@ -7354,7 +7355,8 @@ namespace ts {
function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean {
const list = obj.properties as NodeArray<ObjectLiteralElementLike | JsxAttributeLike>;
return list.some(property => {
const name = property.name && getTextOfPropertyName(property.name);
const nameType = property.name && getLiteralTypeFromPropertyName(property.name);
const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
});
@@ -7741,7 +7743,13 @@ namespace ts {
result.containingType = containingType;
if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
result.valueDeclaration = firstValueDeclaration;
// Inherit information about parent type.
if (firstValueDeclaration.symbol.parent) {
result.parent = firstValueDeclaration.symbol.parent;
}
}
result.declarations = declarations!;
result.nameType = nameType;
result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
@@ -8698,21 +8706,17 @@ namespace ts {
* the type of this reference is just the type of the value we resolved to.
*/
function getJSDocTypeReference(node: NodeWithTypeArguments, symbol: Symbol, typeArguments: Type[] | undefined): Type | undefined {
if (!pushTypeResolution(symbol, TypeSystemPropertyName.JSDocTypeReference)) {
return errorType;
}
const assignedType = getAssignedClassType(symbol);
const valueType = getTypeOfSymbol(symbol);
const referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments);
if (!popTypeResolution()) {
getSymbolLinks(symbol).resolvedJSDocType = errorType;
error(node, Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol));
return errorType;
}
if (referenceType || assignedType) {
// TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?)
const type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType)!;
return getSymbolLinks(symbol).resolvedJSDocType = type;
// In the case of an assignment of a function expression (binary expressions, variable declarations, etc.), we will get the
// correct instance type for the symbol on the LHS by finding the type for RHS. For example if we want to get the type of the symbol `foo`:
// var foo = function() {}
// We will find the static type of the assigned anonymous function.
const staticType = getTypeOfSymbol(symbol);
const instanceType =
staticType.symbol &&
staticType.symbol !== symbol && // Make sure this is an assignment like expression by checking that symbol -> type -> symbol doesn't roundtrips.
getTypeReferenceTypeWorker(node, staticType.symbol, typeArguments); // Get the instance type of the RHS symbol.
if (instanceType) {
return getSymbolLinks(symbol).resolvedJSDocType = instanceType;
}
}
@@ -8733,8 +8737,11 @@ namespace ts {
if (symbol.flags & SymbolFlags.Function &&
isJSDocTypeReference(node) &&
(symbol.members || getJSDocClassTag(symbol.valueDeclaration))) {
return getInferredClassType(symbol);
isJSConstructor(symbol.valueDeclaration)) {
const resolved = resolveStructuredTypeMembers(<ObjectType>getTypeOfSymbol(symbol));
if (resolved.callSignatures.length === 1) {
return getReturnTypeOfSignature(resolved.callSignatures[0]);
}
}
}
@@ -9717,8 +9724,8 @@ namespace ts {
function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, cacheSymbol: boolean, missingType: Type) {
const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined;
const propName = isTypeUsableAsLateBoundName(indexType) ?
getLateBoundNameFromType(indexType) :
const propName = isTypeUsableAsPropertyName(indexType) ?
getPropertyNameFromType(indexType) :
accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
getPropertyNameForKnownSymbolName(idText((<PropertyAccessExpression>accessExpression.argumentExpression).name)) :
accessNode && isPropertyName(accessNode) ?
@@ -9809,7 +9816,7 @@ namespace ts {
if (accessNode) {
const indexNode = getIndexNodeForAccessExpression(accessNode);
if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) {
error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (<LiteralType>indexType).value, typeToString(objectType));
error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (<StringLiteralType | NumberLiteralType>indexType).value, typeToString(objectType));
}
else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) {
error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
@@ -10408,6 +10415,7 @@ namespace ts {
function createUniqueESSymbolType(symbol: Symbol) {
const type = <UniqueESSymbolType>createType(TypeFlags.UniqueESSymbol);
type.symbol = symbol;
type.escapedName = `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}` as __String;
return type;
}
@@ -10628,7 +10636,11 @@ namespace ts {
}
function getRestrictiveTypeParameter(tp: TypeParameter) {
return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol));
return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (
tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
(tp.restrictiveInstantiation as TypeParameter).constraint = unknownType,
tp.restrictiveInstantiation
);
}
function restrictiveMapper(type: Type) {
@@ -11295,7 +11307,7 @@ namespace ts {
}
if (resultObj.error) {
const reportedDiag = resultObj.error;
const propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined;
const propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
const targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
let issuedElaboration = false;
@@ -11754,11 +11766,11 @@ namespace ts {
if (s & TypeFlags.StringLike && t & TypeFlags.String) return true;
if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral &&
t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) &&
(<LiteralType>source).value === (<LiteralType>target).value) return true;
(<StringLiteralType>source).value === (<StringLiteralType>target).value) return true;
if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true;
if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral &&
t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) &&
(<LiteralType>source).value === (<LiteralType>target).value) return true;
(<NumberLiteralType>source).value === (<NumberLiteralType>target).value) return true;
if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true;
if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true;
if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true;
@@ -12671,7 +12683,7 @@ namespace ts {
}
else {
// An empty object type is related to any mapped type that includes a '?' modifier.
if (isPartialMappedType(target) && isEmptyObjectType(source)) {
if (relation !== subtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
return Ternary.True;
}
if (isGenericMappedType(target)) {
@@ -13682,8 +13694,8 @@ namespace ts {
// no flags for all other types (including non-falsy literal types).
function getFalsyFlags(type: Type): TypeFlags {
return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((<UnionType>type).types) :
type.flags & TypeFlags.StringLiteral ? (<LiteralType>type).value === "" ? TypeFlags.StringLiteral : 0 :
type.flags & TypeFlags.NumberLiteral ? (<LiteralType>type).value === 0 ? TypeFlags.NumberLiteral : 0 :
type.flags & TypeFlags.StringLiteral ? (<StringLiteralType>type).value === "" ? TypeFlags.StringLiteral : 0 :
type.flags & TypeFlags.NumberLiteral ? (<NumberLiteralType>type).value === 0 ? TypeFlags.NumberLiteral : 0 :
type.flags & TypeFlags.BigIntLiteral ? isZeroBigInt(<BigIntLiteralType>type) ? TypeFlags.BigIntLiteral : 0 :
type.flags & TypeFlags.BooleanLiteral ? (type === falseType || type === regularFalseType) ? TypeFlags.BooleanLiteral : 0 :
type.flags & TypeFlags.PossiblyFalsy;
@@ -13706,8 +13718,8 @@ namespace ts {
type === regularFalseType ||
type === falseType ||
type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) ||
type.flags & TypeFlags.StringLiteral && (<LiteralType>type).value === "" ||
type.flags & TypeFlags.NumberLiteral && (<LiteralType>type).value === 0 ||
type.flags & TypeFlags.StringLiteral && (<StringLiteralType>type).value === "" ||
type.flags & TypeFlags.NumberLiteral && (<NumberLiteralType>type).value === 0 ||
type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(<BigIntLiteralType>type) ? type :
neverType;
}
@@ -14562,7 +14574,12 @@ namespace ts {
priority |= InferencePriority.MappedTypeConstraint;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(<MappedType>target));
const valueTypes = compact([
getIndexTypeOfType(source, IndexKind.String),
getIndexTypeOfType(source, IndexKind.Number),
...map(getPropertiesOfType(source), getTypeOfSymbol)
]);
inferFromTypes(getUnionType(valueTypes), getTemplateTypeFromMappedType(<MappedType>target));
return true;
}
return false;
@@ -15095,7 +15112,7 @@ namespace ts {
return strictNullChecks ? TypeFacts.StringStrictFacts : TypeFacts.StringFacts;
}
if (flags & TypeFlags.StringLiteral) {
const isEmpty = (<LiteralType>type).value === "";
const isEmpty = (<StringLiteralType>type).value === "";
return strictNullChecks ?
isEmpty ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts :
isEmpty ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts;
@@ -15104,7 +15121,7 @@ namespace ts {
return strictNullChecks ? TypeFacts.NumberStrictFacts : TypeFacts.NumberFacts;
}
if (flags & TypeFlags.NumberLiteral) {
const isZero = (<LiteralType>type).value === 0;
const isZero = (<NumberLiteralType>type).value === 0;
return strictNullChecks ?
isZero ? TypeFacts.ZeroNumberStrictFacts : TypeFacts.NonZeroNumberStrictFacts :
isZero ? TypeFacts.ZeroNumberFacts : TypeFacts.NonZeroNumberFacts;
@@ -15167,7 +15184,9 @@ namespace ts {
}
function getTypeOfDestructuredProperty(type: Type, name: PropertyName) {
const text = getTextOfPropertyName(name);
const nameType = getLiteralTypeFromPropertyName(name);
if (!isTypeUsableAsPropertyName(nameType)) return errorType;
const text = getPropertyNameFromType(nameType);
return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
isNumericLiteralName(text) && getIndexTypeOfType(type, IndexKind.Number) ||
getIndexTypeOfType(type, IndexKind.String) ||
@@ -15775,9 +15794,6 @@ namespace ts {
function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType {
const expr = flow.switchStatement.expression;
if (containsMatchingReferenceDiscriminant(reference, expr)) {
return declaredType;
}
const flowType = getTypeAtFlowNode(flow.antecedent);
let type = getTypeFromFlowType(flowType);
if (isMatchingReference(reference, expr)) {
@@ -15792,6 +15808,9 @@ namespace ts {
else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) {
type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
}
else if (containsMatchingReferenceDiscriminant(reference, expr)) {
type = declaredType;
}
return createFlowType(type, isIncomplete(flowType));
}
@@ -16871,7 +16890,7 @@ namespace ts {
else if (isInJS &&
(container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) &&
getJSDocClassTag(container)) {
const classType = getJSClassType(container.symbol);
const classType = getJSClassType(getMergedSymbol(container.symbol));
if (classType) {
return getFlowTypeOfReference(node, classType);
}
@@ -17299,9 +17318,10 @@ namespace ts {
const parentDeclaration = declaration.parent.parent;
const name = declaration.propertyName || declaration.name;
const parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration);
if (parentType && !isBindingPattern(name)) {
const text = getTextOfPropertyName(name);
if (text !== undefined) {
if (parentType && !isBindingPattern(name) && !isComputedNonLiteralName(name)) {
const nameType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(nameType)) {
const text = getPropertyNameFromType(nameType);
return getTypeOfPropertyOfType(parentType, text);
}
}
@@ -18258,10 +18278,9 @@ namespace ts {
}
}
typeFlags |= type.flags;
const nameType = computedNameType && computedNameType.flags & TypeFlags.StringOrNumberLiteralOrUnique ?
<LiteralType | UniqueESSymbolType>computedNameType : undefined;
const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
const prop = nameType ?
createSymbol(SymbolFlags.Property | member.flags, getLateBoundNameFromType(nameType), CheckFlags.Late) :
createSymbol(SymbolFlags.Property | member.flags, getPropertyNameFromType(nameType), CheckFlags.Late) :
createSymbol(SymbolFlags.Property | member.flags, member.escapedName);
if (nameType) {
prop.nameType = nameType;
@@ -18550,6 +18569,10 @@ namespace ts {
childrenPropSymbol.type = childrenTypes.length === 1 ?
childrenTypes[0] :
(getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
// Fake up a property declaration for the children
childrenPropSymbol.valueDeclaration = createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
childrenPropSymbol.valueDeclaration.parent = attributes;
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
const childPropMap = createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined),
@@ -20412,6 +20435,12 @@ namespace ts {
if (inferenceContext) {
const typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration));
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
candidateForArgumentArityError = checkCandidate;
continue;
}
}
if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
@@ -21041,7 +21070,7 @@ namespace ts {
// If the symbol of the node has members, treat it like a constructor.
const symbol = getSymbolOfNode(func);
return !!symbol && symbol.members !== undefined;
return !!symbol && (symbol.members !== undefined || symbol.exports !== undefined && symbol.exports.get("prototype" as __String) !== undefined);
}
return false;
}
@@ -21060,10 +21089,6 @@ namespace ts {
inferred = getInferredClassType(symbol);
}
const assigned = getAssignedClassType(symbol);
const valueType = getTypeOfSymbol(symbol);
if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) {
inferred = getInferredClassType(valueType.symbol);
}
return assigned && inferred ?
getIntersectionType([inferred, assigned]) :
assigned || inferred;
@@ -21103,12 +21128,6 @@ namespace ts {
return links.inferredClassType;
}
function isInferredClassType(type: Type) {
return type.symbol
&& getObjectFlags(type) & ObjectFlags.Anonymous
&& getSymbolLinks(type.symbol).inferredClassType === type;
}
/**
* Syntactically and semantically checks a call or new expression.
* @param node The call/new expression to be checked.
@@ -21130,21 +21149,10 @@ namespace ts {
declaration.kind !== SyntaxKind.Constructor &&
declaration.kind !== SyntaxKind.ConstructSignature &&
declaration.kind !== SyntaxKind.ConstructorType &&
!isJSDocConstructSignature(declaration)) {
!isJSDocConstructSignature(declaration) &&
!isJSConstructor(declaration)) {
// When resolved signature is a call signature (and not a construct signature) the result type is any, unless
// the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations
// in a JS file
// Note:JS inferred classes might come from a variable declaration instead of a function declaration.
// In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration.
let funcSymbol = checkExpression(node.expression).symbol;
if (!funcSymbol && node.expression.kind === SyntaxKind.Identifier) {
funcSymbol = getResolvedSymbol(node.expression as Identifier);
}
const type = funcSymbol && getJSClassType(funcSymbol);
if (type) {
return signature.target ? instantiateType(type, signature.mapper) : type;
}
// When resolved signature is a call signature (and not a construct signature) the result type is any
if (noImplicitAny) {
error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
}
@@ -22300,7 +22308,7 @@ namespace ts {
if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, TypeFlags.NumberLike | TypeFlags.ESSymbolLike))) {
error(left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
}
if (!isTypeAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) {
if (!allTypesAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) {
error(right, Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
}
return booleanType;
@@ -22321,15 +22329,15 @@ namespace ts {
function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType: Type, property: ObjectLiteralElementLike, allProperties?: NodeArray<ObjectLiteralElementLike>, rightIsThis = false) {
if (property.kind === SyntaxKind.PropertyAssignment || property.kind === SyntaxKind.ShorthandPropertyAssignment) {
const name = property.name;
const text = getTextOfPropertyName(name);
if (text) {
const exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
const text = getPropertyNameFromType(exprType);
const prop = getPropertyOfType(objectLiteralType, text);
if (prop) {
markPropertyAsReferenced(prop, property, rightIsThis);
checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
}
}
const exprType = getLiteralTypeFromPropertyName(name);
const elementType = getIndexedAccessType(objectLiteralType, exprType, name);
const type = getFlowTypeOfDestructuring(property, elementType);
return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type);
@@ -25644,13 +25652,14 @@ namespace ts {
const parent = node.parent.parent;
const parentType = getTypeForBindingElementParent(parent);
const name = node.propertyName || node.name;
if (!isBindingPattern(name)) {
const nameText = getTextOfPropertyName(name);
if (nameText) {
const property = getPropertyOfType(parentType!, nameText); // TODO: GH#18217
if (!isBindingPattern(name) && parentType) {
const exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
const nameText = getPropertyNameFromType(exprType);
const property = getPropertyOfType(parentType, nameText);
if (property) {
markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword, parentType!, property);
checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword, parentType, property);
}
}
}
@@ -26053,7 +26062,7 @@ namespace ts {
? downlevelIteration
? Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
: isIterable
? Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
: Diagnostics.Type_0_is_not_an_array_type
: downlevelIteration
? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
@@ -31184,7 +31193,7 @@ namespace ts {
if (nodeArguments.length !== 1) {
return grammarErrorOnNode(node, Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
}
checkGrammarForDisallowedTrailingComma(nodeArguments);
// see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
// parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
if (isSpreadElement(nodeArguments[0])) {
+5 -2
View File
@@ -884,8 +884,11 @@ namespace ts {
/**
* Compacts an array, removing any falsey elements.
*/
export function compact<T>(array: T[]): T[];
export function compact<T>(array: ReadonlyArray<T>): ReadonlyArray<T>;
export function compact<T>(array: (T | undefined | null | false | 0 | "")[]): T[];
export function compact<T>(array: ReadonlyArray<T | undefined | null | false | 0 | "">): ReadonlyArray<T>;
// TSLint thinks these can be combined with the above - they cannot; they'd produce higher-priority inferences and prevent the falsey types from being stripped
export function compact<T>(array: T[]): T[]; // tslint:disable-line unified-signatures
export function compact<T>(array: ReadonlyArray<T>): ReadonlyArray<T>; // tslint:disable-line unified-signatures
export function compact<T>(array: T[]): T[] {
let result: T[] | undefined;
if (array) {
+5 -5
View File
@@ -2056,10 +2056,6 @@
"category": "Error",
"code": 2567
},
"Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": {
"category": "Error",
"code": 2568
},
"Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": {
"category": "Error",
"code": 2569
@@ -2437,7 +2433,7 @@
"category": "Error",
"code": 2717
},
"Duplicate declaration '{0}'.": {
"Duplicate property '{0}'.": {
"category": "Error",
"code": 2718
},
@@ -2497,6 +2493,10 @@
"category": "Error",
"code": 2732
},
"Property '{0}' was also declared here.": {
"category": "Error",
"code": 2733
},
"It is highly likely that you are missing a semicolon.": {
"category": "Error",
"code": 2734
+14 -9
View File
@@ -38,17 +38,22 @@ namespace ts {
}
}
/*@internal*/
export function getOutputPathsForBundle(options: CompilerOptions, forceDtsPaths: boolean): EmitFileNames {
const outPath = options.outFile || options.out!;
const jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined;
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath };
}
/*@internal*/
export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames {
const options = host.getCompilerOptions();
if (sourceFile.kind === SyntaxKind.Bundle) {
const outPath = options.outFile || options.out!;
const jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined;
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath };
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
@@ -4372,10 +4377,10 @@ namespace ts {
}
/**
* Skips trivia such as comments and white-space that can optionally overriden by the source map source
* Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
*/
function skipSourceTrivia(source: SourceMapSource, pos: number): number {
return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(sourceMapSource.text, pos);
return source.skipTrivia ? source.skipTrivia(pos) : skipTrivia(source.text, pos);
}
/**
+64 -17
View File
@@ -2630,41 +2630,88 @@ namespace ts {
}
export function createUnparsedSourceFile(text: string): UnparsedSource;
export function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
export function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
export function createUnparsedSourceFile(text: string, mapPath?: string, map?: string): UnparsedSource {
export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, mapPathOrType?: string, map?: string): UnparsedSource {
const node = <UnparsedSource>createNode(SyntaxKind.UnparsedSource);
node.text = text;
node.sourceMapPath = mapPath;
node.sourceMapText = map;
if (!isString(textOrInputFiles)) {
Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
}
else {
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
node.sourceMapText = map;
}
return node;
}
export function createInputFiles(
javascript: string,
declaration: string
javascriptText: string,
declarationText: string
): InputFiles;
export function createInputFiles(
javascript: string,
declaration: string,
readFileText: (path: string) => string | undefined,
javascriptPath: string,
javascriptMapPath: string | undefined,
declarationPath: string,
declarationMapPath: string | undefined,
): InputFiles;
export function createInputFiles(
javascriptText: string,
declarationText: string,
javascriptMapPath: string | undefined,
javascriptMapText: string | undefined,
declarationMapPath: string | undefined,
declarationMapText: string | undefined
): InputFiles;
export function createInputFiles(
javascript: string,
declaration: string,
javascriptTextOrReadFileText: string | ((path: string) => string | undefined),
declarationTextOrJavascriptPath: string,
javascriptMapPath?: string,
javascriptMapText?: string,
javascriptMapTextOrDeclarationPath?: string,
declarationMapPath?: string,
declarationMapText?: string
): InputFiles {
const node = <InputFiles>createNode(SyntaxKind.InputFiles);
node.javascriptText = javascript;
node.javascriptMapPath = javascriptMapPath;
node.javascriptMapText = javascriptMapText;
node.declarationText = declaration;
node.declarationMapPath = declarationMapPath;
node.declarationMapText = declarationMapText;
if (!isString(javascriptTextOrReadFileText)) {
const cache = createMap<string | false>();
const textGetter = (path: string | undefined) => {
if (path === undefined) return undefined;
let value = cache.get(path);
if (value === undefined) {
value = javascriptTextOrReadFileText(path);
cache.set(path, value !== undefined ? value : false);
}
return value !== false ? value as string : undefined;
};
const definedTextGetter = (path: string) => {
const result = textGetter(path);
return result !== undefined ? result : `/* Input file ${path} was missing */\r\n`;
};
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
Object.defineProperties(node, {
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
declarationMapText: { get() { return textGetter(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
});
}
else {
node.javascriptText = javascriptTextOrReadFileText;
node.javascriptMapPath = javascriptMapPath;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
node.declarationMapText = declarationMapText;
}
return node;
}
+9 -3
View File
@@ -1093,6 +1093,10 @@ namespace ts {
return currentToken = scanner.reScanTemplateToken();
}
function reScanLessThanToken(): SyntaxKind {
return currentToken = scanner.reScanLessThanToken();
}
function scanJsxIdentifier(): SyntaxKind {
return currentToken = scanner.scanJsxIdentifier();
}
@@ -2276,7 +2280,7 @@ namespace ts {
function parseTypeReference(): TypeReferenceNode {
const node = <TypeReferenceNode>createNode(SyntaxKind.TypeReference);
node.typeName = parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected);
if (!scanner.hasPrecedingLineBreak() && token() === SyntaxKind.LessThanToken) {
if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === SyntaxKind.LessThanToken) {
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
return finishNode(node);
@@ -4523,7 +4527,8 @@ namespace ts {
function parseCallExpressionRest(expression: LeftHandSideExpression): LeftHandSideExpression {
while (true) {
expression = parseMemberExpressionRest(expression);
if (token() === SyntaxKind.LessThanToken) {
// handle 'foo<<T>()'
if (token() === SyntaxKind.LessThanToken || token() === SyntaxKind.LessThanLessThanToken) {
// See if this is the start of a generic invocation. If so, consume it and
// keep checking for postfix expressions. Otherwise, it's just a '<' that's
// part of an arithmetic expression. Break out so we consume it higher in the
@@ -4565,9 +4570,10 @@ namespace ts {
}
function parseTypeArgumentsInExpression() {
if (!parseOptional(SyntaxKind.LessThanToken)) {
if (reScanLessThanToken() !== SyntaxKind.LessThanToken) {
return undefined;
}
nextToken();
const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType);
if (!parseExpected(SyntaxKind.GreaterThanToken)) {
+6 -8
View File
@@ -1456,14 +1456,12 @@ namespace ts {
// Upstream project didn't have outFile set -- skip (error will have been issued earlier)
if (!out) continue;
const dtsFilename = changeExtension(out, ".d.ts");
const js = host.readFile(out) || `/* Input file ${out} was missing */\r\n`;
const jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file
const jsMap = host.readFile(jsMapPath);
const dts = host.readFile(dtsFilename) || `/* Input file ${dtsFilename} was missing */\r\n`;
const dtsMapPath = dtsFilename + ".map";
const dtsMap = host.readFile(dtsMapPath);
const node = createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap);
const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true);
const node = createInputFiles(fileName => {
const path = toPath(fileName);
const sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
}, jsFilePath! , sourceMapFilePath, declarationFilePath! , declarationMapPath);
nodes.push(node);
}
}
+10
View File
@@ -31,6 +31,7 @@ namespace ts {
scanJsxIdentifier(): SyntaxKind;
scanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(): JsxTokenSyntaxKind;
reScanLessThanToken(): SyntaxKind;
scanJsxToken(): JsxTokenSyntaxKind;
scanJSDocToken(): JsDocSyntaxKind;
scan(): SyntaxKind;
@@ -874,6 +875,7 @@ namespace ts {
scanJsxIdentifier,
scanJsxAttributeValue,
reScanJsxToken,
reScanLessThanToken,
scanJsxToken,
scanJSDocToken,
scan,
@@ -1939,6 +1941,14 @@ namespace ts {
return token = scanJsxToken();
}
function reScanLessThanToken(): SyntaxKind {
if (token === SyntaxKind.LessThanLessThanToken) {
pos = tokenPos + 1;
return token = SyntaxKind.LessThanToken;
}
return token;
}
function scanJsxToken(): JsxTokenSyntaxKind {
startPos = tokenPos = pos;
+1 -1
View File
@@ -207,7 +207,7 @@ namespace ts {
}
), mapDefined(node.prepends, prepend => {
if (prepend.kind === SyntaxKind.InputFiles) {
return createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText);
return createUnparsedSourceFile(prepend, "dts");
}
}));
bundle.syntheticFileReferences = [];
+1 -1
View File
@@ -101,7 +101,7 @@ namespace ts {
function transformBundle(node: Bundle) {
return createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, prepend => {
if (prepend.kind === SyntaxKind.InputFiles) {
return createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText);
return createUnparsedSourceFile(prepend, "js");
}
return prepend;
}));
+4
View File
@@ -2761,9 +2761,11 @@ namespace ts {
export interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptPath?: string;
javascriptText: string;
javascriptMapPath?: string;
javascriptMapText?: string;
declarationPath?: string;
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
@@ -2771,6 +2773,7 @@ namespace ts {
export interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
fileName?: string;
text: string;
sourceMapPath?: string;
sourceMapText?: string;
@@ -3952,6 +3955,7 @@ namespace ts {
// Unique symbol types (TypeFlags.UniqueESSymbol)
export interface UniqueESSymbolType extends Type {
symbol: Symbol;
escapedName: __String;
}
export interface StringLiteralType extends LiteralType {
+2 -1
View File
@@ -778,7 +778,8 @@ namespace ts {
case SyntaxKind.NoSubstitutionTemplateLiteral:
return escapeLeadingUnderscores(name.text);
case SyntaxKind.ComputedPropertyName:
return isStringOrNumericLiteralLike(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined!; // TODO: GH#18217 Almost all uses of this assume the result to be defined!
if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text);
return Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
default:
return Debug.assertNever(name);
}
+1 -1
View File
@@ -4,5 +4,5 @@ The files within this directory are used to generate `lib.d.ts` and `lib.es6.d.t
## Generated files
Any files ending in `.generated.d.ts` aren't mean to be edited by hand.
Any files ending in `.generated.d.ts` aren't meant to be edited by hand.
If you need to make changes to such files, make a change to the input files for [**our library generator**](https://github.com/Microsoft/TSJS-lib-generator).
+64 -10
View File
@@ -587,7 +587,7 @@ interface TemplateStringsArray extends ReadonlyArray<string> {
/**
* The type of `import.meta`.
*
*
* If you need to declare that a given property exists on `import.meta`,
* this type may be augmented via interface merging.
*/
@@ -1913,13 +1913,19 @@ interface Int8ArrayConstructor {
*/
of(...items: number[]): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array;
}
@@ -2183,13 +2189,19 @@ interface Uint8ArrayConstructor {
*/
of(...items: number[]): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;
}
declare const Uint8Array: Uint8ArrayConstructor;
@@ -2452,13 +2464,19 @@ interface Uint8ClampedArrayConstructor {
*/
of(...items: number[]): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
declare const Uint8ClampedArray: Uint8ClampedArrayConstructor;
@@ -2719,13 +2737,19 @@ interface Int16ArrayConstructor {
*/
of(...items: number[]): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array;
}
@@ -2989,13 +3013,19 @@ interface Uint16ArrayConstructor {
*/
of(...items: number[]): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array;
}
@@ -3258,13 +3288,19 @@ interface Int32ArrayConstructor {
*/
of(...items: number[]): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;
}
declare const Int32Array: Int32ArrayConstructor;
@@ -3526,13 +3562,19 @@ interface Uint32ArrayConstructor {
*/
of(...items: number[]): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;
}
declare const Uint32Array: Uint32ArrayConstructor;
@@ -3795,13 +3837,19 @@ interface Float32ArrayConstructor {
*/
of(...items: number[]): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array;
}
@@ -4065,13 +4113,19 @@ interface Float64ArrayConstructor {
*/
of(...items: number[]): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
+1
View File
@@ -2905,6 +2905,7 @@ namespace ts.server.protocol {
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
readonly allowRenameOfImportPath?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
}
+2 -1
View File
@@ -1774,7 +1774,8 @@ namespace ts.FindAllReferences.Core {
function isImplementation(node: Node): boolean {
return !!(node.flags & NodeFlags.Ambient)
|| (isVariableLike(node) ? hasInitializer(node)
? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node))
: (isVariableLike(node) ? hasInitializer(node)
: isFunctionLikeDeclaration(node) ? !!node.body
: isClassLike(node) || isModuleOrEnumDeclaration(node));
}
+29 -1
View File
@@ -460,6 +460,12 @@ namespace ts.refactor {
const oldImportsNeededByNewFile = new SymbolSet();
const newFileImportsFromOldFile = new SymbolSet();
const containsJsx = find(toMove, statement => !!(statement.transformFlags & TransformFlags.ContainsJsx));
const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
}
for (const statement of toMove) {
forEachTopLevelDeclaration(statement, decl => {
movedSymbols.add(Debug.assertDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
@@ -485,6 +491,11 @@ namespace ts.refactor {
for (const statement of oldFile.statements) {
if (contains(toMove, statement)) continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
if (jsxNamespaceSymbol && !!(statement.transformFlags & TransformFlags.ContainsJsx)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, symbol => {
if (movedSymbols.has(symbol)) oldFileImportsFromNewFile.add(symbol);
unusedImportsFromOldFile.delete(symbol);
@@ -492,6 +503,23 @@ namespace ts.refactor {
}
return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile };
function getJsxNamespaceSymbol(containsJsx: Node | undefined) {
if (containsJsx === undefined) {
return undefined;
}
const jsxNamespace = checker.getJsxNamespace(containsJsx);
// Strictly speaking, this could resolve to a symbol other than the JSX namespace.
// This will produce erroneous output (probably, an incorrectly copied import) but
// is expected to be very rare and easily reversible.
const jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, SymbolFlags.Namespace, /*excludeGlobals*/ true);
return !!jsxNamespaceSymbol && some(jsxNamespaceSymbol.declarations, isInImport)
? jsxNamespaceSymbol
: undefined;
}
}
// Below should all be utilities
@@ -512,7 +540,7 @@ namespace ts.refactor {
}
function isVariableDeclarationInImport(decl: VariableDeclaration) {
return isSourceFile(decl.parent.parent.parent) &&
decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
!!decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
}
function filterImport(i: SupportedImport, moduleSpecifier: StringLiteralLike, keep: (name: Identifier) => boolean): SupportedImportStatement | undefined {
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"outFile": "../../built/local/run.js",
"composite": false,
@@ -129,5 +129,34 @@ namespace ts {
},
{ sourceMap: true }
);
emitsCorrectly("skipTriviaExternalSourceFiles",
[
{
file: "source.ts",
// The source file contains preceding trivia (e.g. whitespace) to try to confuse the `skipSourceTrivia` function.
text: " original;"
},
],
{
before: [
context => node => visitNode(node, function visitor(node: Node): Node {
if (isIdentifier(node) && node.text === "original") {
const newNode = createIdentifier("changed");
setSourceMapRange(newNode, {
pos: 0,
end: 7,
// Do not provide a custom skipTrivia function for `source`.
source: createSourceMapSource("another.html", "changed;")
});
return newNode;
}
return visitEachChild(node, visitor, context);
})
]
},
{ sourceMap: true }
);
});
}
+41
View File
@@ -469,11 +469,20 @@ export const b = new A();`);
describe("unittests:: tsbuild - baseline sectioned sourcemaps", () => {
let fs: vfs.FileSystem | undefined;
const actualReadFileMap = createMap<number>();
before(() => {
fs = outFileFs.shadow();
const host = new fakes.SolutionBuilderHost(fs);
const builder = createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: false });
host.clearDiagnostics();
const originalReadFile = host.readFile;
host.readFile = path => {
// Dont record libs
if (path.startsWith("/src/")) {
actualReadFileMap.set(path, (actualReadFileMap.get(path) || 0) + 1);
}
return originalReadFile.call(host, path);
};
builder.buildAllProjects();
host.assertDiagnosticMessages(/*none*/);
});
@@ -485,6 +494,38 @@ export const b = new A();`);
// tslint:disable-next-line:no-null-keyword
Harness.Baseline.runBaseline("outfile-concat.js", patch ? vfs.formatPatch(patch) : null);
});
it("verify readFile calls", () => {
const expected = [
// Configs
"/src/third/tsconfig.json",
"/src/second/tsconfig.json",
"/src/first/tsconfig.json",
// Source files
"/src/third/third_part1.ts",
"/src/second/second_part1.ts",
"/src/second/second_part2.ts",
"/src/first/first_PART1.ts",
"/src/first/first_part2.ts",
"/src/first/first_part3.ts",
// outputs
"/src/first/bin/first-output.js",
"/src/first/bin/first-output.js.map",
"/src/first/bin/first-output.d.ts",
"/src/first/bin/first-output.d.ts.map",
"/src/2/second-output.js",
"/src/2/second-output.js.map",
"/src/2/second-output.d.ts",
"/src/2/second-output.d.ts.map"
];
assert.equal(actualReadFileMap.size, expected.length, `Expected: ${JSON.stringify(expected)} \nActual: ${JSON.stringify(arrayFrom(actualReadFileMap.entries()))}`);
expected.forEach(expectedValue => {
const actual = actualReadFileMap.get(expectedValue);
assert.equal(actual, 1, `Mismatch in read file call number for: ${expectedValue}\nExpected: ${JSON.stringify(expected)} \nActual: ${JSON.stringify(arrayFrom(actualReadFileMap.entries()))}`);
});
});
});
describe("unittests:: tsbuild - downstream prepend projects always get rebuilt", () => {
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig-base",
"compilerOptions": {
"declaration": false,
"declarationMap": false,
"composite": false
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"outFile": "../../built/local/tsserver.js",
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"removeComments": true,
"outFile": "../../built/local/typingsInstaller.js",
+2 -2
View File
@@ -1,5 +1,5 @@
{
"extends": "../tsconfig-base",
"extends": "../tsconfig-noncomposite-base",
"compilerOptions": {
"removeComments": true,
"outFile": "../../built/local/watchGuard.js",
@@ -13,4 +13,4 @@
"files": [
"watchGuard.ts"
]
}
}
@@ -1,8 +1,8 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts(2,17): error TS2568: Type 'Set<number>' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts(2,17): error TS2569: Type 'Set<number>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck14.ts (1 errors) ====
var union: string | Set<number>
for (const e of union) { }
~~~~~
!!! error TS2568: Type 'Set<number>' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
!!! error TS2569: Type 'Set<number>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
+10 -2
View File
@@ -1726,15 +1726,18 @@ declare namespace ts {
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptPath?: string;
javascriptText: string;
javascriptMapPath?: string;
javascriptMapText?: string;
declarationPath?: string;
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
fileName?: string;
text: string;
sourceMapPath?: string;
sourceMapText?: string;
@@ -2214,6 +2217,7 @@ declare namespace ts {
}
interface UniqueESSymbolType extends Type {
symbol: Symbol;
escapedName: __String;
}
interface StringLiteralType extends LiteralType {
value: string;
@@ -3097,6 +3101,7 @@ declare namespace ts {
scanJsxIdentifier(): SyntaxKind;
scanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(): JsxTokenSyntaxKind;
reScanLessThanToken(): SyntaxKind;
scanJsxToken(): JsxTokenSyntaxKind;
scanJSDocToken(): JsDocSyntaxKind;
scan(): SyntaxKind;
@@ -3978,9 +3983,11 @@ declare namespace ts {
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascript: string, declaration: string): InputFiles;
function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): 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;
@@ -7932,6 +7939,7 @@ declare namespace ts.server.protocol {
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
readonly allowRenameOfImportPath?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
}
+9 -2
View File
@@ -1726,15 +1726,18 @@ declare namespace ts {
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
javascriptPath?: string;
javascriptText: string;
javascriptMapPath?: string;
javascriptMapText?: string;
declarationPath?: string;
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
fileName?: string;
text: string;
sourceMapPath?: string;
sourceMapText?: string;
@@ -2214,6 +2217,7 @@ declare namespace ts {
}
interface UniqueESSymbolType extends Type {
symbol: Symbol;
escapedName: __String;
}
interface StringLiteralType extends LiteralType {
value: string;
@@ -3097,6 +3101,7 @@ declare namespace ts {
scanJsxIdentifier(): SyntaxKind;
scanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(): JsxTokenSyntaxKind;
reScanLessThanToken(): SyntaxKind;
scanJsxToken(): JsxTokenSyntaxKind;
scanJSDocToken(): JsDocSyntaxKind;
scan(): SyntaxKind;
@@ -3978,9 +3983,11 @@ declare namespace ts {
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascript: string, declaration: string): InputFiles;
function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): 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;
+2 -2
View File
@@ -3,7 +3,7 @@ var arr: string[] | number[];
>arr : Symbol(arr, Decl(arraySlice.ts, 0, 3))
arr.splice(1, 1);
>arr.splice : Symbol(splice, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>arr.splice : Symbol(Array.splice, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>arr : Symbol(arr, Decl(arraySlice.ts, 0, 3))
>splice : Symbol(splice, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>splice : Symbol(Array.splice, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
@@ -24,8 +24,8 @@ declare const b: (string | number)[] | null[] | undefined[] | {}[];
let x = a.equalsShallow(b);
>x : Symbol(x, Decl(bivariantInferences.ts, 9, 3))
>a.equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20))
>a.equalsShallow : Symbol(Array.equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20))
>a : Symbol(a, Decl(bivariantInferences.ts, 6, 13))
>equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20))
>equalsShallow : Symbol(Array.equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20))
>b : Symbol(b, Decl(bivariantInferences.ts, 7, 13))
@@ -94,9 +94,9 @@ function test3(items: string[] | number[]) {
>items : Symbol(items, Decl(callsOnComplexSignatures.tsx, 36, 15))
items.forEach(item => console.log(item));
>items.forEach : Symbol(forEach, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>items.forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>items : Symbol(items, Decl(callsOnComplexSignatures.tsx, 36, 15))
>forEach : Symbol(forEach, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>item : Symbol(item, Decl(callsOnComplexSignatures.tsx, 37, 18))
>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --))
>console : Symbol(console, Decl(lib.dom.d.ts, --, --))
@@ -0,0 +1,31 @@
tests/cases/conformance/jsx/file.tsx(10,13): error TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes'.
Property 'children' does not exist on type 'IntrinsicAttributes'.
tests/cases/conformance/jsx/file.tsx(11,13): error TS2322: Type '{ children: Element; key: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'children' does not exist on type 'IntrinsicAttributes'.
tests/cases/conformance/jsx/file.tsx(12,13): error TS2322: Type '{ children: Element[]; key: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'children' does not exist on type 'IntrinsicAttributes'.
==== tests/cases/conformance/jsx/file.tsx (3 errors) ====
import React = require('react');
const Tag = (x: {}) => <div></div>;
// OK
const k1 = <Tag />;
const k2 = <Tag></Tag>;
// Not OK (excess children)
const k3 = <Tag children={<div></div>} />;
~~~
!!! error TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes'.
!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes'.
const k4 = <Tag key="1"><div></div></Tag>;
~~~
!!! error TS2322: Type '{ children: Element; key: string; }' is not assignable to type 'IntrinsicAttributes'.
!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes'.
const k5 = <Tag key="1"><div></div><div></div></Tag>;
~~~
!!! error TS2322: Type '{ children: Element[]; key: string; }' is not assignable to type 'IntrinsicAttributes'.
!!! error TS2322: Property 'children' does not exist on type 'IntrinsicAttributes'.
@@ -0,0 +1,27 @@
//// [file.tsx]
import React = require('react');
const Tag = (x: {}) => <div></div>;
// OK
const k1 = <Tag />;
const k2 = <Tag></Tag>;
// Not OK (excess children)
const k3 = <Tag children={<div></div>} />;
const k4 = <Tag key="1"><div></div></Tag>;
const k5 = <Tag key="1"><div></div><div></div></Tag>;
//// [file.jsx]
"use strict";
exports.__esModule = true;
var React = require("react");
var Tag = function (x) { return <div></div>; };
// OK
var k1 = <Tag />;
var k2 = <Tag></Tag>;
// Not OK (excess children)
var k3 = <Tag children={<div></div>}/>;
var k4 = <Tag key="1"><div></div></Tag>;
var k5 = <Tag key="1"><div></div><div></div></Tag>;
@@ -0,0 +1,46 @@
=== tests/cases/conformance/jsx/file.tsx ===
import React = require('react');
>React : Symbol(React, Decl(file.tsx, 0, 0))
const Tag = (x: {}) => <div></div>;
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
>x : Symbol(x, Decl(file.tsx, 2, 13))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
// OK
const k1 = <Tag />;
>k1 : Symbol(k1, Decl(file.tsx, 5, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
const k2 = <Tag></Tag>;
>k2 : Symbol(k2, Decl(file.tsx, 6, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
// Not OK (excess children)
const k3 = <Tag children={<div></div>} />;
>k3 : Symbol(k3, Decl(file.tsx, 9, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
>children : Symbol(children, Decl(file.tsx, 9, 15))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
const k4 = <Tag key="1"><div></div></Tag>;
>k4 : Symbol(k4, Decl(file.tsx, 10, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
>key : Symbol(key, Decl(file.tsx, 10, 15))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
const k5 = <Tag key="1"><div></div><div></div></Tag>;
>k5 : Symbol(k5, Decl(file.tsx, 11, 5))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
>key : Symbol(key, Decl(file.tsx, 11, 15))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45))
>Tag : Symbol(Tag, Decl(file.tsx, 2, 5))
@@ -0,0 +1,57 @@
=== tests/cases/conformance/jsx/file.tsx ===
import React = require('react');
>React : typeof React
const Tag = (x: {}) => <div></div>;
>Tag : (x: {}) => JSX.Element
>(x: {}) => <div></div> : (x: {}) => JSX.Element
>x : {}
><div></div> : JSX.Element
>div : any
>div : any
// OK
const k1 = <Tag />;
>k1 : JSX.Element
><Tag /> : JSX.Element
>Tag : (x: {}) => JSX.Element
const k2 = <Tag></Tag>;
>k2 : JSX.Element
><Tag></Tag> : JSX.Element
>Tag : (x: {}) => JSX.Element
>Tag : (x: {}) => JSX.Element
// Not OK (excess children)
const k3 = <Tag children={<div></div>} />;
>k3 : JSX.Element
><Tag children={<div></div>} /> : JSX.Element
>Tag : (x: {}) => JSX.Element
>children : JSX.Element
><div></div> : JSX.Element
>div : any
>div : any
const k4 = <Tag key="1"><div></div></Tag>;
>k4 : JSX.Element
><Tag key="1"><div></div></Tag> : JSX.Element
>Tag : (x: {}) => JSX.Element
>key : string
><div></div> : JSX.Element
>div : any
>div : any
>Tag : (x: {}) => JSX.Element
const k5 = <Tag key="1"><div></div><div></div></Tag>;
>k5 : JSX.Element
><Tag key="1"><div></div><div></div></Tag> : JSX.Element
>Tag : (x: {}) => JSX.Element
>key : string
><div></div> : JSX.Element
>div : any
>div : any
><div></div> : JSX.Element
>div : any
>div : any
>Tag : (x: {}) => JSX.Element
@@ -269,8 +269,8 @@ soup.flavour
>flavour : number
var chowder = new Chowder({ claim: "ignorant" });
>chowder : any
>new Chowder({ claim: "ignorant" }) : any
>chowder : Chowder
>new Chowder({ claim: "ignorant" }) : Chowder
>Chowder : typeof Chowder
>{ claim: "ignorant" } : { claim: "ignorant"; }
>claim : "ignorant"
@@ -279,7 +279,7 @@ var chowder = new Chowder({ claim: "ignorant" });
chowder.flavour.claim
>chowder.flavour.claim : any
>chowder.flavour : any
>chowder : any
>chowder : Chowder
>flavour : any
>claim : any
@@ -121,9 +121,9 @@ function f6() {
>x : Symbol(x, Decl(controlFlowArrayErrors.ts, 37, 7))
x.push(99); // Error
>x.push : Symbol(push, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>x.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>x : Symbol(x, Decl(controlFlowArrayErrors.ts, 37, 7))
>push : Symbol(push, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
}
function f7() {
@@ -0,0 +1,142 @@
//// [controlFlowForCatchAndFinally.ts]
type Page = {close(): Promise<void>; content(): Promise<string>};
type Browser = {close(): Promise<void>};
declare function test1(): Promise<Browser>;
declare function test2(obj: Browser): Promise<Page>;
async function test(): Promise<string> {
let browser: Browser | undefined = undefined;
let page: Page | undefined = undefined;
try {
browser = await test1();
page = await test2(browser);
return await page.content();;
} finally {
if (page) {
await page.close(); // ok
}
if (browser) {
await browser.close(); // ok
}
}
}
declare class Aborter { abort(): void };
class Foo {
abortController: Aborter | undefined = undefined;
async operation() {
if (this.abortController !== undefined) {
this.abortController.abort();
this.abortController = undefined;
}
try {
this.abortController = new Aborter();
} catch (error) {
if (this.abortController !== undefined) {
this.abortController.abort(); // ok
}
}
}
}
//// [controlFlowForCatchAndFinally.js]
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
function test() {
return __awaiter(this, void 0, void 0, function () {
var browser, page;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
browser = undefined;
page = undefined;
_a.label = 1;
case 1:
_a.trys.push([1, , 5, 10]);
return [4 /*yield*/, test1()];
case 2:
browser = _a.sent();
return [4 /*yield*/, test2(browser)];
case 3:
page = _a.sent();
return [4 /*yield*/, page.content()];
case 4: return [2 /*return*/, _a.sent()];
case 5:
if (!page) return [3 /*break*/, 7];
return [4 /*yield*/, page.close()];
case 6:
_a.sent(); // ok
_a.label = 7;
case 7:
if (!browser) return [3 /*break*/, 9];
return [4 /*yield*/, browser.close()];
case 8:
_a.sent(); // ok
_a.label = 9;
case 9: return [7 /*endfinally*/];
case 10: return [2 /*return*/];
}
});
});
}
;
var Foo = /** @class */ (function () {
function Foo() {
this.abortController = undefined;
}
Foo.prototype.operation = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (this.abortController !== undefined) {
this.abortController.abort();
this.abortController = undefined;
}
try {
this.abortController = new Aborter();
}
catch (error) {
if (this.abortController !== undefined) {
this.abortController.abort(); // ok
}
}
return [2 /*return*/];
});
});
};
return Foo;
}());
@@ -0,0 +1,135 @@
=== tests/cases/compiler/controlFlowForCatchAndFinally.ts ===
type Page = {close(): Promise<void>; content(): Promise<string>};
>Page : Symbol(Page, Decl(controlFlowForCatchAndFinally.ts, 0, 0))
>close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 0, 13))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>content : Symbol(content, Decl(controlFlowForCatchAndFinally.ts, 0, 36))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
type Browser = {close(): Promise<void>};
>Browser : Symbol(Browser, Decl(controlFlowForCatchAndFinally.ts, 0, 65))
>close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 1, 16))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
declare function test1(): Promise<Browser>;
>test1 : Symbol(test1, Decl(controlFlowForCatchAndFinally.ts, 1, 40))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>Browser : Symbol(Browser, Decl(controlFlowForCatchAndFinally.ts, 0, 65))
declare function test2(obj: Browser): Promise<Page>;
>test2 : Symbol(test2, Decl(controlFlowForCatchAndFinally.ts, 2, 43))
>obj : Symbol(obj, Decl(controlFlowForCatchAndFinally.ts, 3, 23))
>Browser : Symbol(Browser, Decl(controlFlowForCatchAndFinally.ts, 0, 65))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>Page : Symbol(Page, Decl(controlFlowForCatchAndFinally.ts, 0, 0))
async function test(): Promise<string> {
>test : Symbol(test, Decl(controlFlowForCatchAndFinally.ts, 3, 52))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
let browser: Browser | undefined = undefined;
>browser : Symbol(browser, Decl(controlFlowForCatchAndFinally.ts, 5, 7))
>Browser : Symbol(Browser, Decl(controlFlowForCatchAndFinally.ts, 0, 65))
>undefined : Symbol(undefined)
let page: Page | undefined = undefined;
>page : Symbol(page, Decl(controlFlowForCatchAndFinally.ts, 6, 7))
>Page : Symbol(Page, Decl(controlFlowForCatchAndFinally.ts, 0, 0))
>undefined : Symbol(undefined)
try {
browser = await test1();
>browser : Symbol(browser, Decl(controlFlowForCatchAndFinally.ts, 5, 7))
>test1 : Symbol(test1, Decl(controlFlowForCatchAndFinally.ts, 1, 40))
page = await test2(browser);
>page : Symbol(page, Decl(controlFlowForCatchAndFinally.ts, 6, 7))
>test2 : Symbol(test2, Decl(controlFlowForCatchAndFinally.ts, 2, 43))
>browser : Symbol(browser, Decl(controlFlowForCatchAndFinally.ts, 5, 7))
return await page.content();;
>page.content : Symbol(content, Decl(controlFlowForCatchAndFinally.ts, 0, 36))
>page : Symbol(page, Decl(controlFlowForCatchAndFinally.ts, 6, 7))
>content : Symbol(content, Decl(controlFlowForCatchAndFinally.ts, 0, 36))
} finally {
if (page) {
>page : Symbol(page, Decl(controlFlowForCatchAndFinally.ts, 6, 7))
await page.close(); // ok
>page.close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 0, 13))
>page : Symbol(page, Decl(controlFlowForCatchAndFinally.ts, 6, 7))
>close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 0, 13))
}
if (browser) {
>browser : Symbol(browser, Decl(controlFlowForCatchAndFinally.ts, 5, 7))
await browser.close(); // ok
>browser.close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 1, 16))
>browser : Symbol(browser, Decl(controlFlowForCatchAndFinally.ts, 5, 7))
>close : Symbol(close, Decl(controlFlowForCatchAndFinally.ts, 1, 16))
}
}
}
declare class Aborter { abort(): void };
>Aborter : Symbol(Aborter, Decl(controlFlowForCatchAndFinally.ts, 20, 1))
>abort : Symbol(Aborter.abort, Decl(controlFlowForCatchAndFinally.ts, 22, 23))
class Foo {
>Foo : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
abortController: Aborter | undefined = undefined;
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>Aborter : Symbol(Aborter, Decl(controlFlowForCatchAndFinally.ts, 20, 1))
>undefined : Symbol(undefined)
async operation() {
>operation : Symbol(Foo.operation, Decl(controlFlowForCatchAndFinally.ts, 24, 53))
if (this.abortController !== undefined) {
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>undefined : Symbol(undefined)
this.abortController.abort();
>this.abortController.abort : Symbol(Aborter.abort, Decl(controlFlowForCatchAndFinally.ts, 22, 23))
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>abort : Symbol(Aborter.abort, Decl(controlFlowForCatchAndFinally.ts, 22, 23))
this.abortController = undefined;
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>undefined : Symbol(undefined)
}
try {
this.abortController = new Aborter();
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>Aborter : Symbol(Aborter, Decl(controlFlowForCatchAndFinally.ts, 20, 1))
} catch (error) {
>error : Symbol(error, Decl(controlFlowForCatchAndFinally.ts, 33, 17))
if (this.abortController !== undefined) {
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>undefined : Symbol(undefined)
this.abortController.abort(); // ok
>this.abortController.abort : Symbol(Aborter.abort, Decl(controlFlowForCatchAndFinally.ts, 22, 23))
>this.abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>this : Symbol(Foo, Decl(controlFlowForCatchAndFinally.ts, 22, 40))
>abortController : Symbol(Foo.abortController, Decl(controlFlowForCatchAndFinally.ts, 23, 11))
>abort : Symbol(Aborter.abort, Decl(controlFlowForCatchAndFinally.ts, 22, 23))
}
}
}
}
@@ -0,0 +1,142 @@
=== tests/cases/compiler/controlFlowForCatchAndFinally.ts ===
type Page = {close(): Promise<void>; content(): Promise<string>};
>Page : Page
>close : () => Promise<void>
>content : () => Promise<string>
type Browser = {close(): Promise<void>};
>Browser : Browser
>close : () => Promise<void>
declare function test1(): Promise<Browser>;
>test1 : () => Promise<Browser>
declare function test2(obj: Browser): Promise<Page>;
>test2 : (obj: Browser) => Promise<Page>
>obj : Browser
async function test(): Promise<string> {
>test : () => Promise<string>
let browser: Browser | undefined = undefined;
>browser : Browser | undefined
>undefined : undefined
let page: Page | undefined = undefined;
>page : Page | undefined
>undefined : undefined
try {
browser = await test1();
>browser = await test1() : Browser
>browser : Browser | undefined
>await test1() : Browser
>test1() : Promise<Browser>
>test1 : () => Promise<Browser>
page = await test2(browser);
>page = await test2(browser) : Page
>page : Page | undefined
>await test2(browser) : Page
>test2(browser) : Promise<Page>
>test2 : (obj: Browser) => Promise<Page>
>browser : Browser
return await page.content();;
>await page.content() : string
>page.content() : Promise<string>
>page.content : () => Promise<string>
>page : Page
>content : () => Promise<string>
} finally {
if (page) {
>page : Page | undefined
await page.close(); // ok
>await page.close() : void
>page.close() : Promise<void>
>page.close : () => Promise<void>
>page : Page
>close : () => Promise<void>
}
if (browser) {
>browser : Browser | undefined
await browser.close(); // ok
>await browser.close() : void
>browser.close() : Promise<void>
>browser.close : () => Promise<void>
>browser : Browser
>close : () => Promise<void>
}
}
}
declare class Aborter { abort(): void };
>Aborter : Aborter
>abort : () => void
class Foo {
>Foo : Foo
abortController: Aborter | undefined = undefined;
>abortController : Aborter | undefined
>undefined : undefined
async operation() {
>operation : () => Promise<void>
if (this.abortController !== undefined) {
>this.abortController !== undefined : boolean
>this.abortController : Aborter | undefined
>this : this
>abortController : Aborter | undefined
>undefined : undefined
this.abortController.abort();
>this.abortController.abort() : void
>this.abortController.abort : () => void
>this.abortController : Aborter
>this : this
>abortController : Aborter
>abort : () => void
this.abortController = undefined;
>this.abortController = undefined : undefined
>this.abortController : Aborter | undefined
>this : this
>abortController : Aborter | undefined
>undefined : undefined
}
try {
this.abortController = new Aborter();
>this.abortController = new Aborter() : Aborter
>this.abortController : Aborter | undefined
>this : this
>abortController : Aborter | undefined
>new Aborter() : Aborter
>Aborter : typeof Aborter
} catch (error) {
>error : any
if (this.abortController !== undefined) {
>this.abortController !== undefined : boolean
>this.abortController : Aborter | undefined
>this : this
>abortController : Aborter | undefined
>undefined : undefined
this.abortController.abort(); // ok
>this.abortController.abort() : void
>this.abortController.abort : () => void
>this.abortController : Aborter
>this : this
>abortController : Aborter
>abort : () => void
}
}
}
}
@@ -0,0 +1,36 @@
tests/cases/compiler/crashInGetTextOfComputedPropertyName.ts(23,24): error TS2525: Initializer provides no value for this binding element and the binding element has no default value.
==== tests/cases/compiler/crashInGetTextOfComputedPropertyName.ts (1 errors) ====
// https://github.com/Microsoft/TypeScript/issues/29006
export interface A { type: 'a' }
export interface B { type: 'b' }
export type AB = A | B
const itemId = 'some-id'
// --- test on first level ---
const items: { [id: string]: AB } = {}
const { [itemId]: itemOk1 } = items
typeof itemOk1 // pass
// --- test on second level ---
interface ObjWithItems {
items: {[s: string]: AB}
}
const objWithItems: ObjWithItems = { items: {}}
const itemOk2 = objWithItems.items[itemId]
typeof itemOk2 // pass
const {
items: { [itemId]: itemWithTSError } = {} /*happens when default value is provided*/
~~~~~~~~~~~~~~~
!!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value.
} = objWithItems
// in order to re-produce the error, uncomment next line:
typeof itemWithTSError // :(
// will result in:
// Error from compilation: TypeError: Cannot read property 'charCodeAt' of undefined TypeError: Cannot read property 'charCodeAt' of undefined
@@ -0,0 +1,48 @@
//// [crashInGetTextOfComputedPropertyName.ts]
// https://github.com/Microsoft/TypeScript/issues/29006
export interface A { type: 'a' }
export interface B { type: 'b' }
export type AB = A | B
const itemId = 'some-id'
// --- test on first level ---
const items: { [id: string]: AB } = {}
const { [itemId]: itemOk1 } = items
typeof itemOk1 // pass
// --- test on second level ---
interface ObjWithItems {
items: {[s: string]: AB}
}
const objWithItems: ObjWithItems = { items: {}}
const itemOk2 = objWithItems.items[itemId]
typeof itemOk2 // pass
const {
items: { [itemId]: itemWithTSError } = {} /*happens when default value is provided*/
} = objWithItems
// in order to re-produce the error, uncomment next line:
typeof itemWithTSError // :(
// will result in:
// Error from compilation: TypeError: Cannot read property 'charCodeAt' of undefined TypeError: Cannot read property 'charCodeAt' of undefined
//// [crashInGetTextOfComputedPropertyName.js]
"use strict";
exports.__esModule = true;
var itemId = 'some-id';
// --- test on first level ---
var items = {};
var _a = itemId, itemOk1 = items[_a];
typeof itemOk1; // pass
var objWithItems = { items: {} };
var itemOk2 = objWithItems.items[itemId];
typeof itemOk2; // pass
var _b = objWithItems.items /*happens when default value is provided*/, _c = itemId, itemWithTSError = (_b === void 0 ? {} /*happens when default value is provided*/ : _b)[_c];
// in order to re-produce the error, uncomment next line:
typeof itemWithTSError; // :(
// will result in:
// Error from compilation: TypeError: Cannot read property 'charCodeAt' of undefined TypeError: Cannot read property 'charCodeAt' of undefined
@@ -0,0 +1,71 @@
=== tests/cases/compiler/crashInGetTextOfComputedPropertyName.ts ===
// https://github.com/Microsoft/TypeScript/issues/29006
export interface A { type: 'a' }
>A : Symbol(A, Decl(crashInGetTextOfComputedPropertyName.ts, 0, 0))
>type : Symbol(A.type, Decl(crashInGetTextOfComputedPropertyName.ts, 1, 20))
export interface B { type: 'b' }
>B : Symbol(B, Decl(crashInGetTextOfComputedPropertyName.ts, 1, 32))
>type : Symbol(B.type, Decl(crashInGetTextOfComputedPropertyName.ts, 2, 20))
export type AB = A | B
>AB : Symbol(AB, Decl(crashInGetTextOfComputedPropertyName.ts, 2, 32))
>A : Symbol(A, Decl(crashInGetTextOfComputedPropertyName.ts, 0, 0))
>B : Symbol(B, Decl(crashInGetTextOfComputedPropertyName.ts, 1, 32))
const itemId = 'some-id'
>itemId : Symbol(itemId, Decl(crashInGetTextOfComputedPropertyName.ts, 5, 5))
// --- test on first level ---
const items: { [id: string]: AB } = {}
>items : Symbol(items, Decl(crashInGetTextOfComputedPropertyName.ts, 8, 5))
>id : Symbol(id, Decl(crashInGetTextOfComputedPropertyName.ts, 8, 16))
>AB : Symbol(AB, Decl(crashInGetTextOfComputedPropertyName.ts, 2, 32))
const { [itemId]: itemOk1 } = items
>itemId : Symbol(itemId, Decl(crashInGetTextOfComputedPropertyName.ts, 5, 5))
>itemOk1 : Symbol(itemOk1, Decl(crashInGetTextOfComputedPropertyName.ts, 9, 7))
>items : Symbol(items, Decl(crashInGetTextOfComputedPropertyName.ts, 8, 5))
typeof itemOk1 // pass
>itemOk1 : Symbol(itemOk1, Decl(crashInGetTextOfComputedPropertyName.ts, 9, 7))
// --- test on second level ---
interface ObjWithItems {
>ObjWithItems : Symbol(ObjWithItems, Decl(crashInGetTextOfComputedPropertyName.ts, 10, 14))
items: {[s: string]: AB}
>items : Symbol(ObjWithItems.items, Decl(crashInGetTextOfComputedPropertyName.ts, 13, 24))
>s : Symbol(s, Decl(crashInGetTextOfComputedPropertyName.ts, 14, 13))
>AB : Symbol(AB, Decl(crashInGetTextOfComputedPropertyName.ts, 2, 32))
}
const objWithItems: ObjWithItems = { items: {}}
>objWithItems : Symbol(objWithItems, Decl(crashInGetTextOfComputedPropertyName.ts, 16, 5))
>ObjWithItems : Symbol(ObjWithItems, Decl(crashInGetTextOfComputedPropertyName.ts, 10, 14))
>items : Symbol(items, Decl(crashInGetTextOfComputedPropertyName.ts, 16, 36))
const itemOk2 = objWithItems.items[itemId]
>itemOk2 : Symbol(itemOk2, Decl(crashInGetTextOfComputedPropertyName.ts, 18, 5))
>objWithItems.items : Symbol(ObjWithItems.items, Decl(crashInGetTextOfComputedPropertyName.ts, 13, 24))
>objWithItems : Symbol(objWithItems, Decl(crashInGetTextOfComputedPropertyName.ts, 16, 5))
>items : Symbol(ObjWithItems.items, Decl(crashInGetTextOfComputedPropertyName.ts, 13, 24))
>itemId : Symbol(itemId, Decl(crashInGetTextOfComputedPropertyName.ts, 5, 5))
typeof itemOk2 // pass
>itemOk2 : Symbol(itemOk2, Decl(crashInGetTextOfComputedPropertyName.ts, 18, 5))
const {
items: { [itemId]: itemWithTSError } = {} /*happens when default value is provided*/
>items : Symbol(ObjWithItems.items, Decl(crashInGetTextOfComputedPropertyName.ts, 13, 24))
>itemId : Symbol(itemId, Decl(crashInGetTextOfComputedPropertyName.ts, 5, 5))
>itemWithTSError : Symbol(itemWithTSError, Decl(crashInGetTextOfComputedPropertyName.ts, 22, 12))
} = objWithItems
>objWithItems : Symbol(objWithItems, Decl(crashInGetTextOfComputedPropertyName.ts, 16, 5))
// in order to re-produce the error, uncomment next line:
typeof itemWithTSError // :(
>itemWithTSError : Symbol(itemWithTSError, Decl(crashInGetTextOfComputedPropertyName.ts, 22, 12))
// will result in:
// Error from compilation: TypeError: Cannot read property 'charCodeAt' of undefined TypeError: Cannot read property 'charCodeAt' of undefined
@@ -0,0 +1,71 @@
=== tests/cases/compiler/crashInGetTextOfComputedPropertyName.ts ===
// https://github.com/Microsoft/TypeScript/issues/29006
export interface A { type: 'a' }
>type : "a"
export interface B { type: 'b' }
>type : "b"
export type AB = A | B
>AB : AB
const itemId = 'some-id'
>itemId : "some-id"
>'some-id' : "some-id"
// --- test on first level ---
const items: { [id: string]: AB } = {}
>items : { [id: string]: AB; }
>id : string
>{} : {}
const { [itemId]: itemOk1 } = items
>itemId : "some-id"
>itemOk1 : AB
>items : { [id: string]: AB; }
typeof itemOk1 // pass
>typeof itemOk1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
>itemOk1 : AB
// --- test on second level ---
interface ObjWithItems {
items: {[s: string]: AB}
>items : { [s: string]: AB; }
>s : string
}
const objWithItems: ObjWithItems = { items: {}}
>objWithItems : ObjWithItems
>{ items: {}} : { items: {}; }
>items : {}
>{} : {}
const itemOk2 = objWithItems.items[itemId]
>itemOk2 : AB
>objWithItems.items[itemId] : AB
>objWithItems.items : { [s: string]: AB; }
>objWithItems : ObjWithItems
>items : { [s: string]: AB; }
>itemId : "some-id"
typeof itemOk2 // pass
>typeof itemOk2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
>itemOk2 : AB
const {
items: { [itemId]: itemWithTSError } = {} /*happens when default value is provided*/
>items : any
>itemId : "some-id"
>itemWithTSError : any
>{} : { some-id: any; }
} = objWithItems
>objWithItems : ObjWithItems
// in order to re-produce the error, uncomment next line:
typeof itemWithTSError // :(
>typeof itemWithTSError : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
>itemWithTSError : any
// will result in:
// Error from compilation: TypeError: Cannot read property 'charCodeAt' of undefined TypeError: Cannot read property 'charCodeAt' of undefined
@@ -0,0 +1,6 @@
// [source.js.map]
{"version":3,"file":"source.js","sourceRoot":"","sources":["source.ts","another.html"],"names":[],"mappings":"ACAA,OAAO,CDAW"}
// [source.js]
changed;
//# sourceMappingURL=source.js.map
@@ -1,9 +1,10 @@
tests/cases/compiler/destructureComputedProperty.ts(7,7): error TS2341: Property 'p' is private and only accessible within class 'C'.
tests/cases/compiler/destructureComputedProperty.ts(8,7): error TS2341: Property 'p' is private and only accessible within class 'C'.
tests/cases/compiler/destructureComputedProperty.ts(9,7): error TS2341: Property 'p' is private and only accessible within class 'C'.
tests/cases/compiler/destructureComputedProperty.ts(10,7): error TS2341: Property 'p' is private and only accessible within class 'C'.
==== tests/cases/compiler/destructureComputedProperty.ts (3 errors) ====
==== tests/cases/compiler/destructureComputedProperty.ts (4 errors) ====
declare const ab: { n: number } | { n: string };
const nameN = "n";
const { [nameN]: n } = ab;
@@ -17,6 +18,8 @@ tests/cases/compiler/destructureComputedProperty.ts(10,7): error TS2341: Propert
~~~~~~~~~~~~~
!!! error TS2341: Property 'p' is private and only accessible within class 'C'.
const { [nameP]: p2 } = new C();
~~~~~~~~~~~~~~~
!!! error TS2341: Property 'p' is private and only accessible within class 'C'.
const { p: p3 } = new C();
~~~~~~~~~
!!! error TS2341: Property 'p' is private and only accessible within class 'C'.
@@ -1,7 +1,8 @@
tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,8): error TS2339: Property 'prop2' does not exist on type '{ prop: string; }'.
tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,21): error TS2525: Initializer provides no value for this binding element and the binding element has no default value.
tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,37): error TS2353: Object literal may only specify known properties, and 'prop' does not exist in type '{ prop2: any; }'.
==== tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts (1 errors) ====
==== tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts (2 errors) ====
let { [Symbol.iterator]: destructured } = [];
void destructured;
@@ -13,6 +14,8 @@ tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,8): error TS
const notPresent = "prop2";
let { [notPresent]: computed2 } = { prop: "b" };
~~~~~~~~~~
!!! error TS2339: Property 'prop2' does not exist on type '{ prop: string; }'.
~~~~~~~~~
!!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value.
~~~~
!!! error TS2353: Object literal may only specify known properties, and 'prop' does not exist in type '{ prop2: any; }'.
@@ -32,7 +32,7 @@ const notPresent = "prop2";
let { [notPresent]: computed2 } = { prop: "b" };
>notPresent : "prop2"
>computed2 : any
>{ prop: "b" } : { prop: string; }
>{ prop: "b" } : { prop: string; prop2: any; }
>prop : string
>"b" : "b"
@@ -1,8 +1,10 @@
tests/cases/compiler/destructuringAssignment_private.ts(6,10): error TS2341: Property 'x' is private and only accessible within class 'C'.
tests/cases/compiler/destructuringAssignment_private.ts(7,4): error TS2341: Property 'o' is private and only accessible within class 'C'.
tests/cases/compiler/destructuringAssignment_private.ts(10,10): error TS2341: Property 'x' is private and only accessible within class 'C'.
tests/cases/compiler/destructuringAssignment_private.ts(13,4): error TS2341: Property 'o' is private and only accessible within class 'C'.
==== tests/cases/compiler/destructuringAssignment_private.ts (2 errors) ====
==== tests/cases/compiler/destructuringAssignment_private.ts (4 errors) ====
class C {
private x = 0;
private o = [{ a: 1 }];
@@ -14,4 +16,14 @@ tests/cases/compiler/destructuringAssignment_private.ts(7,4): error TS2341: Prop
({ o: [{ a: x }]} = new C());
~
!!! error TS2341: Property 'o' is private and only accessible within class 'C'.
const nameX = "x";
([{ a: { [nameX]: x } }] = [{ a: new C() }]);
~~~~~~~
!!! error TS2341: Property 'x' is private and only accessible within class 'C'.
const nameO = "o";
({ [nameO]: [{ a: x }]} = new C());
~~~~~~~
!!! error TS2341: Property 'o' is private and only accessible within class 'C'.
@@ -6,9 +6,16 @@ class C {
let x: number;
([{ a: { x } }] = [{ a: new C() }]);
({ o: [{ a: x }]} = new C());
const nameX = "x";
([{ a: { [nameX]: x } }] = [{ a: new C() }]);
const nameO = "o";
({ [nameO]: [{ a: x }]} = new C());
//// [destructuringAssignment_private.js]
var _a, _b;
var C = /** @class */ (function () {
function C() {
this.x = 0;
@@ -19,3 +26,7 @@ var C = /** @class */ (function () {
var x;
(x = [{ a: new C() }][0].a.x);
(x = new C().o[0].a);
var nameX = "x";
(_a = nameX, x = [{ a: new C() }][0].a[_a]);
var nameO = "o";
(_b = nameO, x = new C()[_b][0].a);
@@ -24,3 +24,24 @@ let x: number;
>x : Symbol(x, Decl(destructuringAssignment_private.ts, 4, 3))
>C : Symbol(C, Decl(destructuringAssignment_private.ts, 0, 0))
const nameX = "x";
>nameX : Symbol(nameX, Decl(destructuringAssignment_private.ts, 8, 5))
([{ a: { [nameX]: x } }] = [{ a: new C() }]);
>a : Symbol(a, Decl(destructuringAssignment_private.ts, 9, 3))
>[nameX] : Symbol([nameX], Decl(destructuringAssignment_private.ts, 9, 8))
>nameX : Symbol(nameX, Decl(destructuringAssignment_private.ts, 8, 5))
>x : Symbol(x, Decl(destructuringAssignment_private.ts, 4, 3))
>a : Symbol(a, Decl(destructuringAssignment_private.ts, 9, 29))
>C : Symbol(C, Decl(destructuringAssignment_private.ts, 0, 0))
const nameO = "o";
>nameO : Symbol(nameO, Decl(destructuringAssignment_private.ts, 11, 5))
({ [nameO]: [{ a: x }]} = new C());
>[nameO] : Symbol([nameO], Decl(destructuringAssignment_private.ts, 12, 2))
>nameO : Symbol(nameO, Decl(destructuringAssignment_private.ts, 11, 5))
>a : Symbol(a, Decl(destructuringAssignment_private.ts, 12, 14))
>x : Symbol(x, Decl(destructuringAssignment_private.ts, 4, 3))
>C : Symbol(C, Decl(destructuringAssignment_private.ts, 0, 0))
@@ -42,3 +42,40 @@ let x: number;
>new C() : C
>C : typeof C
const nameX = "x";
>nameX : "x"
>"x" : "x"
([{ a: { [nameX]: x } }] = [{ a: new C() }]);
>([{ a: { [nameX]: x } }] = [{ a: new C() }]) : [{ a: C; }]
>[{ a: { [nameX]: x } }] = [{ a: new C() }] : [{ a: C; }]
>[{ a: { [nameX]: x } }] : [{ a: { [nameX]: number; }; }]
>{ a: { [nameX]: x } } : { a: { [nameX]: number; }; }
>a : { [nameX]: number; }
>{ [nameX]: x } : { [nameX]: number; }
>[nameX] : number
>nameX : "x"
>x : number
>[{ a: new C() }] : [{ a: C; }]
>{ a: new C() } : { a: C; }
>a : C
>new C() : C
>C : typeof C
const nameO = "o";
>nameO : "o"
>"o" : "o"
({ [nameO]: [{ a: x }]} = new C());
>({ [nameO]: [{ a: x }]} = new C()) : C
>{ [nameO]: [{ a: x }]} = new C() : C
>{ [nameO]: [{ a: x }]} : { [nameO]: [{ a: number; }]; }
>[nameO] : [{ a: number; }]
>nameO : "o"
>[{ a: x }] : [{ a: number; }]
>{ a: x } : { a: number; }
>a : number
>x : number
>new C() : C
>C : typeof C
@@ -128,4 +128,58 @@ tests/cases/compiler/discriminantPropertyCheck.ts(65,9): error TS2532: Object is
u.a && u.b && f(u.a, u.b);
u.b && u.a && f(u.a, u.b);
// Repro from #29012
type Additive = '+' | '-';
type Multiplicative = '*' | '/';
interface AdditiveObj {
key: Additive
}
interface MultiplicativeObj {
key: Multiplicative
}
type Obj = AdditiveObj | MultiplicativeObj
export function foo(obj: Obj) {
switch (obj.key) {
case '+': {
onlyPlus(obj.key);
return;
}
}
}
function onlyPlus(arg: '+') {
return arg;
}
// Repro from #29496
declare function never(value: never): never;
const enum BarEnum {
bar1 = 1,
bar2 = 2,
}
type UnionOfBar = TypeBar1 | TypeBar2;
type TypeBar1 = { type: BarEnum.bar1 };
type TypeBar2 = { type: BarEnum.bar2 };
function func3(value: Partial<UnionOfBar>) {
if (value.type !== undefined) {
switch (value.type) {
case BarEnum.bar1:
break;
case BarEnum.bar2:
break;
default:
never(value.type);
}
}
}
@@ -120,9 +120,65 @@ const u: U = {} as any;
u.a && u.b && f(u.a, u.b);
u.b && u.a && f(u.a, u.b);
// Repro from #29012
type Additive = '+' | '-';
type Multiplicative = '*' | '/';
interface AdditiveObj {
key: Additive
}
interface MultiplicativeObj {
key: Multiplicative
}
type Obj = AdditiveObj | MultiplicativeObj
export function foo(obj: Obj) {
switch (obj.key) {
case '+': {
onlyPlus(obj.key);
return;
}
}
}
function onlyPlus(arg: '+') {
return arg;
}
// Repro from #29496
declare function never(value: never): never;
const enum BarEnum {
bar1 = 1,
bar2 = 2,
}
type UnionOfBar = TypeBar1 | TypeBar2;
type TypeBar1 = { type: BarEnum.bar1 };
type TypeBar2 = { type: BarEnum.bar2 };
function func3(value: Partial<UnionOfBar>) {
if (value.type !== undefined) {
switch (value.type) {
case BarEnum.bar1:
break;
case BarEnum.bar2:
break;
default:
never(value.type);
}
}
}
//// [discriminantPropertyCheck.js]
"use strict";
exports.__esModule = true;
function goo1(x) {
if (x.kind === "A" && x.foo !== undefined) {
x.foo.length;
@@ -188,3 +244,27 @@ var f = function (_a, _b) { };
var u = {};
u.a && u.b && f(u.a, u.b);
u.b && u.a && f(u.a, u.b);
function foo(obj) {
switch (obj.key) {
case '+': {
onlyPlus(obj.key);
return;
}
}
}
exports.foo = foo;
function onlyPlus(arg) {
return arg;
}
function func3(value) {
if (value.type !== undefined) {
switch (value.type) {
case 1 /* bar1 */:
break;
case 2 /* bar2 */:
break;
default:
never(value.type);
}
}
}
@@ -377,3 +377,134 @@ u.b && u.a && f(u.a, u.b);
>u : Symbol(u, Decl(discriminantPropertyCheck.ts, 116, 5))
>b : Symbol(b, Decl(discriminantPropertyCheck.ts, 105, 13), Decl(discriminantPropertyCheck.ts, 110, 12))
// Repro from #29012
type Additive = '+' | '-';
>Additive : Symbol(Additive, Decl(discriminantPropertyCheck.ts, 120, 26))
type Multiplicative = '*' | '/';
>Multiplicative : Symbol(Multiplicative, Decl(discriminantPropertyCheck.ts, 124, 26))
interface AdditiveObj {
>AdditiveObj : Symbol(AdditiveObj, Decl(discriminantPropertyCheck.ts, 125, 32))
key: Additive
>key : Symbol(AdditiveObj.key, Decl(discriminantPropertyCheck.ts, 127, 23))
>Additive : Symbol(Additive, Decl(discriminantPropertyCheck.ts, 120, 26))
}
interface MultiplicativeObj {
>MultiplicativeObj : Symbol(MultiplicativeObj, Decl(discriminantPropertyCheck.ts, 129, 1))
key: Multiplicative
>key : Symbol(MultiplicativeObj.key, Decl(discriminantPropertyCheck.ts, 131, 29))
>Multiplicative : Symbol(Multiplicative, Decl(discriminantPropertyCheck.ts, 124, 26))
}
type Obj = AdditiveObj | MultiplicativeObj
>Obj : Symbol(Obj, Decl(discriminantPropertyCheck.ts, 133, 1))
>AdditiveObj : Symbol(AdditiveObj, Decl(discriminantPropertyCheck.ts, 125, 32))
>MultiplicativeObj : Symbol(MultiplicativeObj, Decl(discriminantPropertyCheck.ts, 129, 1))
export function foo(obj: Obj) {
>foo : Symbol(foo, Decl(discriminantPropertyCheck.ts, 135, 42))
>obj : Symbol(obj, Decl(discriminantPropertyCheck.ts, 137, 20))
>Obj : Symbol(Obj, Decl(discriminantPropertyCheck.ts, 133, 1))
switch (obj.key) {
>obj.key : Symbol(key, Decl(discriminantPropertyCheck.ts, 127, 23), Decl(discriminantPropertyCheck.ts, 131, 29))
>obj : Symbol(obj, Decl(discriminantPropertyCheck.ts, 137, 20))
>key : Symbol(key, Decl(discriminantPropertyCheck.ts, 127, 23), Decl(discriminantPropertyCheck.ts, 131, 29))
case '+': {
onlyPlus(obj.key);
>onlyPlus : Symbol(onlyPlus, Decl(discriminantPropertyCheck.ts, 144, 1))
>obj.key : Symbol(AdditiveObj.key, Decl(discriminantPropertyCheck.ts, 127, 23))
>obj : Symbol(obj, Decl(discriminantPropertyCheck.ts, 137, 20))
>key : Symbol(AdditiveObj.key, Decl(discriminantPropertyCheck.ts, 127, 23))
return;
}
}
}
function onlyPlus(arg: '+') {
>onlyPlus : Symbol(onlyPlus, Decl(discriminantPropertyCheck.ts, 144, 1))
>arg : Symbol(arg, Decl(discriminantPropertyCheck.ts, 146, 18))
return arg;
>arg : Symbol(arg, Decl(discriminantPropertyCheck.ts, 146, 18))
}
// Repro from #29496
declare function never(value: never): never;
>never : Symbol(never, Decl(discriminantPropertyCheck.ts, 148, 1))
>value : Symbol(value, Decl(discriminantPropertyCheck.ts, 152, 23))
const enum BarEnum {
>BarEnum : Symbol(BarEnum, Decl(discriminantPropertyCheck.ts, 152, 44))
bar1 = 1,
>bar1 : Symbol(BarEnum.bar1, Decl(discriminantPropertyCheck.ts, 154, 20))
bar2 = 2,
>bar2 : Symbol(BarEnum.bar2, Decl(discriminantPropertyCheck.ts, 155, 13))
}
type UnionOfBar = TypeBar1 | TypeBar2;
>UnionOfBar : Symbol(UnionOfBar, Decl(discriminantPropertyCheck.ts, 157, 1))
>TypeBar1 : Symbol(TypeBar1, Decl(discriminantPropertyCheck.ts, 159, 38))
>TypeBar2 : Symbol(TypeBar2, Decl(discriminantPropertyCheck.ts, 160, 39))
type TypeBar1 = { type: BarEnum.bar1 };
>TypeBar1 : Symbol(TypeBar1, Decl(discriminantPropertyCheck.ts, 159, 38))
>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17))
>BarEnum : Symbol(BarEnum, Decl(discriminantPropertyCheck.ts, 152, 44))
>bar1 : Symbol(BarEnum.bar1, Decl(discriminantPropertyCheck.ts, 154, 20))
type TypeBar2 = { type: BarEnum.bar2 };
>TypeBar2 : Symbol(TypeBar2, Decl(discriminantPropertyCheck.ts, 160, 39))
>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 161, 17))
>BarEnum : Symbol(BarEnum, Decl(discriminantPropertyCheck.ts, 152, 44))
>bar2 : Symbol(BarEnum.bar2, Decl(discriminantPropertyCheck.ts, 155, 13))
function func3(value: Partial<UnionOfBar>) {
>func3 : Symbol(func3, Decl(discriminantPropertyCheck.ts, 161, 39))
>value : Symbol(value, Decl(discriminantPropertyCheck.ts, 163, 15))
>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --))
>UnionOfBar : Symbol(UnionOfBar, Decl(discriminantPropertyCheck.ts, 157, 1))
if (value.type !== undefined) {
>value.type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
>value : Symbol(value, Decl(discriminantPropertyCheck.ts, 163, 15))
>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
>undefined : Symbol(undefined)
switch (value.type) {
>value.type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
>value : Symbol(value, Decl(discriminantPropertyCheck.ts, 163, 15))
>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
case BarEnum.bar1:
>BarEnum.bar1 : Symbol(BarEnum.bar1, Decl(discriminantPropertyCheck.ts, 154, 20))
>BarEnum : Symbol(BarEnum, Decl(discriminantPropertyCheck.ts, 152, 44))
>bar1 : Symbol(BarEnum.bar1, Decl(discriminantPropertyCheck.ts, 154, 20))
break;
case BarEnum.bar2:
>BarEnum.bar2 : Symbol(BarEnum.bar2, Decl(discriminantPropertyCheck.ts, 155, 13))
>BarEnum : Symbol(BarEnum, Decl(discriminantPropertyCheck.ts, 152, 44))
>bar2 : Symbol(BarEnum.bar2, Decl(discriminantPropertyCheck.ts, 155, 13))
break;
default:
never(value.type);
>never : Symbol(never, Decl(discriminantPropertyCheck.ts, 148, 1))
>value.type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
>value : Symbol(value, Decl(discriminantPropertyCheck.ts, 163, 15))
>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 160, 17), Decl(discriminantPropertyCheck.ts, 161, 17))
}
}
}
@@ -378,3 +378,126 @@ u.b && u.a && f(u.a, u.b);
>u : U
>b : string
// Repro from #29012
type Additive = '+' | '-';
>Additive : Additive
type Multiplicative = '*' | '/';
>Multiplicative : Multiplicative
interface AdditiveObj {
key: Additive
>key : Additive
}
interface MultiplicativeObj {
key: Multiplicative
>key : Multiplicative
}
type Obj = AdditiveObj | MultiplicativeObj
>Obj : Obj
export function foo(obj: Obj) {
>foo : (obj: Obj) => void
>obj : Obj
switch (obj.key) {
>obj.key : "+" | "-" | "*" | "/"
>obj : Obj
>key : "+" | "-" | "*" | "/"
case '+': {
>'+' : "+"
onlyPlus(obj.key);
>onlyPlus(obj.key) : "+"
>onlyPlus : (arg: "+") => "+"
>obj.key : "+"
>obj : AdditiveObj
>key : "+"
return;
}
}
}
function onlyPlus(arg: '+') {
>onlyPlus : (arg: "+") => "+"
>arg : "+"
return arg;
>arg : "+"
}
// Repro from #29496
declare function never(value: never): never;
>never : (value: never) => never
>value : never
const enum BarEnum {
>BarEnum : BarEnum
bar1 = 1,
>bar1 : BarEnum.bar1
>1 : 1
bar2 = 2,
>bar2 : BarEnum.bar2
>2 : 2
}
type UnionOfBar = TypeBar1 | TypeBar2;
>UnionOfBar : UnionOfBar
type TypeBar1 = { type: BarEnum.bar1 };
>TypeBar1 : TypeBar1
>type : BarEnum.bar1
>BarEnum : any
type TypeBar2 = { type: BarEnum.bar2 };
>TypeBar2 : TypeBar2
>type : BarEnum.bar2
>BarEnum : any
function func3(value: Partial<UnionOfBar>) {
>func3 : (value: Partial<TypeBar1> | Partial<TypeBar2>) => void
>value : Partial<TypeBar1> | Partial<TypeBar2>
if (value.type !== undefined) {
>value.type !== undefined : boolean
>value.type : BarEnum | undefined
>value : Partial<TypeBar1> | Partial<TypeBar2>
>type : BarEnum | undefined
>undefined : undefined
switch (value.type) {
>value.type : BarEnum
>value : Partial<TypeBar1> | Partial<TypeBar2>
>type : BarEnum
case BarEnum.bar1:
>BarEnum.bar1 : BarEnum.bar1
>BarEnum : typeof BarEnum
>bar1 : BarEnum.bar1
break;
case BarEnum.bar2:
>BarEnum.bar2 : BarEnum.bar2
>BarEnum : typeof BarEnum
>bar2 : BarEnum.bar2
break;
default:
never(value.type);
>never(value.type) : never
>never : (value: never) => never
>value.type : never
>value : Partial<TypeBar1> | Partial<TypeBar2>
>type : never
}
}
}
@@ -0,0 +1,8 @@
tests/cases/compiler/dynamicImportTrailingComma.ts(2,12): error TS1009: Trailing comma not allowed.
==== tests/cases/compiler/dynamicImportTrailingComma.ts (1 errors) ====
const path = './foo';
import(path,);
~
!!! error TS1009: Trailing comma not allowed.
@@ -0,0 +1,7 @@
//// [dynamicImportTrailingComma.ts]
const path = './foo';
import(path,);
//// [dynamicImportTrailingComma.js]
var path = './foo';
Promise.resolve().then(function () { return require(path); });
@@ -0,0 +1,7 @@
=== tests/cases/compiler/dynamicImportTrailingComma.ts ===
const path = './foo';
>path : Symbol(path, Decl(dynamicImportTrailingComma.ts, 0, 5))
import(path,);
>path : Symbol(path, Decl(dynamicImportTrailingComma.ts, 0, 5))
@@ -0,0 +1,9 @@
=== tests/cases/compiler/dynamicImportTrailingComma.ts ===
const path = './foo';
>path : "./foo"
>'./foo' : "./foo"
import(path,);
>import(path,) : Promise<any>
>path : "./foo"
@@ -1,5 +1,5 @@
tests/cases/compiler/dynamicNamesErrors.ts(5,5): error TS2718: Duplicate declaration '[c0]'.
tests/cases/compiler/dynamicNamesErrors.ts(6,5): error TS2718: Duplicate declaration '[c0]'.
tests/cases/compiler/dynamicNamesErrors.ts(5,5): error TS2718: Duplicate property '1'.
tests/cases/compiler/dynamicNamesErrors.ts(6,5): error TS2733: Property '1' was also declared here.
tests/cases/compiler/dynamicNamesErrors.ts(19,5): error TS2717: Subsequent property declarations must have the same type. Property '[c1]' must be of type 'number', but here has type 'string'.
tests/cases/compiler/dynamicNamesErrors.ts(24,1): error TS2322: Type 'T2' is not assignable to type 'T1'.
Types of property '[c0]' are incompatible.
@@ -16,10 +16,10 @@ tests/cases/compiler/dynamicNamesErrors.ts(25,1): error TS2322: Type 'T1' is not
interface T0 {
[c0]: number;
~~~~
!!! error TS2718: Duplicate declaration '[c0]'.
!!! error TS2718: Duplicate property '1'.
1: number;
~
!!! error TS2718: Duplicate declaration '[c0]'.
!!! error TS2733: Property '1' was also declared here.
}
interface T1 {
@@ -23,6 +23,14 @@ function foo<T>(t: T) {
var rb3 = x in t;
}
function unionCase<T, U>(t: T | U) {
var rb4 = x in t;
}
function unionCase2<T>(t: T | object) {
var rb5 = x in t;
}
interface X { x: number }
interface Y { y: number }
@@ -53,6 +61,12 @@ var rb2 = x in {};
function foo(t) {
var rb3 = x in t;
}
function unionCase(t) {
var rb4 = x in t;
}
function unionCase2(t) {
var rb5 = x in t;
}
var c1;
var c2;
var c3;
@@ -59,35 +59,61 @@ function foo<T>(t: T) {
>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 20, 16))
}
function unionCase<T, U>(t: T | U) {
>unionCase : Symbol(unionCase, Decl(inOperatorWithValidOperands.ts, 22, 1))
>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 19))
>U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 24, 21))
>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 25))
>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 19))
>U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 24, 21))
var rb4 = x in t;
>rb4 : Symbol(rb4, Decl(inOperatorWithValidOperands.ts, 25, 7))
>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3))
>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 25))
}
function unionCase2<T>(t: T | object) {
>unionCase2 : Symbol(unionCase2, Decl(inOperatorWithValidOperands.ts, 26, 1))
>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 20))
>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 23))
>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 20))
var rb5 = x in t;
>rb5 : Symbol(rb5, Decl(inOperatorWithValidOperands.ts, 29, 7))
>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3))
>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 23))
}
interface X { x: number }
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 22, 1))
>x : Symbol(X.x, Decl(inOperatorWithValidOperands.ts, 24, 13))
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1))
>x : Symbol(X.x, Decl(inOperatorWithValidOperands.ts, 32, 13))
interface Y { y: number }
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 24, 25))
>y : Symbol(Y.y, Decl(inOperatorWithValidOperands.ts, 25, 13))
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25))
>y : Symbol(Y.y, Decl(inOperatorWithValidOperands.ts, 33, 13))
var c1: X | Y;
>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 27, 3))
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 22, 1))
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 24, 25))
>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 35, 3))
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1))
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25))
var c2: X;
>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 28, 3))
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 22, 1))
>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 36, 3))
>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1))
var c3: Y;
>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 29, 3))
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 24, 25))
>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 37, 3))
>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25))
var rc1 = x in c1;
>rc1 : Symbol(rc1, Decl(inOperatorWithValidOperands.ts, 31, 3))
>rc1 : Symbol(rc1, Decl(inOperatorWithValidOperands.ts, 39, 3))
>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3))
>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 27, 3))
>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 35, 3))
var rc2 = x in (c2 || c3);
>rc2 : Symbol(rc2, Decl(inOperatorWithValidOperands.ts, 32, 3))
>rc2 : Symbol(rc2, Decl(inOperatorWithValidOperands.ts, 40, 3))
>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3))
>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 28, 3))
>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 29, 3))
>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 36, 3))
>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 37, 3))
@@ -68,6 +68,28 @@ function foo<T>(t: T) {
>t : T
}
function unionCase<T, U>(t: T | U) {
>unionCase : <T, U>(t: T | U) => void
>t : T | U
var rb4 = x in t;
>rb4 : boolean
>x in t : boolean
>x : any
>t : T | U
}
function unionCase2<T>(t: T | object) {
>unionCase2 : <T>(t: object | T) => void
>t : object | T
var rb5 = x in t;
>rb5 : boolean
>x in t : boolean
>x : any
>t : object | T
}
interface X { x: number }
>x : number
@@ -5,19 +5,19 @@ const a = {};
>{} : {}
a.d = function() {};
>a.d = function() {} : { (): void; prototype: {}; }
>a.d : { (): void; prototype: {}; }
>a.d = function() {} : typeof d
>a.d : typeof d
>a : typeof a
>d : { (): void; prototype: {}; }
>function() {} : { (): void; prototype: {}; }
>d : typeof d
>function() {} : typeof d
=== tests/cases/conformance/salsa/b.js ===
a.d.prototype = {};
>a.d.prototype = {} : {}
>a.d.prototype : {}
>a.d : { (): void; prototype: {}; }
>a.d : typeof d
>a : typeof a
>d : { (): void; prototype: {}; }
>d : typeof d
>prototype : {}
>{} : {}
@@ -0,0 +1,8 @@
//// [mappedToToIndexSignatureInference.ts]
declare const fn: <K extends string, V>(object: { [Key in K]: V }) => object;
declare const a: { [index: string]: number };
fn(a);
//// [mappedToToIndexSignatureInference.js]
fn(a);
@@ -0,0 +1,18 @@
=== tests/cases/compiler/mappedToToIndexSignatureInference.ts ===
declare const fn: <K extends string, V>(object: { [Key in K]: V }) => object;
>fn : Symbol(fn, Decl(mappedToToIndexSignatureInference.ts, 0, 13))
>K : Symbol(K, Decl(mappedToToIndexSignatureInference.ts, 0, 19))
>V : Symbol(V, Decl(mappedToToIndexSignatureInference.ts, 0, 36))
>object : Symbol(object, Decl(mappedToToIndexSignatureInference.ts, 0, 40))
>Key : Symbol(Key, Decl(mappedToToIndexSignatureInference.ts, 0, 51))
>K : Symbol(K, Decl(mappedToToIndexSignatureInference.ts, 0, 19))
>V : Symbol(V, Decl(mappedToToIndexSignatureInference.ts, 0, 36))
declare const a: { [index: string]: number };
>a : Symbol(a, Decl(mappedToToIndexSignatureInference.ts, 1, 13))
>index : Symbol(index, Decl(mappedToToIndexSignatureInference.ts, 1, 20))
fn(a);
>fn : Symbol(fn, Decl(mappedToToIndexSignatureInference.ts, 0, 13))
>a : Symbol(a, Decl(mappedToToIndexSignatureInference.ts, 1, 13))
@@ -0,0 +1,14 @@
=== tests/cases/compiler/mappedToToIndexSignatureInference.ts ===
declare const fn: <K extends string, V>(object: { [Key in K]: V }) => object;
>fn : <K extends string, V>(object: { [Key in K]: V; }) => object
>object : { [Key in K]: V; }
declare const a: { [index: string]: number };
>a : { [index: string]: number; }
>index : string
fn(a);
>fn(a) : object
>fn : <K extends string, V>(object: { [Key in K]: V; }) => object
>a : { [index: string]: number; }
@@ -15,9 +15,15 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(84,6): error TS2445: Pro
tests/cases/conformance/classes/mixinAccessModifiers.ts(89,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses.
tests/cases/conformance/classes/mixinAccessModifiers.ts(97,6): error TS2445: Property 'p' is protected and only accessible within class 'C4' and its subclasses.
tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Property 's' is protected and only accessible within class 'typeof C4' and its subclasses.
tests/cases/conformance/classes/mixinAccessModifiers.ts(119,4): error TS2341: Property 'privateMethod' is private and only accessible within class 'ProtectedGeneric<T>'.
tests/cases/conformance/classes/mixinAccessModifiers.ts(120,4): error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<T>' and its subclasses.
tests/cases/conformance/classes/mixinAccessModifiers.ts(124,4): error TS2546: Property 'privateMethod' has conflicting declarations and is inaccessible in type 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>'.
tests/cases/conformance/classes/mixinAccessModifiers.ts(125,4): error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>' and its subclasses.
tests/cases/conformance/classes/mixinAccessModifiers.ts(129,4): error TS2546: Property 'privateMethod' has conflicting declarations and is inaccessible in type 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>'.
tests/cases/conformance/classes/mixinAccessModifiers.ts(130,4): error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<T>' and its subclasses.
==== tests/cases/conformance/classes/mixinAccessModifiers.ts (11 errors) ====
==== tests/cases/conformance/classes/mixinAccessModifiers.ts (17 errors) ====
type Constructable = new (...args: any[]) => object;
class Private {
@@ -152,4 +158,41 @@ tests/cases/conformance/classes/mixinAccessModifiers.ts(102,6): error TS2445: Pr
C6.s
}
}
class ProtectedGeneric<T> {
private privateMethod() {}
protected protectedMethod() {}
}
class ProtectedGeneric2<T> {
private privateMethod() {}
protected protectedMethod() {}
}
function f7(x: ProtectedGeneric<{}> & ProtectedGeneric<{}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
~~~~~~~~~~~~~
!!! error TS2341: Property 'privateMethod' is private and only accessible within class 'ProtectedGeneric<T>'.
x.protectedMethod(); // Error, protected when all constituents are protected
~~~~~~~~~~~~~~~
!!! error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<T>' and its subclasses.
}
function f8(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric2<{a:void;b:void;}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
~~~~~~~~~~~~~
!!! error TS2546: Property 'privateMethod' has conflicting declarations and is inaccessible in type 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>'.
x.protectedMethod(); // Error, protected when all constituents are protected
~~~~~~~~~~~~~~~
!!! error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>' and its subclasses.
}
function f9(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric<{a:void;b:void;}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
~~~~~~~~~~~~~
!!! error TS2546: Property 'privateMethod' has conflicting declarations and is inaccessible in type 'ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>'.
x.protectedMethod(); // Error, protected when all constituents are protected
~~~~~~~~~~~~~~~
!!! error TS2445: Property 'protectedMethod' is protected and only accessible within class 'ProtectedGeneric<T>' and its subclasses.
}
@@ -105,6 +105,31 @@ class C6 extends Mix(Public, Public2) {
C6.s
}
}
class ProtectedGeneric<T> {
private privateMethod() {}
protected protectedMethod() {}
}
class ProtectedGeneric2<T> {
private privateMethod() {}
protected protectedMethod() {}
}
function f7(x: ProtectedGeneric<{}> & ProtectedGeneric<{}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
function f8(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric2<{a:void;b:void;}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
function f9(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric<{a:void;b:void;}>) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
//// [mixinAccessModifiers.js]
@@ -266,6 +291,32 @@ var C6 = /** @class */ (function (_super) {
};
return C6;
}(Mix(Public, Public2)));
var ProtectedGeneric = /** @class */ (function () {
function ProtectedGeneric() {
}
ProtectedGeneric.prototype.privateMethod = function () { };
ProtectedGeneric.prototype.protectedMethod = function () { };
return ProtectedGeneric;
}());
var ProtectedGeneric2 = /** @class */ (function () {
function ProtectedGeneric2() {
}
ProtectedGeneric2.prototype.privateMethod = function () { };
ProtectedGeneric2.prototype.protectedMethod = function () { };
return ProtectedGeneric2;
}());
function f7(x) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
function f8(x) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
function f9(x) {
x.privateMethod(); // Error, private constituent makes method inaccessible
x.protectedMethod(); // Error, protected when all constituents are protected
}
//// [mixinAccessModifiers.d.ts]
@@ -329,3 +380,24 @@ declare class C6 extends C6_base {
f(c4: C4, c5: C5, c6: C6): void;
static g(): void;
}
declare class ProtectedGeneric<T> {
private privateMethod;
protected protectedMethod(): void;
}
declare class ProtectedGeneric2<T> {
private privateMethod;
protected protectedMethod(): void;
}
declare function f7(x: ProtectedGeneric<{}> & ProtectedGeneric<{}>): void;
declare function f8(x: ProtectedGeneric<{
a: void;
}> & ProtectedGeneric2<{
a: void;
b: void;
}>): void;
declare function f9(x: ProtectedGeneric<{
a: void;
}> & ProtectedGeneric<{
a: void;
b: void;
}>): void;
@@ -328,3 +328,82 @@ class C6 extends Mix(Public, Public2) {
}
}
class ProtectedGeneric<T> {
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
>T : Symbol(T, Decl(mixinAccessModifiers.ts, 107, 23))
private privateMethod() {}
>privateMethod : Symbol(ProtectedGeneric.privateMethod, Decl(mixinAccessModifiers.ts, 107, 27))
protected protectedMethod() {}
>protectedMethod : Symbol(ProtectedGeneric.protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27))
}
class ProtectedGeneric2<T> {
>ProtectedGeneric2 : Symbol(ProtectedGeneric2, Decl(mixinAccessModifiers.ts, 110, 1))
>T : Symbol(T, Decl(mixinAccessModifiers.ts, 112, 24))
private privateMethod() {}
>privateMethod : Symbol(ProtectedGeneric2.privateMethod, Decl(mixinAccessModifiers.ts, 112, 28))
protected protectedMethod() {}
>protectedMethod : Symbol(ProtectedGeneric2.protectedMethod, Decl(mixinAccessModifiers.ts, 113, 27))
}
function f7(x: ProtectedGeneric<{}> & ProtectedGeneric<{}>) {
>f7 : Symbol(f7, Decl(mixinAccessModifiers.ts, 115, 1))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 117, 12))
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod : Symbol(ProtectedGeneric.privateMethod, Decl(mixinAccessModifiers.ts, 107, 27))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 117, 12))
>privateMethod : Symbol(ProtectedGeneric.privateMethod, Decl(mixinAccessModifiers.ts, 107, 27))
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod : Symbol(ProtectedGeneric.protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 117, 12))
>protectedMethod : Symbol(ProtectedGeneric.protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27))
}
function f8(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric2<{a:void;b:void;}>) {
>f8 : Symbol(f8, Decl(mixinAccessModifiers.ts, 120, 1))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 122, 12))
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
>a : Symbol(a, Decl(mixinAccessModifiers.ts, 122, 33))
>ProtectedGeneric2 : Symbol(ProtectedGeneric2, Decl(mixinAccessModifiers.ts, 110, 1))
>a : Symbol(a, Decl(mixinAccessModifiers.ts, 122, 65))
>b : Symbol(b, Decl(mixinAccessModifiers.ts, 122, 72))
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod : Symbol(privateMethod, Decl(mixinAccessModifiers.ts, 107, 27), Decl(mixinAccessModifiers.ts, 112, 28))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 122, 12))
>privateMethod : Symbol(privateMethod, Decl(mixinAccessModifiers.ts, 107, 27), Decl(mixinAccessModifiers.ts, 112, 28))
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod : Symbol(protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27), Decl(mixinAccessModifiers.ts, 113, 27))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 122, 12))
>protectedMethod : Symbol(protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27), Decl(mixinAccessModifiers.ts, 113, 27))
}
function f9(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric<{a:void;b:void;}>) {
>f9 : Symbol(f9, Decl(mixinAccessModifiers.ts, 125, 1))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 127, 12))
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
>a : Symbol(a, Decl(mixinAccessModifiers.ts, 127, 33))
>ProtectedGeneric : Symbol(ProtectedGeneric, Decl(mixinAccessModifiers.ts, 105, 1))
>a : Symbol(a, Decl(mixinAccessModifiers.ts, 127, 64))
>b : Symbol(b, Decl(mixinAccessModifiers.ts, 127, 71))
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod : Symbol(ProtectedGeneric.privateMethod, Decl(mixinAccessModifiers.ts, 107, 27), Decl(mixinAccessModifiers.ts, 107, 27))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 127, 12))
>privateMethod : Symbol(ProtectedGeneric.privateMethod, Decl(mixinAccessModifiers.ts, 107, 27), Decl(mixinAccessModifiers.ts, 107, 27))
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod : Symbol(ProtectedGeneric.protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27), Decl(mixinAccessModifiers.ts, 108, 27))
>x : Symbol(x, Decl(mixinAccessModifiers.ts, 127, 12))
>protectedMethod : Symbol(ProtectedGeneric.protectedMethod, Decl(mixinAccessModifiers.ts, 108, 27), Decl(mixinAccessModifiers.ts, 108, 27))
}
@@ -307,3 +307,80 @@ class C6 extends Mix(Public, Public2) {
}
}
class ProtectedGeneric<T> {
>ProtectedGeneric : ProtectedGeneric<T>
private privateMethod() {}
>privateMethod : () => void
protected protectedMethod() {}
>protectedMethod : () => void
}
class ProtectedGeneric2<T> {
>ProtectedGeneric2 : ProtectedGeneric2<T>
private privateMethod() {}
>privateMethod : () => void
protected protectedMethod() {}
>protectedMethod : () => void
}
function f7(x: ProtectedGeneric<{}> & ProtectedGeneric<{}>) {
>f7 : (x: ProtectedGeneric<{}>) => void
>x : ProtectedGeneric<{}>
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod() : void
>x.privateMethod : () => void
>x : ProtectedGeneric<{}>
>privateMethod : () => void
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod() : void
>x.protectedMethod : () => void
>x : ProtectedGeneric<{}>
>protectedMethod : () => void
}
function f8(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric2<{a:void;b:void;}>) {
>f8 : (x: ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>) => void
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>
>a : void
>a : void
>b : void
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod() : void
>x.privateMethod : (() => void) & (() => void)
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>
>privateMethod : (() => void) & (() => void)
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod() : void
>x.protectedMethod : (() => void) & (() => void)
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric2<{ a: void; b: void; }>
>protectedMethod : (() => void) & (() => void)
}
function f9(x: ProtectedGeneric<{a: void;}> & ProtectedGeneric<{a:void;b:void;}>) {
>f9 : (x: ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>) => void
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>
>a : void
>a : void
>b : void
x.privateMethod(); // Error, private constituent makes method inaccessible
>x.privateMethod() : void
>x.privateMethod : (() => void) & (() => void)
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>
>privateMethod : (() => void) & (() => void)
x.protectedMethod(); // Error, protected when all constituents are protected
>x.protectedMethod() : void
>x.protectedMethod : (() => void) & (() => void)
>x : ProtectedGeneric<{ a: void; }> & ProtectedGeneric<{ a: void; b: void; }>
>protectedMethod : (() => void) & (() => void)
}
@@ -0,0 +1,11 @@
//// [parseGenericArrowRatherThanLeftShift.ts]
type Bar = ReturnType<<T>(x: T) => number>;
declare const a: Bar;
function foo<T>(_x: T) {}
const b = foo<<T>(x: T) => number>(() => 1);
//// [parseGenericArrowRatherThanLeftShift.js]
function foo(_x) { }
var b = foo(function () { return 1; });
@@ -0,0 +1,25 @@
=== tests/cases/compiler/parseGenericArrowRatherThanLeftShift.ts ===
type Bar = ReturnType<<T>(x: T) => number>;
>Bar : Symbol(Bar, Decl(parseGenericArrowRatherThanLeftShift.ts, 0, 0))
>ReturnType : Symbol(ReturnType, Decl(lib.es5.d.ts, --, --))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 0, 23))
>x : Symbol(x, Decl(parseGenericArrowRatherThanLeftShift.ts, 0, 26))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 0, 23))
declare const a: Bar;
>a : Symbol(a, Decl(parseGenericArrowRatherThanLeftShift.ts, 1, 13))
>Bar : Symbol(Bar, Decl(parseGenericArrowRatherThanLeftShift.ts, 0, 0))
function foo<T>(_x: T) {}
>foo : Symbol(foo, Decl(parseGenericArrowRatherThanLeftShift.ts, 1, 21))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 3, 13))
>_x : Symbol(_x, Decl(parseGenericArrowRatherThanLeftShift.ts, 3, 16))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 3, 13))
const b = foo<<T>(x: T) => number>(() => 1);
>b : Symbol(b, Decl(parseGenericArrowRatherThanLeftShift.ts, 4, 5))
>foo : Symbol(foo, Decl(parseGenericArrowRatherThanLeftShift.ts, 1, 21))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 4, 15))
>x : Symbol(x, Decl(parseGenericArrowRatherThanLeftShift.ts, 4, 18))
>T : Symbol(T, Decl(parseGenericArrowRatherThanLeftShift.ts, 4, 15))
@@ -0,0 +1,20 @@
=== tests/cases/compiler/parseGenericArrowRatherThanLeftShift.ts ===
type Bar = ReturnType<<T>(x: T) => number>;
>Bar : number
>x : T
declare const a: Bar;
>a : number
function foo<T>(_x: T) {}
>foo : <T>(_x: T) => void
>_x : T
const b = foo<<T>(x: T) => number>(() => 1);
>b : void
>foo<<T>(x: T) => number>(() => 1) : void
>foo : <T>(_x: T) => void
>x : T
>() => 1 : () => number
>1 : 1
@@ -0,0 +1,42 @@
//// [partialTypeNarrowedToByTypeGuard.ts]
type Obj = {} | undefined;
type User = {
email: string;
name: string;
};
type PartialUser = Partial<User>;
// type PartialUser = {
// email?: string;
// name?: string;
// };
function isUser(obj: Obj): obj is PartialUser {
return true;
}
function getUserName(obj: Obj) {
if (isUser(obj)) {
return obj.name;
}
return '';
}
//// [partialTypeNarrowedToByTypeGuard.js]
"use strict";
// type PartialUser = {
// email?: string;
// name?: string;
// };
function isUser(obj) {
return true;
}
function getUserName(obj) {
if (isUser(obj)) {
return obj.name;
}
return '';
}
@@ -0,0 +1,52 @@
=== tests/cases/compiler/partialTypeNarrowedToByTypeGuard.ts ===
type Obj = {} | undefined;
>Obj : Symbol(Obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 0, 0))
type User = {
>User : Symbol(User, Decl(partialTypeNarrowedToByTypeGuard.ts, 0, 26))
email: string;
>email : Symbol(email, Decl(partialTypeNarrowedToByTypeGuard.ts, 2, 13))
name: string;
>name : Symbol(name, Decl(partialTypeNarrowedToByTypeGuard.ts, 3, 18))
};
type PartialUser = Partial<User>;
>PartialUser : Symbol(PartialUser, Decl(partialTypeNarrowedToByTypeGuard.ts, 5, 2))
>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --))
>User : Symbol(User, Decl(partialTypeNarrowedToByTypeGuard.ts, 0, 26))
// type PartialUser = {
// email?: string;
// name?: string;
// };
function isUser(obj: Obj): obj is PartialUser {
>isUser : Symbol(isUser, Decl(partialTypeNarrowedToByTypeGuard.ts, 7, 33))
>obj : Symbol(obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 14, 16))
>Obj : Symbol(Obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 0, 0))
>obj : Symbol(obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 14, 16))
>PartialUser : Symbol(PartialUser, Decl(partialTypeNarrowedToByTypeGuard.ts, 5, 2))
return true;
}
function getUserName(obj: Obj) {
>getUserName : Symbol(getUserName, Decl(partialTypeNarrowedToByTypeGuard.ts, 16, 1))
>obj : Symbol(obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 18, 21))
>Obj : Symbol(Obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 0, 0))
if (isUser(obj)) {
>isUser : Symbol(isUser, Decl(partialTypeNarrowedToByTypeGuard.ts, 7, 33))
>obj : Symbol(obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 18, 21))
return obj.name;
>obj.name : Symbol(name, Decl(partialTypeNarrowedToByTypeGuard.ts, 3, 18))
>obj : Symbol(obj, Decl(partialTypeNarrowedToByTypeGuard.ts, 18, 21))
>name : Symbol(name, Decl(partialTypeNarrowedToByTypeGuard.ts, 3, 18))
}
return '';
}
@@ -0,0 +1,49 @@
=== tests/cases/compiler/partialTypeNarrowedToByTypeGuard.ts ===
type Obj = {} | undefined;
>Obj : Obj
type User = {
>User : User
email: string;
>email : string
name: string;
>name : string
};
type PartialUser = Partial<User>;
>PartialUser : Partial<User>
// type PartialUser = {
// email?: string;
// name?: string;
// };
function isUser(obj: Obj): obj is PartialUser {
>isUser : (obj: Obj) => obj is Partial<User>
>obj : Obj
return true;
>true : true
}
function getUserName(obj: Obj) {
>getUserName : (obj: Obj) => string | undefined
>obj : Obj
if (isUser(obj)) {
>isUser(obj) : boolean
>isUser : (obj: Obj) => obj is Partial<User>
>obj : Obj
return obj.name;
>obj.name : string | undefined
>obj : Partial<User>
>name : string | undefined
}
return '';
>'' : ""
}
@@ -0,0 +1,15 @@
error TS2318: Cannot find global type 'IterableIterator'.
tests/cases/compiler/spreadOfParamsFromGeneratorMakesRequiredParams.ts(6,1): error TS2554: Expected 2 arguments, but got 1.
!!! error TS2318: Cannot find global type 'IterableIterator'.
==== tests/cases/compiler/spreadOfParamsFromGeneratorMakesRequiredParams.ts (1 errors) ====
declare function call<Fn extends (...args: any[]) => any>(
fn: Fn,
...args: Parameters<Fn>
): any;
call(function* (a: 'a') { }); // error, 2nd argument required
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2554: Expected 2 arguments, but got 1.
!!! related TS6210 tests/cases/compiler/spreadOfParamsFromGeneratorMakesRequiredParams.ts:3:5: An argument for 'args' was not provided.
@@ -0,0 +1,39 @@
//// [spreadOfParamsFromGeneratorMakesRequiredParams.ts]
declare function call<Fn extends (...args: any[]) => any>(
fn: Fn,
...args: Parameters<Fn>
): any;
call(function* (a: 'a') { }); // error, 2nd argument required
//// [spreadOfParamsFromGeneratorMakesRequiredParams.js]
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
call(function (a) { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); // error, 2nd argument required
@@ -0,0 +1,21 @@
=== tests/cases/compiler/spreadOfParamsFromGeneratorMakesRequiredParams.ts ===
declare function call<Fn extends (...args: any[]) => any>(
>call : Symbol(call, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 0))
>Fn : Symbol(Fn, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 22))
>args : Symbol(args, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 34))
fn: Fn,
>fn : Symbol(fn, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 58))
>Fn : Symbol(Fn, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 22))
...args: Parameters<Fn>
>args : Symbol(args, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 1, 11))
>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --))
>Fn : Symbol(Fn, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 22))
): any;
call(function* (a: 'a') { }); // error, 2nd argument required
>call : Symbol(call, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 0, 0))
>a : Symbol(a, Decl(spreadOfParamsFromGeneratorMakesRequiredParams.ts, 5, 16))
@@ -0,0 +1,19 @@
=== tests/cases/compiler/spreadOfParamsFromGeneratorMakesRequiredParams.ts ===
declare function call<Fn extends (...args: any[]) => any>(
>call : <Fn extends (...args: any[]) => any>(fn: Fn, ...args: Parameters<Fn>) => any
>args : any[]
fn: Fn,
>fn : Fn
...args: Parameters<Fn>
>args : Parameters<Fn>
): any;
call(function* (a: 'a') { }); // error, 2nd argument required
>call(function* (a: 'a') { }) : any
>call : <Fn extends (...args: any[]) => any>(fn: Fn, ...args: Parameters<Fn>) => any
>function* (a: 'a') { } : (a: "a") => {}
>a : "a"
@@ -12,9 +12,10 @@ tests/cases/conformance/jsx/file.tsx(26,40): error TS2322: Type 'string' is not
tests/cases/conformance/jsx/file.tsx(33,32): error TS2322: Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/jsx/file.tsx(34,29): error TS2322: Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/jsx/file.tsx(35,29): error TS2322: Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/jsx/file.tsx(36,29): error TS2322: Type 'string' is not assignable to type 'boolean'.
==== tests/cases/conformance/jsx/file.tsx (10 errors) ====
==== tests/cases/conformance/jsx/file.tsx (11 errors) ====
import React = require('react')
declare function OneThing(): JSX.Element;
declare function OneThing(l: {yy: number, yy1: string}): JSX.Element;
@@ -82,4 +83,7 @@ tests/cases/conformance/jsx/file.tsx(35,29): error TS2322: Type 'string' is not
!!! error TS2322: Type 'string' is not assignable to type 'boolean'.
!!! related TS6500 tests/cases/conformance/jsx/file.tsx:30:38: The expected type comes from property 'y1' which is declared here on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'
const e4 = <TestingOptional y1="hello" y2={1000}>Hi</TestingOptional>
~~
!!! error TS2322: Type 'string' is not assignable to type 'boolean'.
!!! related TS6500 tests/cases/conformance/jsx/file.tsx:30:38: The expected type comes from property 'y1' which is declared here on type 'IntrinsicAttributes & { y1: boolean; y2?: number; y3: boolean; }'
@@ -5,18 +5,18 @@ var Outer = {};
=== tests/cases/conformance/salsa/work.js ===
Outer.Inner = function () {}
>Outer.Inner = function () {} : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner = function () {} : typeof Inner
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>function () {} : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
>function () {} : typeof Inner
Outer.Inner.prototype = {
>Outer.Inner.prototype = { x: 1, m() { }} : { x: number; m(): void; }
>Outer.Inner.prototype : { x: number; m(): void; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
>prototype : { x: number; m(): void; }
>{ x: 1, m() { }} : { x: number; m(): void; }
@@ -47,9 +47,9 @@ inner.m()
var inno = new Outer.Inner()
>inno : { x: number; m(): void; }
>new Outer.Inner() : { x: number; m(): void; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
inno.x
>inno.x : number
@@ -4,18 +4,18 @@ var Outer = {};
>{} : {}
Outer.Inner = function () {}
>Outer.Inner = function () {} : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner = function () {} : typeof Inner
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>function () {} : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
>function () {} : typeof Inner
Outer.Inner.prototype = {
>Outer.Inner.prototype = { x: 1, m() { }} : { x: number; m(): void; }
>Outer.Inner.prototype : { x: number; m(): void; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
>prototype : { x: number; m(): void; }
>{ x: 1, m() { }} : { x: number; m(): void; }
@@ -45,9 +45,9 @@ inner.m()
var inno = new Outer.Inner()
>inno : { x: number; m(): void; }
>new Outer.Inner() : { x: number; m(): void; }
>Outer.Inner : { (): void; prototype: { x: number; m(): void; }; }
>Outer.Inner : typeof Inner
>Outer : typeof Outer
>Inner : { (): void; prototype: { x: number; m(): void; }; }
>Inner : typeof Inner
inno.x
>inno.x : number
@@ -0,0 +1,26 @@
tests/cases/conformance/salsa/bug26885.js(2,5): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
tests/cases/conformance/salsa/bug26885.js(11,16): error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.
==== tests/cases/conformance/salsa/bug26885.js (2 errors) ====
function Multimap3() {
this._map = {};
~~~~
!!! error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
};
Multimap3.prototype = {
/**
* @param {string} key
* @returns {number} the value ok
*/
get(key) {
return this._map[key + ''];
~~~~~~~~~~~~~~~~~~~
!!! error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.
}
}
/** @type {Multimap3} */
const map = new Multimap3();
const n = map.get('hi')
@@ -0,0 +1,40 @@
=== tests/cases/conformance/salsa/bug26885.js ===
function Multimap3() {
>Multimap3 : Symbol(Multimap3, Decl(bug26885.js, 0, 0), Decl(bug26885.js, 2, 2))
this._map = {};
>_map : Symbol(Multimap3._map, Decl(bug26885.js, 0, 22))
};
Multimap3.prototype = {
>Multimap3.prototype : Symbol(Multimap3.prototype, Decl(bug26885.js, 2, 2))
>Multimap3 : Symbol(Multimap3, Decl(bug26885.js, 0, 0), Decl(bug26885.js, 2, 2))
>prototype : Symbol(Multimap3.prototype, Decl(bug26885.js, 2, 2))
/**
* @param {string} key
* @returns {number} the value ok
*/
get(key) {
>get : Symbol(get, Decl(bug26885.js, 4, 23))
>key : Symbol(key, Decl(bug26885.js, 9, 8))
return this._map[key + ''];
>this._map : Symbol(Multimap3._map, Decl(bug26885.js, 0, 22))
>_map : Symbol(Multimap3._map, Decl(bug26885.js, 0, 22))
>key : Symbol(key, Decl(bug26885.js, 9, 8))
}
}
/** @type {Multimap3} */
const map = new Multimap3();
>map : Symbol(map, Decl(bug26885.js, 15, 5))
>Multimap3 : Symbol(Multimap3, Decl(bug26885.js, 0, 0), Decl(bug26885.js, 2, 2))
const n = map.get('hi')
>n : Symbol(n, Decl(bug26885.js, 16, 5))
>map.get : Symbol(get, Decl(bug26885.js, 4, 23))
>map : Symbol(map, Decl(bug26885.js, 15, 5))
>get : Symbol(get, Decl(bug26885.js, 4, 23))
@@ -0,0 +1,53 @@
=== tests/cases/conformance/salsa/bug26885.js ===
function Multimap3() {
>Multimap3 : typeof Multimap3
this._map = {};
>this._map = {} : {}
>this._map : any
>this : any
>_map : any
>{} : {}
};
Multimap3.prototype = {
>Multimap3.prototype = { /** * @param {string} key * @returns {number} the value ok */ get(key) { return this._map[key + '']; }} : { get(key: string): number; }
>Multimap3.prototype : { get(key: string): number; }
>Multimap3 : typeof Multimap3
>prototype : { get(key: string): number; }
>{ /** * @param {string} key * @returns {number} the value ok */ get(key) { return this._map[key + '']; }} : { get(key: string): number; }
/**
* @param {string} key
* @returns {number} the value ok
*/
get(key) {
>get : (key: string) => number
>key : string
return this._map[key + ''];
>this._map[key + ''] : any
>this._map : {}
>this : Multimap3 & { get(key: string): number; }
>_map : {}
>key + '' : string
>key : string
>'' : ""
}
}
/** @type {Multimap3} */
const map = new Multimap3();
>map : Multimap3 & { get(key: string): number; }
>new Multimap3() : Multimap3 & { get(key: string): number; }
>Multimap3 : typeof Multimap3
const n = map.get('hi')
>n : number
>map.get('hi') : number
>map.get : (key: string) => number
>map : Multimap3 & { get(key: string): number; }
>get : (key: string) => number
>'hi' : "hi"
@@ -33,9 +33,9 @@ function f<T extends Cat | Dog>(a: T) {
>T : Symbol(T, Decl(typeParameterExtendingUnion1.ts, 8, 11))
a.run();
>a.run : Symbol(run, Decl(typeParameterExtendingUnion1.ts, 0, 14), Decl(typeParameterExtendingUnion1.ts, 0, 14))
>a.run : Symbol(Animal.run, Decl(typeParameterExtendingUnion1.ts, 0, 14), Decl(typeParameterExtendingUnion1.ts, 0, 14))
>a : Symbol(a, Decl(typeParameterExtendingUnion1.ts, 8, 32))
>run : Symbol(run, Decl(typeParameterExtendingUnion1.ts, 0, 14), Decl(typeParameterExtendingUnion1.ts, 0, 14))
>run : Symbol(Animal.run, Decl(typeParameterExtendingUnion1.ts, 0, 14), Decl(typeParameterExtendingUnion1.ts, 0, 14))
run(a);
>run : Symbol(run, Decl(typeParameterExtendingUnion1.ts, 2, 33))

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