diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b58cc2875a78..18c0a352cbdcb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,11 +59,11 @@ Run `gulp` to build a version of the compiler/language service that reflects cha ## 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. +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 (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)) 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. ## Contributing features -Features (things that add new or improved functionality to TypeScript) may be accepted, but will need to first be approved (marked as "Milestone == Community" by a TypeScript coordinator with the message "Approved") in the suggestion issue. Features with language design impact, or that are adequately satisfied with external tools, will not be accepted. +Features (things that add new or improved functionality to TypeScript) may be accepted, but will need to first be approved ([labelled "help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) by a TypeScript project maintainer) in the suggestion issue. Features with language design impact, or that are adequately satisfied with external tools, will not be accepted. Design changes will not be accepted at this time. If you have a design change proposal, please log a suggestion issue. diff --git a/Gulpfile.js b/Gulpfile.js index 582c07fef3eac..bfc4bf43db724 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -545,6 +545,10 @@ const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerel task("configure-insiders", series(buildScripts, configureInsiders)); task("configure-insiders").description = "Runs scripts/configurePrerelease.ts to prepare a build for insiders publishing"; +const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/core.ts"]) +task("configure-experimental", series(buildScripts, configureExperimental)); +task("configure-experimental").description = "Runs scripts/configurePrerelease.ts to prepare a build for experimental publishing"; + const publishNightly = () => exec("npm", ["publish", "--tag", "next"]); task("publish-nightly", series(task("clean"), task("LKG"), task("clean"), task("runtests-parallel"), publishNightly)); task("publish-nightly").description = "Runs `npm publish --tag next` to create a new nightly build on npm"; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e99261be3f3b5..cb035b63293e3 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -626,7 +626,7 @@ declare namespace ts { initializer?: Expression; } interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index d7b494960537c..907cdf391440e 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -626,7 +626,7 @@ declare namespace ts { initializer?: Expression; } interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 6b5bd1778e661..64211e8254da8 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -626,7 +626,7 @@ declare namespace ts { initializer?: Expression; } interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ diff --git a/package.json b/package.json index 493a3501d2f51..a50a79aff1322 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,6 @@ "gulp-rename": "latest", "gulp-sourcemaps": "latest", "istanbul": "latest", - "lodash": "^4.17.11", "merge2": "latest", "minimist": "latest", "mkdirp": "latest", diff --git a/scripts/configurePrerelease.ts b/scripts/configurePrerelease.ts index 93bcc004deab6..5e3ac5653d72e 100644 --- a/scripts/configurePrerelease.ts +++ b/scripts/configurePrerelease.ts @@ -22,7 +22,7 @@ function main(): void { } const tag = args[0]; - if (tag !== "dev" && tag !== "insiders") { + if (tag !== "dev" && tag !== "insiders" && tag !== "experimental") { throw new Error(`Unexpected tag name '${tag}'.`); } diff --git a/scripts/open-user-pr.ts b/scripts/open-user-pr.ts index 9c582ad9895de..0a636c267b825 100644 --- a/scripts/open-user-pr.ts +++ b/scripts/open-user-pr.ts @@ -1,16 +1,7 @@ /// // Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally -import cp = require("child_process"); import Octokit = require("@octokit/rest"); - -const opts = { timeout: 100_000, shell: true, stdio: "inherit" } -function runSequence(tasks: [string, string[]][]) { - for (const task of tasks) { - console.log(`${task[0]} ${task[1].join(" ")}`); - const result = cp.spawnSync(task[0], task[1], opts); - if (result.status !== 0) throw new Error(`${task[0]} ${task[1].join(" ")} failed: ${result.stderr && result.stderr.toString()}`); - } -} +import {runSequence} from "./run-sequence"; function padNum(number: number) { const str = "" + number; diff --git a/scripts/run-sequence.js b/scripts/run-sequence.js new file mode 100644 index 0000000000000..ef7a384af4c6e --- /dev/null +++ b/scripts/run-sequence.js @@ -0,0 +1,19 @@ +// @ts-check +const cp = require("child_process"); +/** + * + * @param {[string, string[]][]} tasks + * @param {cp.SpawnSyncOptions} opts + */ +function runSequence(tasks, opts = { timeout: 100000, shell: true, stdio: "inherit" }) { + let lastResult; + for (const task of tasks) { + console.log(`${task[0]} ${task[1].join(" ")}`); + const result = cp.spawnSync(task[0], task[1], opts); + if (result.status !== 0) throw new Error(`${task[0]} ${task[1].join(" ")} failed: ${result.stderr && result.stderr.toString()}`); + lastResult = result; + } + return lastResult && lastResult.stdout && lastResult.stdout.toString(); +} + +exports.runSequence = runSequence; \ No newline at end of file diff --git a/scripts/update-experimental-branches.js b/scripts/update-experimental-branches.js new file mode 100644 index 0000000000000..c112cf1a3673d --- /dev/null +++ b/scripts/update-experimental-branches.js @@ -0,0 +1,97 @@ +// @ts-check +/// +const Octokit = require("@octokit/rest"); +const {runSequence} = require("./run-sequence"); + +/** + * This program should be invoked as `node ./scripts/update-experimental-branches [Branch2] [...]` + */ +async function main() { + const branchesRaw = process.argv[3]; + const branches = process.argv.slice(3); + if (!branches.length) { + throw new Error(`No experimental branches, aborting...`); + } + console.log(`Performing experimental branch updating and merging for branches ${branchesRaw}`); + + const gh = new Octokit(); + gh.authenticate({ + type: "token", + token: process.argv[2] + }); + + // Fetch all relevant refs + runSequence([ + ["git", ["fetch", "origin", "master:master", ...branches.map(b => `${b}:${b}`)]] + ]) + + // Forcibly cleanup workspace + runSequence([ + ["git", ["clean", "-fdx"]], + ["git", ["checkout", "."]], + ["git", ["checkout", "master"]], + ]); + + // Update branches + for (const branch of branches) { + // Checkout, then get the merge base + const mergeBase = runSequence([ + ["git", ["checkout", branch]], + ["git", ["merge-base", branch, "master"]], + ]); + // Simulate the merge and abort if there are conflicts + const mergeTree = runSequence([ + ["git", ["merge-tree", mergeBase, branch, "master"]] + ]); + if (mergeTree.indexOf(`===${"="}===`)) { // 7 equals is the center of the merge conflict marker + const res = await gh.pulls.list({owner: "Microsoft", repo: "TypeScript", base: branch}); + if (res && res.data && res.data[0]) { + const pr = res.data[0]; + await gh.issues.createComment({ + owner: "Microsoft", + repo: "TypeScript", + number: pr.number, + body: `This PR is configured as an experiment, and currently has merge conflicts with master - please rebase onto master and fix the conflicts.` + }); + } + throw new Error(`Merge conflict detected on branch ${branch} with master`); + } + // Merge is good - apply a rebase and (force) push + runSequence([ + ["git", ["rebase", "master"]], + ["git", ["push", "-f", "-u", "origin", branch]], + ]); + } + + // Return to `master` and make a new `experimental` branch + runSequence([ + ["git", ["checkout", "master"]], + ["git", ["branch", "-D", "experimental"]], + ["git", ["checkout", "-b", "experimental"]], + ]); + + // Merge each branch into `experimental` (which, if there is a conflict, we now know is from inter-experiment conflict) + for (const branch of branches) { + // Find the merge base + const mergeBase = runSequence([ + ["git", ["merge-base", branch, "experimental"]], + ]); + // Simulate the merge and abort if there are conflicts + const mergeTree = runSequence([ + ["git", ["merge-tree", mergeBase, branch, "experimental"]] + ]); + if (mergeTree.indexOf(`===${"="}===`)) { // 7 equals is the center of the merge conflict marker + throw new Error(`Merge conflict detected on branch ${branch} with other experiment`); + } + // Merge (always producing a merge commit) + runSequence([ + ["git", ["merge", branch, "--no-ff"]], + ]); + } + // Every branch merged OK, force push the replacement `experimental` branch + runSequence([ + ["git", ["push", "-f", "-u", "origin", "experimental"]], + ]); +} + +main().catch(e => (console.error(e), process.exitCode = 2)); diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index ef22ec250b3d2..78058bf5a5341 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -238,10 +238,7 @@ namespace ts { if (oldCompilerOptions && compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed - state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(f => f.path)); - if (state.affectedFilesPendingEmitIndex === undefined) { - state.affectedFilesPendingEmitIndex = 0; - } + addToAffectedFilesPendingEmit(state, newProgram.getSourceFiles().map(f => f.path)); Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = createMap(); } @@ -339,7 +336,7 @@ namespace ts { if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -406,31 +403,83 @@ namespace ts { } /** - * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + * Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file + * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ - function cleanSemanticDiagnosticsOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile) { - if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { - // If there are no more diagnostics from old cache, done + function handleDtsMayChangeOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash) { + removeSemanticDiagnosticsOf(state, affectedFile.path); + + // If affected files is everything except default library, then nothing more to do + if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { + if (!state.cleanedDiagnosticsOfLibFiles) { + state.cleanedDiagnosticsOfLibFiles = true; + const program = Debug.assertDefined(state.program); + const options = program.getCompilerOptions(); + forEach(program.getSourceFiles(), f => + program.isSourceFileDefaultLibrary(f) && + !skipTypeChecking(f, options) && + removeSemanticDiagnosticsOf(state, f.path) + ); + } return; } - // Clean lib file diagnostics if its all files excluding default files to emit - if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { - state.cleanedDiagnosticsOfLibFiles = true; + forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, (state, path) => handleDtsMayChangeOf(state, path, cancellationToken, computeHash)); + } + + /** + * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled, + * Also we need to make sure signature is updated for these files + */ + function handleDtsMayChangeOf(state: BuilderProgramState, path: Path, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash) { + removeSemanticDiagnosticsOf(state, path); + + if (!state.changedFilesSet.has(path)) { const program = Debug.assertDefined(state.program); - const options = program.getCompilerOptions(); - if (forEach(program.getSourceFiles(), f => - program.isSourceFileDefaultLibrary(f) && - !skipTypeChecking(f, options) && - removeSemanticDiagnosticsOf(state, f.path) - )) { - return; + const sourceFile = program.getSourceFileByPath(path); + if (sourceFile) { + // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics + // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file + // This ensures that we dont later during incremental builds considering wrong signature. + // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build + BuilderState.updateShapeSignature( + state, + program, + sourceFile, + Debug.assertDefined(state.currentAffectedFilesSignatures), + cancellationToken, + computeHash, + state.currentAffectedFilesExportedModulesMap + ); + // If not dts emit, nothing more to do + if (getEmitDeclarations(state.compilerOptions)) { + addToAffectedFilesPendingEmit(state, [path]); + } } } - // If there was change in signature for the changed file, - // then delete the semantic diagnostics for files that are affected by using exports of this module + return false; + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) { + if (!state.semanticDiagnosticsFromOldState) { + return true; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile!.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } + + /** + * Iterate on referencing modules that export entities from affected file + */ + function forEachReferencingModulesOfExportOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, fn: (state: BuilderProgramState, filePath: Path) => boolean) { + // If there was change in signature (dts output) for the changed file, + // then only we need to handle pending file emit if (!state.exportedModulesMap || state.affectedFiles!.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { return; } @@ -442,7 +491,7 @@ namespace ts { if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) + forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn) )) { return; } @@ -451,29 +500,28 @@ namespace ts { forEachEntry(state.exportedModulesMap, (exportedModules, exportedFromPath) => !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) + forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn) ); } /** - * removes the semantic diagnostics of files referencing referencedPath and - * returns true if there are no more semantic diagnostics from old state + * Iterate on files referencing referencedPath */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path, seenFileAndExportsOfFile: Map) { + function forEachFilesReferencingPath(state: BuilderProgramState, referencedPath: Path, seenFileAndExportsOfFile: Map, fn: (state: BuilderProgramState, filePath: Path) => boolean) { return forEachEntry(state.referencedMap!, (referencesInFile, filePath) => - referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath as Path, seenFileAndExportsOfFile) + referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath as Path, seenFileAndExportsOfFile, fn) ); } /** - * Removes semantic diagnostics of file and anything that exports this file + * fn on file and iterate on anything that exports this file */ - function removeSemanticDiagnosticsOfFileAndExportsOfFile(state: BuilderProgramState, filePath: Path, seenFileAndExportsOfFile: Map): boolean { + function forEachFileAndExportsOfFile(state: BuilderProgramState, filePath: Path, seenFileAndExportsOfFile: Map, fn: (state: BuilderProgramState, filePath: Path) => boolean): boolean { if (!addToSeen(seenFileAndExportsOfFile, filePath)) { return false; } - if (removeSemanticDiagnosticsOf(state, filePath)) { + if (fn(state, filePath)) { // If there are no more diagnostics from old cache, done return true; } @@ -484,7 +532,7 @@ namespace ts { if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => exportedModules && exportedModules.has(filePath) && - removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) + forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn) )) { return true; } @@ -493,7 +541,7 @@ namespace ts { if (forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) => !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && - removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) + forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn) )) { return true; } @@ -502,22 +550,10 @@ namespace ts { return !!forEachEntry(state.referencedMap!, (referencesInFile, referencingFilePath) => referencesInFile.has(filePath) && !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file - removeSemanticDiagnosticsOf(state, referencingFilePath as Path) // Dont add to seen since this is not yet done with the export removal + fn(state, referencingFilePath as Path) // Dont add to seen since this is not yet done with the export removal ); } - /** - * Removes semantic diagnostics for path and - * returns true if there are no more semantic diagnostics from the old state - */ - function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) { - if (!state.semanticDiagnosticsFromOldState) { - return true; - } - state.semanticDiagnosticsFromOldState.delete(path); - state.semanticDiagnosticsPerFile!.delete(path); - return !state.semanticDiagnosticsFromOldState.size; - } /** * This is called after completing operation on the next affected file. @@ -808,11 +844,6 @@ namespace ts { } } - // Mark seen emitted files if there are pending files to be emitted - if (state.affectedFilesPendingEmit && state.program !== affected) { - (state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).path, true); - } - return toAffectedFileResult( state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) @@ -931,14 +962,7 @@ namespace ts { // In case of emit builder, cache the files to be emitted if (affectedFilesPendingEmit) { - state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); - // affectedFilesPendingEmitIndex === undefined - // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files - // so start from 0 as array would be affectedFilesPendingEmit - // else, continue to iterate from existing index, the current set is appended to existing files - if (state.affectedFilesPendingEmitIndex === undefined) { - state.affectedFilesPendingEmitIndex = 0; - } + addToAffectedFilesPendingEmit(state, affectedFilesPendingEmit); } let diagnostics: Diagnostic[] | undefined; @@ -949,6 +973,17 @@ namespace ts { } } + function addToAffectedFilesPendingEmit(state: BuilderProgramState, affectedFilesPendingEmit: readonly Path[]) { + state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; + } + } + function getMapOfReferencedSet(mapLike: MapLike> | undefined): ReadonlyMap | undefined { if (!mapLike) return undefined; const map = createMap(); diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index b7f01b838fdbf..58b189d9e81d4 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -321,7 +321,7 @@ namespace ts.BuilderState { /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state: Readonly, programOfThisState: Program, sourceFile: SourceFile, cacheToUpdateSignature: Map, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, exportedModulesMapCache?: ComputingExportedModulesMap) { + export function updateShapeSignature(state: Readonly, programOfThisState: Program, sourceFile: SourceFile, cacheToUpdateSignature: Map, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, exportedModulesMapCache?: ComputingExportedModulesMap) { Debug.assert(!!sourceFile); Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0b486de1891a3..87010df583597 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1293,6 +1293,8 @@ namespace ts { let lastLocation: Node | undefined; let lastSelfReferenceLocation: Node | undefined; let propertyWithInvalidInitializer: Node | undefined; + let associatedDeclarationForContainingInitializer: ParameterDeclaration | BindingElement | undefined; + let withinDeferredContext = false; const errorLocation = location; let grandparent: Node; let isInExternalModule = false; @@ -1353,6 +1355,7 @@ namespace ts { } } } + withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { case SyntaxKind.SourceFile: if (!isExternalOrCommonJsModule(location)) break; @@ -1548,6 +1551,19 @@ namespace ts { // js type aliases do not resolve names from their host, so skip past it location = getJSDocHost(location); break; + case SyntaxKind.Parameter: + if (lastLocation && lastLocation === (location as ParameterDeclaration).initializer) { + associatedDeclarationForContainingInitializer = location as ParameterDeclaration; + } + break; + case SyntaxKind.BindingElement: + if (lastLocation && lastLocation === (location as BindingElement).initializer) { + const root = getRootDeclaration(location); + if (root.kind === SyntaxKind.Parameter) { + associatedDeclarationForContainingInitializer = location as BindingElement; + } + } + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -1649,13 +1665,45 @@ namespace ts { if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(originalLocation!.flags & NodeFlags.JSDoc)) { const merged = getMergedSymbol(result); if (length(merged.declarations) && every(merged.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { - error(errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); // TODO: GH#18217 + errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); + } + } + + // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { + const candidate = getMergedSymbol(getLateBoundSymbol(result)); + const root = (getRootDeclaration(associatedDeclarationForContainingInitializer) as ParameterDeclaration); + // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { + error(errorLocation, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, declarationNameToString(associatedDeclarationForContainingInitializer.name)); + } + // And it cannot refer to any declarations which come after it + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializer.name), declarationNameToString(errorLocation)); } } } return result; } + function getIsDeferredContext(location: Node, lastLocation: Node | undefined): boolean { + if (location.kind !== SyntaxKind.ArrowFunction && location.kind !== SyntaxKind.FunctionExpression) { + // initializers in instance property declaration of class like entities are executed in constructor and thus deferred + return isTypeQueryNode(location) || (( + isFunctionLikeDeclaration(location) || + (location.kind === SyntaxKind.PropertyDeclaration && !hasModifier(location, ModifierFlags.Static)) + ) && (!lastLocation || lastLocation !== (location as FunctionLike | PropertyDeclaration).name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + } + if (lastLocation && lastLocation === (location as FunctionExpression | ArrowFunction).name) { + return false; + } + // generator functions and async functions are not inlined in control flow when immediately invoked + if ((location as FunctionExpression | ArrowFunction).asteriskToken || hasModifier(location, ModifierFlags.Async)) { + return true; + } + return !getImmediatelyInvokedFunctionExpression(location); + } + function isSelfReferenceLocation(node: Node): boolean { switch (node.kind) { case SyntaxKind.FunctionDeclaration: @@ -1967,7 +2015,21 @@ namespace ts { const file = find(moduleSymbol.declarations, isSourceFile); const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { - error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (hasExportAssignmentSymbol(moduleSymbol)) { + const compilerOptionName = moduleKind >= ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; + const exportEqualsSymbol = moduleSymbol.exports!.get(InternalSymbolName.ExportEquals); + const exportAssignment = exportEqualsSymbol!.valueDeclaration; + const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); + + addRelatedInfo(err, createDiagnosticForNode( + exportAssignment, + Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, + compilerOptionName + )); + } + else { + error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present @@ -2241,7 +2303,7 @@ namespace ts { const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(name) ? meaning & SymbolFlags.Value : 0); let symbol: Symbol | undefined; if (name.kind === SyntaxKind.Identifier) { - const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); const symbolFromJSPrototype = isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -3309,6 +3371,16 @@ namespace ts { return result; } + function getTypeNamesForErrorDisplay(left: Type, right: Type): [string, string] { + let leftStr = typeToString(left); + let rightStr = typeToString(right); + if (leftStr === rightStr) { + leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + } + return [leftStr, rightStr]; + } + function toNodeBuilderFlags(flags = TypeFormatFlags.None): NodeBuilderFlags { return flags & TypeFormatFlags.NodeBuilderFlagsMask; } @@ -3413,8 +3485,9 @@ namespace ts { return createLiteralTypeNode(setEmitFlags(createLiteral((type).value), EmitFlags.NoAsciiEscaping)); } if (type.flags & TypeFlags.NumberLiteral) { - context.approximateLength += (("" + (type).value).length); - return createLiteralTypeNode((createLiteral((type).value))); + const value = (type).value; + context.approximateLength += ("" + value).length; + return createLiteralTypeNode(value < 0 ? createPrefix(SyntaxKind.MinusToken, createLiteral(-value)) : createLiteral(value)); } if (type.flags & TypeFlags.BigIntLiteral) { context.approximateLength += (pseudoBigIntToString((type).value).length) + 1; @@ -11257,7 +11330,7 @@ namespace ts { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations ? + return couldContainTypeVariables(type) ? getAnonymousTypeInstantiation(type, mapper) : type; } if (objectFlags & ObjectFlags.Mapped) { @@ -11296,7 +11369,7 @@ namespace ts { } else { const sub = instantiateType((type).substitute, mapper); - if (sub.flags & TypeFlags.AnyOrUnknown || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + if (sub.flags & TypeFlags.AnyOrUnknown || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { return maybeVariable; } return sub; @@ -11702,6 +11775,10 @@ namespace ts { } } + function getSemanticJsxChildren(children: NodeArray) { + return filter(children, i => !isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces); + } + function elaborateJsxComponents(node: JsxAttributes, source: Type, target: Type, relation: Map) { let result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); let invalidTextDiagnostic: DiagnosticMessage | undefined; @@ -11711,7 +11788,7 @@ namespace ts { const childrenPropName = childPropName === undefined ? "children" : unescapeLeadingUnderscores(childPropName); const childrenNameType = getLiteralType(childrenPropName); const childrenTargetType = getIndexedAccessType(target, childrenNameType); - const validChildren = filter(containingElement.children, i => !isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces); + const validChildren = getSemanticJsxChildren(containingElement.children); if (!length(validChildren)) { return result; } @@ -11788,6 +11865,7 @@ namespace ts { } function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type, relation: Map) { + if (target.flags & TypeFlags.Primitive) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); } @@ -11824,6 +11902,7 @@ namespace ts { } function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type, relation: Map) { + if (target.flags & TypeFlags.Primitive) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } @@ -12240,12 +12319,7 @@ namespace ts { } function reportRelationError(message: DiagnosticMessage | undefined, source: Type, target: Type) { - let sourceType = typeToString(source); - let targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); - } + const [sourceType, targetType] = getTypeNamesForErrorDisplay(source, target); if (!message) { if (relation === comparableRelation) { @@ -13198,7 +13272,7 @@ namespace ts { } if (props.length === 1) { const propName = symbolToString(unmatchedProperty); - reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, typeToString(source), typeToString(target)); + reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, ...getTypeNamesForErrorDisplay(source, target)); if (length(unmatchedProperty.declarations)) { associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName)); } @@ -14573,7 +14647,7 @@ namespace ts { const objectFlags = getObjectFlags(type); return !!(type.flags & TypeFlags.Instantiable || objectFlags & ObjectFlags.Reference && forEach((type).typeArguments, couldContainTypeVariables) || - objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class) || + objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || objectFlags & ObjectFlags.Mapped || type.flags & TypeFlags.UnionOrIntersection && couldUnionOrIntersectionContainTypeVariables(type)); } @@ -15287,8 +15361,8 @@ namespace ts { // EXPRESSION TYPE CHECKING - function getCannotFindNameDiagnosticForName(name: __String): DiagnosticMessage { - switch (name) { + function getCannotFindNameDiagnosticForName(node: Identifier): DiagnosticMessage { + switch (node.escapedText) { case "document": case "console": return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; @@ -15319,7 +15393,13 @@ namespace ts { case "Iterator": case "AsyncIterator": return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; - default: return Diagnostics.Cannot_find_name_0; + default: + if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { + return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; + } + else { + return Diagnostics.Cannot_find_name_0; + } } } @@ -15331,7 +15411,7 @@ namespace ts { node, node.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue, - getCannotFindNameDiagnosticForName(node.escapedText), + getCannotFindNameDiagnosticForName(node), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ false, @@ -17080,7 +17160,7 @@ namespace ts { // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || + const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.AnyOrUnknown) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || @@ -18134,16 +18214,17 @@ namespace ts { if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return undefined; } - const childIndex = node.children.indexOf(child); + const realChildren = getSemanticJsxChildren(node.children); + const childIndex = realChildren.indexOf(child); const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); - return childFieldType && mapType(childFieldType, t => { + return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, t => { if (isArrayLikeType(t)) { return getIndexedAccessType(t, getLiteralType(childIndex)); } else { return t; } - }, /*noReductions*/ true); + }, /*noReductions*/ true)); } function getContextualTypeForJsxExpression(node: JsxExpression): Type | undefined { @@ -20459,7 +20540,7 @@ namespace ts { function getArrayifiedType(type: Type) { if (forEachType(type, t => !(t.flags & (TypeFlags.Any | TypeFlags.Instantiable) || isArrayType(t) || isTupleType(t)))) { - return createArrayType(getIndexTypeOfType(type, IndexKind.Number) || errorType); + return createArrayType(getIndexedAccessType(type, numberType)); } return type; } @@ -23311,12 +23392,6 @@ namespace ts { case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsEqualsToken: case SyntaxKind.ExclamationEqualsEqualsToken: - const leftIsLiteral = isLiteralType(leftType); - const rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23448,8 +23523,7 @@ namespace ts { } function reportOperatorError() { - const leftStr = typeToString(leftType); - const rightStr = typeToString(rightType); + const [leftStr, rightStr] = getTypeNamesForErrorDisplay(leftType, rightType); const errNode = errorNode || operatorToken; if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { error( @@ -26302,74 +26376,6 @@ namespace ts { } } - // Check that a parameter initializer contains no references to parameters declared to the right of itself - function checkParameterInitializer(node: HasExpressionInitializer): void { - if (getRootDeclaration(node).kind !== SyntaxKind.Parameter) { - return; - } - - const func = getContainingFunction(node); - visit(node.initializer!); - - function visit(n: Node): void { - if (isTypeNode(n) || isDeclarationName(n)) { - // do not dive in types - // skip declaration names (i.e. in object literal expressions) - return; - } - if (n.kind === SyntaxKind.PropertyAccessExpression) { - // skip property names in property access expression - return visit((n).expression); - } - else if (n.kind === SyntaxKind.Identifier) { - // check FunctionLikeDeclaration.locals (stores parameters\function local variable) - // if it contains entry with a specified name - const symbol = resolveName(n, (n).escapedText, SymbolFlags.Value | SymbolFlags.Alias, /*nameNotFoundMessage*/undefined, /*nameArg*/undefined, /*isUse*/ false); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, declarationNameToString(node.name)); - return; - } - // locals map for function contain both parameters and function locals - // so we need to do a bit of extra work to check if reference is legal - const enclosingContainer = getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === SyntaxKind.Parameter || - symbol.valueDeclaration.kind === SyntaxKind.BindingElement) { - // it is ok to reference parameter in initializer if either - // - parameter is located strictly on the left of current parameter declaration - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - // - parameter is wrapped in function-like entity - if (findAncestor( - n, - current => { - if (current === node.initializer) { - return "quit"; - } - return isFunctionLike(current.parent) || - // computed property names/initializers in instance property declaration of class like entities - // are executed in constructor and thus deferred - (current.parent.kind === SyntaxKind.PropertyDeclaration && - !(hasModifier(current.parent, ModifierFlags.Static)) && - isClassLike(current.parent.parent)); - })) { - return; - } - // fall through to report error - } - error(n, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(node.name), declarationNameToString(n)); - } - } - else { - return forEachChild(n, visit); - } - } - } - function convertAutoToAny(type: Type) { return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; } @@ -26446,7 +26452,6 @@ namespace ts { else { checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); } - checkParameterInitializer(node); } return; } @@ -26463,7 +26468,6 @@ namespace ts { hasEntries(symbol.exports); if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); - checkParameterInitializer(node); } } if (symbol.declarations.length > 1) { @@ -31017,7 +31021,7 @@ namespace ts { Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, getTextOfNode(parameter.name), typeToString(type), - typeToString(getTypeFromTypeNode(node.type!))); + typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } if (type.flags & TypeFlags.Union && allTypesAssignableToKind(type, TypeFlags.StringLiteral, /*strict*/ true)) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index edb25e9cb717a..e1a8d77b7675a 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -588,6 +588,13 @@ namespace ts { category: Diagnostics.Module_Resolution_Options, description: Diagnostics.Do_not_resolve_the_real_path_of_symlinks, }, + { + name: "allowUmdGlobalAccess", + type: "boolean", + affectsSemanticDiagnostics: true, + category: Diagnostics.Module_Resolution_Options, + description: Diagnostics.Allow_accessing_UMD_globals_from_modules, + }, // Source Maps { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 52fb34565f885..a78e89f42beb3 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -851,6 +851,10 @@ "category": "Error", "code": 1258 }, + "Module '{0}' can only be default-imported using the '{1}' flag": { + "category": "Error", + "code": 1259 + }, "'with' statements are not allowed in an async function block.": { "category": "Error", "code": 1300 @@ -2156,6 +2160,10 @@ "category": "Error", "code": 2593 }, + "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag.": { + "category": "Error", + "code": 2594 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 @@ -4911,14 +4919,6 @@ "category": "Message", "code": 95066 }, - "Generate types for '{0}'": { - "category": "Message", - "code": 95067 - }, - "Generate types for all packages without types": { - "category": "Message", - "code": 95068 - }, "Add 'unknown' conversion for non-overlapping types": { "category": "Message", "code": 95069 @@ -4946,5 +4946,13 @@ "Convert parameters to destructured object": { "category": "Message", "code": 95075 + }, + "Allow accessing UMD globals from modules.": { + "category": "Message", + "code": 95076 + }, + "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer." :{ + "category": "Error", + "code": 18004 } } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 5f4299f1e2021..3742f2d5fdf11 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -845,7 +845,7 @@ namespace ts { const node = createSynthesizedNode(SyntaxKind.ImportType); node.argument = argument; node.qualifier = qualifier; - node.typeArguments = asNodeArray(typeArguments); + node.typeArguments = parenthesizeTypeParameters(typeArguments); node.isTypeOf = isTypeOf; return node; } diff --git a/src/compiler/inspectValue.ts b/src/compiler/inspectValue.ts deleted file mode 100644 index fab4a57ef1bab..0000000000000 --- a/src/compiler/inspectValue.ts +++ /dev/null @@ -1,162 +0,0 @@ -/* @internal */ -namespace ts { - export interface InspectValueOptions { - readonly fileNameToRequire: string; - } - - export const enum ValueKind { Const, Array, FunctionOrClass, Object } - export interface ValueInfoBase { - readonly name: string; - } - export type ValueInfo = ValueInfoSimple | ValueInfoArray | ValueInfoFunctionOrClass | ValueInfoObject; - export interface ValueInfoSimple extends ValueInfoBase { - readonly kind: ValueKind.Const; - readonly typeName: string; - readonly comment?: string | undefined; - } - export interface ValueInfoFunctionOrClass extends ValueInfoBase { - readonly kind: ValueKind.FunctionOrClass; - readonly source: string | number; // For a native function, this is the length. - readonly prototypeMembers: ReadonlyArray; - readonly namespaceMembers: ReadonlyArray; - } - export interface ValueInfoArray extends ValueInfoBase { - readonly kind: ValueKind.Array; - readonly inner: ValueInfo; - } - export interface ValueInfoObject extends ValueInfoBase { - readonly kind: ValueKind.Object; - readonly hasNontrivialPrototype: boolean; - readonly members: ReadonlyArray; - } - - export function inspectModule(fileNameToRequire: string): ValueInfo { - return inspectValue(removeFileExtension(getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); - } - - export function inspectValue(name: string, value: unknown): ValueInfo { - return getValueInfo(name, value, getRecurser()); - } - - type Recurser = (obj: unknown, name: string, cbOk: () => T, cbFail: (isCircularReference: boolean, keyStack: ReadonlyArray) => T) => T; - function getRecurser(): Recurser { - const seen: unknown[] = []; - const nameStack: string[] = []; - return (obj, name, cbOk, cbFail) => { - if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { - return cbFail(seen.indexOf(obj) !== -1, nameStack); - } - - seen.push(obj); - nameStack.push(name); - const res = cbOk(); - nameStack.pop(); - seen.pop(); - return res; - }; - } - - function getValueInfo(name: string, value: unknown, recurser: Recurser): ValueInfo { - return recurser(value, name, - (): ValueInfo => { - if (typeof value === "function") return getFunctionOrClassInfo(value as AnyFunction, name, recurser); - if (typeof value === "object") { - const builtin = getBuiltinType(name, value as object, recurser); - if (builtin !== undefined) return builtin; - const entries = getEntriesOfObject(value as object); - const hasNontrivialPrototype = Object.getPrototypeOf(value) !== Object.prototype; - const members = flatMap(entries, ({ key, value }) => getValueInfo(key, value, recurser)); - return { kind: ValueKind.Object, name, hasNontrivialPrototype, members }; - } - return { kind: ValueKind.Const, name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; - }, - (isCircularReference, keyStack) => anyValue(name, ` ${isCircularReference ? "Circular reference" : "Too-deep object hierarchy"} from ${keyStack.join(".")}`)); - } - - function getFunctionOrClassInfo(fn: AnyFunction, name: string, recurser: Recurser): ValueInfoFunctionOrClass { - const prototypeMembers = getPrototypeMembers(fn, recurser); - const namespaceMembers = flatMap(getEntriesOfObject(fn), ({ key, value }) => getValueInfo(key, value, recurser)); - const toString = cast(Function.prototype.toString.call(fn), isString); - const source = stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; - return { kind: ValueKind.FunctionOrClass, name, source, namespaceMembers, prototypeMembers }; - } - - const builtins: () => ReadonlyMap = memoize(() => { - const map = createMap(); - for (const { key, value } of getEntriesOfObject(global)) { - if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { - map.set(key, value as AnyConstructor); - } - } - return map; - }); - function getBuiltinType(name: string, value: object, recurser: Recurser): ValueInfo | undefined { - return isArray(value) - ? { name, kind: ValueKind.Array, inner: value.length && getValueInfo("element", first(value), recurser) || anyValue(name) } - : forEachEntry(builtins(), (builtin, builtinName): ValueInfo | undefined => - value instanceof builtin ? { kind: ValueKind.Const, name, typeName: builtinName } : undefined); - } - - function getPrototypeMembers(fn: AnyFunction, recurser: Recurser): ReadonlyArray { - const prototype = fn.prototype as unknown; - // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) - return typeof prototype !== "object" || prototype === null ? emptyArray : mapDefined(getEntriesOfObject(prototype as object), ({ key, value }) => - key === "constructor" ? undefined : getValueInfo(key, value, recurser)); - } - - const ignoredProperties: ReadonlyArray = ["arguments", "caller", "constructor", "eval", "super_"]; - const reservedFunctionProperties: ReadonlyArray = Object.getOwnPropertyNames(noop); - interface ObjectEntry { readonly key: string; readonly value: unknown; } - function getEntriesOfObject(obj: object): ReadonlyArray { - const seen = createMap(); - const entries: ObjectEntry[] = []; - let chain = obj; - while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { - for (const key of Object.getOwnPropertyNames(chain)) { - if (!isJsPrivate(key) && - ignoredProperties.indexOf(key) === -1 && - (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && - // Don't add property from a higher prototype if it already exists in a lower one - addToSeen(seen, key)) { - const value = safeGetPropertyOfObject(chain, key); - // Don't repeat "toString" that matches signature from Object.prototype - if (!(key === "toString" && typeof value === "function" && value.length === 0)) { - entries.push({ key, value }); - } - } - } - chain = Object.getPrototypeOf(chain); - } - return entries.sort((e1, e2) => compareStringsCaseSensitive(e1.key, e2.key)); - } - - function getFunctionLength(fn: AnyFunction): number { - return tryCast(safeGetPropertyOfObject(fn, "length"), isNumber) || 0; - } - - function safeGetPropertyOfObject(obj: object, key: string): unknown { - const desc = Object.getOwnPropertyDescriptor(obj, key); - return desc && desc.value; - } - - function isNullOrUndefined(value: unknown): value is null | undefined { - return value == null; // tslint:disable-line - } - - function anyValue(name: string, comment?: string): ValueInfo { - return { kind: ValueKind.Const, name, typeName: "any", comment }; - } - - export function isJsPrivate(name: string): boolean { - return startsWith(name, "_"); - } - - function tryRequire(fileNameToRequire: string): unknown { - try { - return require(fileNameToRequire); - } - catch { - return undefined; - } - } -} diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index ada4288903271..481a601118edb 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2922,7 +2922,9 @@ namespace ts { if (parseOptional(SyntaxKind.DotToken)) { node.qualifier = parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected); } - node.typeArguments = tryParseTypeArguments(); + if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === SyntaxKind.LessThanToken) { + node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); + } return finishNode(node); } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 15d7cb6ff5fa5..20aac7d4936e5 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -63,7 +63,7 @@ namespace ts { let enclosingDeclaration: Node; let necessaryTypeReferences: Map | undefined; let lateMarkedStatements: LateVisibilityPaintedStatement[] | undefined; - let lateStatementReplacementMap: Map>; + let lateStatementReplacementMap: Map>; let suppressNewDiagnosticContexts: boolean; let exportedModulesFromDeclarationEmit: Symbol[] | undefined; @@ -701,12 +701,12 @@ namespace ts { } } - function isExternalModuleIndicator(result: LateVisibilityPaintedStatement) { + function isExternalModuleIndicator(result: LateVisibilityPaintedStatement | ExportAssignment) { // Exported top-level member indicates moduleness return isAnyImportOrReExport(result) || isExportAssignment(result) || hasModifier(result, ModifierFlags.Export); } - function needsScopeMarker(result: LateVisibilityPaintedStatement) { + function needsScopeMarker(result: LateVisibilityPaintedStatement | ExportAssignment) { return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasModifier(result, ModifierFlags.Export) && !isAmbientModule(result); } @@ -1047,7 +1047,43 @@ namespace ts { return createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList([varDecl])); }); const namespaceDecl = createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name!, createModuleBlock(declarations), NodeFlags.Namespace); - return [clean, namespaceDecl]; + + if (!hasModifier(clean, ModifierFlags.ExportDefault)) { + return [clean, namespaceDecl]; + } + + const modifiers = createModifiersFromModifierFlags((getModifierFlags(clean) & ~ModifierFlags.ExportDefault) | ModifierFlags.Ambient); + const cleanDeclaration = updateFunctionDeclaration( + clean, + /*decorators*/ undefined, + modifiers, + /*asteriskToken*/ undefined, + clean.name, + clean.typeParameters, + clean.parameters, + clean.type, + /*body*/ undefined + ); + + const namespaceDeclaration = updateModuleDeclaration( + namespaceDecl, + /*decorators*/ undefined, + modifiers, + namespaceDecl.name, + namespaceDecl.body + ); + + const exportDefaultDeclaration = createExportAssignment( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*isExportEquals*/ false, + namespaceDecl.name + ); + + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + + return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration]; } else { return clean; diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 84bedb34b7cee..18934aa9bb1cd 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -53,6 +53,5 @@ "moduleSpecifiers.ts", "watch.ts", "tsbuild.ts", - "inspectValue.ts", ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index b875210f8e703..4484d047daea1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -946,7 +946,7 @@ namespace ts { } export interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } @@ -4590,6 +4590,7 @@ namespace ts { allowJs?: boolean; /*@internal*/ allowNonTsExtensions?: boolean; allowSyntheticDefaultImports?: boolean; + allowUmdGlobalAccess?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; alwaysStrict?: boolean; // Always combine with strict property diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 0d4d0d9482d6a..0cb3b2691057e 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -268,7 +268,8 @@ namespace ts { nodesVisitor((node).decorators, visitor, isDecorator), nodesVisitor((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), - visitNode((node).questionToken, tokenVisitor, isToken), + // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too + visitNode((node).questionToken || (node).exclamationToken, tokenVisitor, isToken), visitNode((node).type, visitor, isTypeNode), visitNode((node).initializer, visitor, isExpression)); diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 9e117cdfd8fe9..e8c2912365f56 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3068,19 +3068,6 @@ Actual: ${stringify(fullActual)}`); return this.languageService.getApplicableRefactors(fileName, positionOrRange, preferences) || ts.emptyArray; } - public generateTypes(examples: ReadonlyArray): void { - for (const { name = "example", value, global, output, outputBaseline } of examples) { - const actual = (global ? ts.generateTypesForGlobal : ts.generateTypesForModule)(name, value, this.formatCodeSettings); - if (outputBaseline) { - if (actual === undefined) throw ts.Debug.fail(); - Harness.Baseline.runBaseline(ts.combinePaths("generateTypes", outputBaseline + ts.Extension.Dts), actual); - } - else { - assert.equal(actual, output, `generateTypes output for ${name} does not match`); - } - } - } - public configurePlugin(pluginName: string, configuration: any): void { (this.languageService).configurePlugin(pluginName, configuration); } @@ -4140,19 +4127,6 @@ namespace FourSlashInterface { public noMoveToNewFile(): void { this.state.noMoveToNewFile(); } - - public generateTypes(...options: GenerateTypesOptions[]): void { - this.state.generateTypes(options); - } - } - - export interface GenerateTypesOptions { - readonly name?: string; - readonly value: unknown; - readonly global?: boolean; - // Exactly one of these should be set: - readonly output?: string; - readonly outputBaseline?: string; } export class Edit { diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index c1624527cf3fb..b5b3286253b55 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -4,7 +4,6 @@ namespace ts.server { export const ActionSet: ActionSet = "action::set"; export const ActionInvalidate: ActionInvalidate = "action::invalidate"; export const ActionPackageInstalled: ActionPackageInstalled = "action::packageInstalled"; - export const ActionValueInspected: ActionValueInspected = "action::valueInspected"; export const EventTypesRegistry: EventTypesRegistry = "event::typesRegistry"; export const EventBeginInstallTypes: EventBeginInstallTypes = "event::beginInstallTypes"; export const EventEndInstallTypes: EventEndInstallTypes = "event::endInstallTypes"; diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index 6bc3e667f8766..f9e2a38fea7ee 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -2,14 +2,13 @@ declare namespace ts.server { export type ActionSet = "action::set"; export type ActionInvalidate = "action::invalidate"; export type ActionPackageInstalled = "action::packageInstalled"; - export type ActionValueInspected = "action::valueInspected"; export type EventTypesRegistry = "event::typesRegistry"; export type EventBeginInstallTypes = "event::beginInstallTypes"; export type EventEndInstallTypes = "event::endInstallTypes"; export type EventInitializationFailed = "event::initializationFailed"; export interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } export interface TypingInstallerRequestWithProjectName { @@ -17,7 +16,7 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest | InspectValueRequest; + export type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest; export interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; @@ -44,12 +43,6 @@ declare namespace ts.server { readonly projectRootPath: Path; } - /* @internal */ - export interface InspectValueRequest { - readonly kind: "inspectValue"; - readonly options: InspectValueOptions; - } - /* @internal */ export interface TypesRegistryResponse extends TypingInstallerResponse { readonly kind: EventTypesRegistry; @@ -62,12 +55,6 @@ declare namespace ts.server { readonly message: string; } - /* @internal */ - export interface InspectValueResponse { - readonly kind: ActionValueInspected; - readonly result: ValueInfo; - } - export interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; @@ -115,5 +102,5 @@ declare namespace ts.server { } /* @internal */ - export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | InstallTypes | InitializationFailedResponse; + export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InstallTypes | InitializationFailedResponse; } diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index cfb300c784d74..ccada2e0069c9 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -298,6 +298,12 @@ interface ObjectConstructor { */ getOwnPropertySymbols(o: any): symbol[]; + /** + * Returns the names of the enumerable string properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: {}): string[]; + /** * Returns true if the values are the same value, false otherwise. * @param value1 The first value. diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index b679bea14d572..faba45bc51895 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -177,7 +177,7 @@ interface ReadonlySet { } interface SetConstructor { - new (iterable: Iterable): Set; + new (iterable?: Iterable | null): Set; } interface WeakSet { } diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 79fd72ac9375c..de4a612d3919f 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -235,10 +235,10 @@ interface ObjectConstructor { isExtensible(o: any): boolean; /** - * Returns the names of the enumerable properties and methods of an object. + * Returns the names of the enumerable string properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - keys(o: {}): string[]; + keys(o: object): string[]; } /** diff --git a/src/server/project.ts b/src/server/project.ts index 515340c94cc4c..c204facad5ca1 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -277,10 +277,6 @@ namespace ts.server { installPackage(options: InstallPackageOptions): Promise { return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); } - /* @internal */ - inspectValue(options: InspectValueOptions): Promise { - return this.typingsCache.inspectValue(options); - } private get typingsCache(): TypingsCache { return this.projectService.typingsCache; diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index d3b6e21a21c94..8f3cb7607b0b4 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -8,8 +8,6 @@ namespace ts.server { export interface ITypingsInstaller { isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptionsWithProject): Promise; - /* @internal */ - inspectValue(options: InspectValueOptions): Promise; enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; @@ -20,7 +18,6 @@ namespace ts.server { isKnownTypesPackageName: returnFalse, // Should never be called because we never provide a types registry. installPackage: notImplemented, - inspectValue: notImplemented, enqueueInstallTypingsRequest: noop, attach: noop, onProjectClosed: noop, @@ -98,10 +95,6 @@ namespace ts.server { return this.installer.installPackage(options); } - inspectValue(options: InspectValueOptions): Promise { - return this.installer.inspectValue(options); - } - enqueueInstallTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray | undefined, forceRefresh: boolean) { const typeAcquisition = project.getTypeAcquisition(); diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index aae1d205de3d2..3842c30d6aae3 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -14,7 +14,22 @@ namespace ts.codefix { getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context)), }); + const enum SynthBindingNameKind { + Identifier, + BindingPattern, + } + + type SynthBindingName = SynthBindingPattern | SynthIdentifier; + + interface SynthBindingPattern { + readonly kind: SynthBindingNameKind.BindingPattern; + readonly elements: ReadonlyArray; + readonly bindingPattern: BindingPattern; + readonly types: Type[]; + } + interface SynthIdentifier { + readonly kind: SynthBindingNameKind.Identifier; readonly identifier: Identifier; readonly types: Type[]; numberOfAssignmentsOriginal: number; // number of times the variable should be assigned in the refactor @@ -188,8 +203,8 @@ namespace ts.codefix { allVarNames.push({ identifier: synthName.identifier, symbol }); addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } - // we only care about identifiers that are parameters and declarations (don't care about other uses) - else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { + // we only care about identifiers that are parameters, declarations, or binding elements (don't care about other uses) + else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) { const originalName = node.text; const collidingSymbols = collidingSymbolMap.get(originalName); @@ -204,7 +219,7 @@ namespace ts.codefix { else { const identifier = getSynthesizedDeepClone(node); identsToRenameMap.set(symbolIdString, identifier); - synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); + synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier, [], allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/)); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { allVarNames.push({ identifier, symbol }); addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); @@ -261,12 +276,12 @@ namespace ts.codefix { const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); - return { identifier, types: [], numberOfAssignmentsOriginal }; + return createSynthIdentifier(identifier, [], numberOfAssignmentsOriginal); } // dispatch function to recursively build the refactoring // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts - function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { + function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): ReadonlyArray { if (!node) { return emptyArray; } @@ -291,10 +306,11 @@ namespace ts.codefix { return emptyArray; } - function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { + function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthBindingName): ReadonlyArray { const func = node.arguments[0]; - const argName = getArgName(func, transformer); + const argName = getArgBindingName(func, transformer); const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); + let possibleNameForVarDecl: SynthIdentifier | undefined; /* If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) @@ -302,67 +318,86 @@ namespace ts.codefix { We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step */ if (prevArgName && !shouldReturn) { - prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block - transformer.synthNamesMap.forEach((val, key) => { - if (val.identifier.text === prevArgName.identifier.text) { - const newSynthName = createUniqueSynthName(prevArgName); - transformer.synthNamesMap.set(key, newSynthName); - } - }); + if (isSynthIdentifier(prevArgName)) { + possibleNameForVarDecl = prevArgName; + transformer.synthNamesMap.forEach((val, key) => { + if (val.identifier.text === prevArgName.identifier.text) { + const newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); + } + }); + } + else { + possibleNameForVarDecl = createSynthIdentifier(createOptimisticUniqueName("result"), prevArgName.types); + } + possibleNameForVarDecl.numberOfAssignmentsOriginal = 2; // Try block and catch block // update the constIdentifiers list - if (transformer.constIdentifiers.some(elem => elem.text === prevArgName.identifier.text)) { - transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); + if (transformer.constIdentifiers.some(elem => elem.text === possibleNameForVarDecl!.identifier.text)) { + transformer.constIdentifiers.push(createUniqueSynthName(possibleNameForVarDecl).identifier); } } - const tryBlock = createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + const tryBlock = createBlock(transformExpression(node.expression, transformer, node, possibleNameForVarDecl)); - const transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - const catchArg = argName ? argName.identifier.text : "e"; - const catchClause = createCatchClause(catchArg, createBlock(transformationBody)); + const transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer); + const catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e"; + const catchVariableDeclaration = createVariableDeclaration(catchArg); + const catchClause = createCatchClause(catchVariableDeclaration, createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) */ - let varDeclList; - if (prevArgName && !shouldReturn) { - const typeArray: Type[] = prevArgName.types; + let varDeclList: VariableStatement | undefined; + let varDeclIdentifier: Identifier | undefined; + if (possibleNameForVarDecl && !shouldReturn) { + varDeclIdentifier = getSynthesizedDeepClone(possibleNameForVarDecl.identifier); + const typeArray: Type[] = possibleNameForVarDecl.types; const unionType = transformer.checker.getUnionType(typeArray, UnionReduction.Subtype); const unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); - const varDecl = [createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + const varDecl = [createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList(varDecl, NodeFlags.Let)); } const tryStatement = createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); - return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + const destructuredResult = prevArgName && varDeclIdentifier && isSynthBindingPattern(prevArgName) + && createVariableStatement(/* modifiers */ undefined, createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepCloneWithRenames(prevArgName.bindingPattern), /* type */ undefined, varDeclIdentifier)], NodeFlags.Const)); + return compact([varDeclList, tryStatement, destructuredResult]); } - function createUniqueSynthName(prevArgName: SynthIdentifier) { + function getIdentifierTextsFromBindingName(bindingName: BindingName): ReadonlyArray { + if (isIdentifier(bindingName)) return [bindingName.text]; + return flatMap(bindingName.elements, element => { + if (isOmittedExpression(element)) return []; + return getIdentifierTextsFromBindingName(element.name); + }); + } + + function createUniqueSynthName(prevArgName: SynthIdentifier): SynthIdentifier { const renamedPrevArg = createOptimisticUniqueName(prevArgName.identifier.text); - const newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; - return newSynthName; + return createSynthIdentifier(renamedPrevArg); } - function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): ReadonlyArray { + function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): ReadonlyArray { const [res, rej] = node.arguments; if (!res) { return transformExpression(node.expression, transformer, outermostParent); } - const argNameRes = getArgName(res, transformer); + const argNameRes = getArgBindingName(res, transformer); const transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); if (rej) { - const argNameRej = getArgName(rej, transformer); + const argNameRej = getArgBindingName(rej, transformer); const tryBlock = createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); const transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - const catchArg = argNameRej ? argNameRej.identifier.text : "e"; - const catchClause = createCatchClause(catchArg, createBlock(transformationBody2)); + const catchArg = argNameRej ? isSynthIdentifier(argNameRej) ? argNameRej.identifier.text : argNameRej.bindingPattern : "e"; + const catchVariableDeclaration = createVariableDeclaration(catchArg); + const catchClause = createCatchClause(catchVariableDeclaration, createBlock(transformationBody2)); return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } @@ -370,12 +405,13 @@ namespace ts.codefix { return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } - function getFlagOfIdentifier(node: Identifier, constIdentifiers: ReadonlyArray): NodeFlags { - const inArr: boolean = constIdentifiers.some(elem => elem.text === node.text); + function getFlagOfBindingName(bindingName: SynthBindingName, constIdentifiers: ReadonlyArray): NodeFlags { + const identifiers = getIdentifierTextsFromBindingName(getNode(bindingName)); + const inArr: boolean = constIdentifiers.some(elem => contains(identifiers, elem.text)); return inArr ? NodeFlags.Const : NodeFlags.Let; } - function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthIdentifier): ReadonlyArray { + function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthBindingName): ReadonlyArray { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call const originalNodeParent = node.original ? node.original.parent : node.parent; @@ -389,23 +425,23 @@ namespace ts.codefix { return [createReturn(getSynthesizedDeepClone(node))]; } - function createTransformedStatement(prevArgName: SynthIdentifier | undefined, rightHandSide: Expression, transformer: Transformer): ReadonlyArray { - if (!prevArgName || prevArgName.identifier.text.length === 0) { + function createTransformedStatement(prevArgName: SynthBindingName | undefined, rightHandSide: Expression, transformer: Transformer): ReadonlyArray { + if (!prevArgName || isEmpty(prevArgName)) { // if there's no argName to assign to, there still might be side effects return [createStatement(rightHandSide)]; } - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + if (isSynthIdentifier(prevArgName) && prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { // if the variable has already been declared, we don't need "let" or "const" return [createStatement(createAssignment(getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; } return [createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; + (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(getNode(prevArgName)), /*type*/ undefined, rightHandSide)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))]; } // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts - function getTransformationBody(func: Expression, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier | undefined, parent: CallExpression, transformer: Transformer): ReadonlyArray { + function getTransformationBody(func: Expression, prevArgName: SynthBindingName | undefined, argName: SynthBindingName | undefined, parent: CallExpression, transformer: Transformer): ReadonlyArray { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { @@ -418,7 +454,7 @@ namespace ts.codefix { break; } - const synthCall = createCall(getSynthesizedDeepClone(func as Identifier), /*typeArguments*/ undefined, [argName.identifier]); + const synthCall = createCall(getSynthesizedDeepClone(func as Identifier), /*typeArguments*/ undefined, isSynthIdentifier(argName) ? [argName.identifier] : []); if (shouldReturn) { return [createReturn(synthCall)]; } @@ -461,7 +497,7 @@ namespace ts.codefix { return shouldReturn ? refactoredStmts.map(s => getSynthesizedDeepClone(s)) : removeReturns( refactoredStmts, - prevArgName === undefined ? undefined : prevArgName.identifier, + prevArgName, transformer, seenReturnStatement); } @@ -503,7 +539,7 @@ namespace ts.codefix { } - function removeReturns(stmts: ReadonlyArray, prevArgName: Identifier | undefined, transformer: Transformer, seenReturnStatement: boolean): ReadonlyArray { + function removeReturns(stmts: ReadonlyArray, prevArgName: SynthBindingName | undefined, transformer: Transformer, seenReturnStatement: boolean): ReadonlyArray { const ret: Statement[] = []; for (const stmt of stmts) { if (isReturnStatement(stmt)) { @@ -514,7 +550,7 @@ namespace ts.codefix { } else { ret.push(createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + (createVariableDeclarationList([createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))); } } } @@ -526,14 +562,14 @@ namespace ts.codefix { // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables if (!seenReturnStatement && prevArgName !== undefined) { ret.push(createVariableStatement(/*modifiers*/ undefined, - (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + (createVariableDeclarationList([createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, createIdentifier("undefined"))], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))); } return ret; } - function getInnerTransformationBody(transformer: Transformer, innerRetStmts: ReadonlyArray, prevArgName?: SynthIdentifier) { + function getInnerTransformationBody(transformer: Transformer, innerRetStmts: ReadonlyArray, prevArgName?: SynthBindingName) { let innerCbBody: Statement[] = []; for (const stmt of innerRetStmts) { @@ -553,17 +589,17 @@ namespace ts.codefix { return innerCbBody; } - function getArgName(funcNode: Expression, transformer: Transformer): SynthIdentifier | undefined { + function getArgBindingName(funcNode: Expression, transformer: Transformer): SynthBindingName | undefined { const numberOfAssignmentsOriginal = 0; const types: Type[] = []; - let name: SynthIdentifier | undefined; + let name: SynthBindingName | undefined; if (isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { - const param = funcNode.parameters[0].name as Identifier; - name = getMapEntryOrDefault(param); + const param = funcNode.parameters[0].name; + name = getMappedBindingNameOrDefault(param); } } else if (isIdentifier(funcNode)) { @@ -571,22 +607,32 @@ namespace ts.codefix { } // return undefined argName when arg is null or undefined - if (!name || name.identifier.text === "undefined") { + if (!name || "identifier" in name && name.identifier.text === "undefined") { return undefined; } return name; + function getMappedBindingNameOrDefault(bindingName: BindingName): SynthBindingName { + if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName); + const elements = flatMap(bindingName.elements, element => { + if (isOmittedExpression(element)) return []; + return [getMappedBindingNameOrDefault(element.name)]; + }); + + return createSynthBindingPattern(bindingName, elements); + } + function getMapEntryOrDefault(identifier: Identifier): SynthIdentifier { const originalNode = getOriginalNode(identifier); const symbol = getSymbol(originalNode); if (!symbol) { - return { identifier, types, numberOfAssignmentsOriginal }; + return createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal); } const mapEntry = transformer.synthNamesMap.get(getSymbolId(symbol).toString()); - return mapEntry || { identifier, types, numberOfAssignmentsOriginal }; + return mapEntry || createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal); } function getSymbol(node: Node): Symbol | undefined { @@ -597,4 +643,34 @@ namespace ts.codefix { return node.original ? node.original : node; } } + + function isEmpty(bindingName: SynthBindingName | undefined): boolean { + if (!bindingName) { + return true; + } + if (isSynthIdentifier(bindingName)) { + return !bindingName.identifier.text; + } + return every(bindingName.elements, isEmpty); + } + + function getNode(bindingName: SynthBindingName) { + return isSynthIdentifier(bindingName) ? bindingName.identifier : bindingName.bindingPattern; + } + + function createSynthIdentifier(identifier: Identifier, types: Type[] = [], numberOfAssignmentsOriginal = 0): SynthIdentifier { + return { kind: SynthBindingNameKind.Identifier, identifier, types, numberOfAssignmentsOriginal }; + } + + function createSynthBindingPattern(bindingPattern: BindingPattern, elements: ReadonlyArray = emptyArray, types: Type[] = []): SynthBindingPattern { + return { kind: SynthBindingNameKind.BindingPattern, bindingPattern, elements, types }; + } + + function isSynthIdentifier(bindingName: SynthBindingName): bindingName is SynthIdentifier { + return bindingName.kind === SynthBindingNameKind.Identifier; + } + + function isSynthBindingPattern(bindingName: SynthBindingName): bindingName is SynthBindingPattern { + return bindingName.kind === SynthBindingNameKind.BindingPattern; + } } diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 1baaa9714f241..77393f0072ccb 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -2,7 +2,6 @@ namespace ts.codefix { const fixName = "fixCannotFindModule"; const fixIdInstallTypesPackage = "installTypesPackage"; - const fixIdGenerateTypes = "generateTypes"; const errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0.code; const errorCodes = [ @@ -17,13 +16,12 @@ namespace ts.codefix { if (packageName === undefined) return undefined; const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); return typesPackageName === undefined - ? singleElementArray(tryGetGenerateTypesAction(context, packageName)) + ? [] : [createCodeFixAction(fixName, /*changes*/ [], [Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; }, - fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + fixIds: [fixIdInstallTypesPackage], getAllCodeActions: context => { - let savedTypesDir: string | null | undefined = null; // tslint:disable-line no-null-keyword - return codeFixAll(context, errorCodes, (changes, diag, commands) => { + return codeFixAll(context, errorCodes, (_changes, diag, commands) => { const packageName = tryGetImportedPackageName(diag.file, diag.start); if (packageName === undefined) return undefined; switch (context.fixId) { @@ -34,12 +32,6 @@ namespace ts.codefix { } break; } - case fixIdGenerateTypes: { - const typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); - const command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); - if (command) commands.push(command); - break; - } default: Debug.fail(`Bad fixId: ${context.fixId}`); } @@ -47,88 +39,6 @@ namespace ts.codefix { }, }); - function tryGetGenerateTypesAction(context: CodeFixContextBase, packageName: string): CodeFixAction | undefined { - let command: GenerateTypesAction | undefined; - const changes = textChanges.ChangeTracker.with(context, t => { - const typesDir = getOrCreateTypesDirectory(t, context); - command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); - }); - return command && createCodeFixAction(fixName, changes, [Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, Diagnostics.Generate_types_for_all_packages_without_types, command); - } - - function tryGenerateTypes(typesDir: string, packageName: string, context: CodeFixContextBase): GenerateTypesAction | undefined { - const file = context.sourceFile.fileName; - const fileToGenerateTypesFor = tryResolveJSModule(packageName, getDirectoryPath(file), context.host as ModuleResolutionHost); // TODO: GH#18217 - if (fileToGenerateTypesFor === undefined) return undefined; - - const outputFileName = resolvePath(getDirectoryPath(context.program.getCompilerOptions().configFile!.fileName), typesDir, packageName + ".d.ts"); - if (context.host.fileExists!(outputFileName)) return undefined; - return { type: "generate types", file, fileToGenerateTypesFor, outputFileName }; - } - - // If no types directory exists yet, adds it to tsconfig.json - function getOrCreateTypesDirectory(changes: textChanges.ChangeTracker, context: CodeFixContextBase): string | undefined { - const { configFile } = context.program.getCompilerOptions(); - if (!configFile) return undefined; - - const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); - if (!tsconfigObjectLiteral) return undefined; - - const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); - if (!compilerOptionsProperty) { - const newCompilerOptions = createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); - changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); - return defaultTypesDirectoryName; - } - - const compilerOptions = compilerOptionsProperty.initializer; - if (!isObjectLiteralExpression(compilerOptions)) return defaultTypesDirectoryName; - - const baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); - const typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); - return combinePaths(baseUrl, typesDirectoryFromPathMapping); - } - - const defaultBaseUrl = "."; - function makeDefaultBaseUrl(): PropertyAssignment { - return createJsonPropertyAssignment("baseUrl", createStringLiteral(defaultBaseUrl)); - } - function getOrAddBaseUrl(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression): string { - const baseUrlProp = findJsonProperty(compilerOptions, "baseUrl"); - if (baseUrlProp) { - return isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; - } - else { - changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); - return defaultBaseUrl; - } - } - - const defaultTypesDirectoryName = "types"; - function makeDefaultPathMapping(): PropertyAssignment { - return createJsonPropertyAssignment("*", createArrayLiteral([createStringLiteral(`${defaultTypesDirectoryName}/*`)])); - } - function makeDefaultPaths(): PropertyAssignment { - return createJsonPropertyAssignment("paths", createObjectLiteral([makeDefaultPathMapping()])); - } - function getOrAddPathMapping(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression) { - const paths = findJsonProperty(compilerOptions, "paths"); - if (!paths || !isObjectLiteralExpression(paths.initializer)) { - changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); - return defaultTypesDirectoryName; - } - - // Look for an existing path mapping. Should look like `"*": "foo/*"`. - const existing = firstDefined(paths.initializer.properties, prop => - isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "*" && isArrayLiteralExpression(prop.initializer) - ? firstDefined(prop.initializer.elements, value => isStringLiteral(value) ? tryRemoveSuffix(value.text, "/*") : undefined) - : undefined); - if (existing) return existing; - - changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); - return defaultTypesDirectoryName; - } - function getInstallCommand(fileName: string, packageName: string): InstallPackageAction { return { type: "install package", file: fileName, packageName }; } diff --git a/src/services/codefixes/generateTypes.ts b/src/services/codefixes/generateTypes.ts deleted file mode 100644 index 53c474f5d35c0..0000000000000 --- a/src/services/codefixes/generateTypes.ts +++ /dev/null @@ -1,252 +0,0 @@ -namespace ts { - export function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string { - return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, OutputKind.ExportEquals); - } - - export function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string { - return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, OutputKind.Global); - } - - function generateTypesForModuleOrGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global): string { - return valueInfoToDeclarationFileText(inspectValue(name, globalValue), formatSettings, outputKind); - } - - /* @internal */ - export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global = OutputKind.ExportEquals): string { - return textChanges.getNewFileText(toStatements(valueInfo, outputKind), ScriptKind.TS, formatSettings.newLineCharacter || "\n", formatting.getFormatContext(formatSettings)); - } - - /* @internal */ - const enum OutputKind { ExportEquals, NamedExport, NamespaceMember, Global } - function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray { - return toStatements(info, OutputKind.NamespaceMember); - } - function toStatements(info: ValueInfo, kind: OutputKind): ReadonlyArray { - const isDefault = info.name === InternalSymbolName.Default; - const name = isDefault ? "_default" : info.name; - if (!isValidIdentifier(name) || isDefault && kind !== OutputKind.NamedExport) return emptyArray; - - const modifiers = isDefault && info.kind === ValueKind.FunctionOrClass ? [createModifier(SyntaxKind.ExportKeyword), createModifier(SyntaxKind.DefaultKeyword)] - : kind === OutputKind.Global || kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] - : kind === OutputKind.NamedExport ? [createModifier(SyntaxKind.ExportKeyword)] - : undefined; - const exportEquals = () => kind === OutputKind.ExportEquals ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : emptyArray; - const exportDefault = () => isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : emptyArray; - - switch (info.kind) { - case ValueKind.FunctionOrClass: - return [...exportEquals(), ...functionOrClassToStatements(modifiers, name, info)]; - case ValueKind.Object: - const { members, hasNontrivialPrototype } = info; - if (!hasNontrivialPrototype) { - if (kind === OutputKind.ExportEquals) { - return flatMap(members, v => toStatements(v, OutputKind.NamedExport)); - } - if (members.some(m => m.kind === ValueKind.FunctionOrClass)) { - // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. - return [...exportDefault(), createNamespace(modifiers, name, flatMap(members, toNamespaceMemberStatements))]; - } - } - // falls through - case ValueKind.Const: - case ValueKind.Array: { - const comment = info.kind === ValueKind.Const ? info.comment : undefined; - const constVar = createVariableStatement(modifiers, createVariableDeclarationList([createVariableDeclaration(name, toType(info))], NodeFlags.Const)); - return [...exportEquals(), ...exportDefault(), addComment(constVar, comment)]; - } - default: - return Debug.assertNever(info); - } - } - function exportEqualsOrDefault(name: string, isExportEquals: boolean): ExportAssignment { - return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, createIdentifier(name)); - } - - function functionOrClassToStatements(modifiers: Modifiers, name: string, { source, prototypeMembers, namespaceMembers }: ValueInfoFunctionOrClass): ReadonlyArray { - const fnAst = parseClassOrFunctionBody(source); - const { parameters, returnType } = fnAst === undefined ? { parameters: emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst); - const protoOrInstanceMembers = createMap(); - if (typeof fnAst === "object") getConstructorFunctionInstanceProperties(fnAst, protoOrInstanceMembers); - for (const p of prototypeMembers) { - // ignore non-functions on the prototype - if (p.kind === ValueKind.FunctionOrClass) { - const m = tryGetMethod(p); - if (m) { - protoOrInstanceMembers.set(p.name, m); - } - } - } - - const classStaticMembers: ClassElement[] | undefined = - protoOrInstanceMembers.size !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor ? [] : undefined; - - const namespaceStatements = flatMap(namespaceMembers, info => { - if (!isValidIdentifier(info.name)) return undefined; - if (classStaticMembers) { - switch (info.kind) { - case ValueKind.Object: - if (info.members.some(m => m.kind === ValueKind.FunctionOrClass)) { - break; - } - // falls through - case ValueKind.Array: - case ValueKind.Const: - classStaticMembers.push( - addComment( - createProperty(/*decorators*/ undefined, [createModifier(SyntaxKind.StaticKeyword)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), - info.kind === ValueKind.Const ? info.comment : undefined)); - return undefined; - case ValueKind.FunctionOrClass: - if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. - const sig = tryGetMethod(info, [createModifier(SyntaxKind.StaticKeyword)]); - if (sig) { - classStaticMembers.push(sig); - return undefined; - } - } - break; - default: - Debug.assertNever(info); - } - } - return toStatements(info, OutputKind.NamespaceMember); - }); - - const decl = classStaticMembers - ? createClassDeclaration( - /*decorators*/ undefined, - modifiers, - name, - /*typeParameters*/ undefined, - /*heritageClauses*/ undefined, - [ - ...classStaticMembers, - ...(parameters.length ? [createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : emptyArray), - ...arrayFrom(protoOrInstanceMembers.values()), - ]) - : createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); - return [decl, ...(namespaceStatements.length === 0 ? emptyArray : [createNamespace(modifiers && modifiers.map(m => getSynthesizedDeepClone(m)), name, namespaceStatements)])]; - } - - function tryGetMethod({ name, source }: ValueInfoFunctionOrClass, modifiers?: Modifiers): MethodDeclaration | undefined { - if (!isValidIdentifier(name)) return undefined; - const fnAst = parseClassOrFunctionBody(source); - if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === SyntaxKind.Constructor)) return undefined; - const sig = getParametersAndReturnType(fnAst); - return sig && createMethod( - /*decorators*/ undefined, - modifiers, - /*asteriskToken*/ undefined, - name, - /*questionToken*/ undefined, - /*typeParameters*/ undefined, - sig.parameters, - sig.returnType, - /*body*/ undefined); - } - - function toType(info: ValueInfo): TypeNode { - switch (info.kind) { - case ValueKind.Const: - return createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); - case ValueKind.Array: - return createArrayTypeNode(toType(info.inner)); - case ValueKind.FunctionOrClass: - return createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. - case ValueKind.Object: - return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); - default: - return Debug.assertNever(info); - } - } - function toPropertyName(name: string): Identifier | StringLiteral { - return isIdentifierText(name, ScriptTarget.ESNext) ? createIdentifier(name) : createStringLiteral(name); - } - - // Parses assignments to "this.x" in the constructor into class property declarations - function getConstructorFunctionInstanceProperties(fnAst: FunctionOrConstructorNode, members: Map): void { - forEachOwnNodeOfFunction(fnAst, node => { - if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && - isPropertyAccessExpression(node.left) && node.left.expression.kind === SyntaxKind.ThisKeyword) { - const name = node.left.name.text; - if (!isJsPrivate(name)) { - getOrUpdate(members, name, () => createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); - } - } - }); - } - - interface ParametersAndReturnType { readonly parameters: ReadonlyArray; readonly returnType: TypeNode; } - function getParametersAndReturnType(fnAst: FunctionOrConstructor): ParametersAndReturnType { - if (typeof fnAst === "number") { - return { parameters: fill(fnAst, i => makeParameter(`p${i}`, anyType())), returnType: anyType() }; - } - let usedArguments = false, hasReturn = false; - forEachOwnNodeOfFunction(fnAst, node => { - usedArguments = usedArguments || isIdentifier(node) && node.text === "arguments"; - hasReturn = hasReturn || isReturnStatement(node) && !!node.expression && node.expression.kind !== SyntaxKind.VoidExpression; - }); - const parameters = [ - ...fnAst.parameters.map(p => makeParameter(`${p.name.getText()}`, inferParameterType(fnAst, p))), - ...(usedArguments ? [makeRestParameter()] : emptyArray), - ]; - return { parameters, returnType: hasReturn ? anyType() : createKeywordTypeNode(SyntaxKind.VoidKeyword) }; - } - function makeParameter(name: string, type: TypeNode): ParameterDeclaration { - return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); - } - function makeRestParameter(): ParameterDeclaration { - return createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, createToken(SyntaxKind.DotDotDotToken), "args", /*questionToken*/ undefined, createArrayTypeNode(anyType())); - } - - type FunctionOrConstructorNode = FunctionExpression | ArrowFunction | ConstructorDeclaration | MethodDeclaration; - type FunctionOrConstructor = FunctionOrConstructorNode | number; // number is for native function - /** Returns 'undefined' for class with no declared constructor */ - function parseClassOrFunctionBody(source: string | number): FunctionOrConstructor | undefined { - if (typeof source === "number") return source; - const classOrFunction = tryCast(parseExpression(source), (node): node is FunctionExpression | ArrowFunction | ClassExpression => isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)); - return classOrFunction - ? isClassExpression(classOrFunction) ? find(classOrFunction.members, isConstructorDeclaration) : classOrFunction - // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. - : cast(first(cast(parseExpression(`{ ${source} }`), isObjectLiteralExpression).properties), isMethodDeclaration); - } - - function parseExpression(expr: string): Expression { - const text = `const _ = ${expr}`; - const srcFile = createSourceFile("test.ts", text, ScriptTarget.Latest, /*setParentNodes*/ true); - return first(cast(first(srcFile.statements), isVariableStatement).declarationList.declarations).initializer!; - } - - function inferParameterType(_fn: FunctionOrConstructor, _param: ParameterDeclaration): TypeNode { - // TODO: Inspect function body for clues (see inferFromUsage.ts) - return anyType(); - } - - // Descends through all nodes in a function, but not in nested functions. - function forEachOwnNodeOfFunction(fnAst: FunctionOrConstructorNode, cb: (node: Node) => void) { - fnAst.body!.forEachChild(function recur(node) { - cb(node); - if (!isFunctionLike(node)) node.forEachChild(recur); - }); - } - - function isValidIdentifier(name: string): boolean { - const keyword = stringToToken(name); - return !(keyword && isNonContextualKeyword(keyword)) && isIdentifierText(name, ScriptTarget.ESNext); - } - - type Modifiers = ReadonlyArray | undefined; - - function addComment(node: T, comment: string | undefined): T { - if (comment !== undefined) addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, comment); - return node; - } - - function anyType(): KeywordTypeNode { - return createKeywordTypeNode(SyntaxKind.AnyKeyword); - } - - function createNamespace(modifiers: Modifiers, name: string, statements: ReadonlyArray): NamespaceDeclaration { - return createModuleDeclaration(/*decorators*/ undefined, modifiers, createIdentifier(name), createModuleBlock(statements), NodeFlags.Namespace) as NamespaceDeclaration; - } -} diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 8d710f87a4ea2..38792d448e4ac 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -98,7 +98,7 @@ namespace ts.formatting { rule("SpaceAfterConditionalClosingParen", SyntaxKind.CloseParenToken, SyntaxKind.OpenBracketToken, [isControlDeclContext], RuleAction.Space), rule("NoSpaceBetweenFunctionKeywordAndStar", SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken, [isFunctionDeclarationOrFunctionExpressionContext], RuleAction.Delete), - rule("SpaceAfterStarInGeneratorDeclaration", SyntaxKind.AsteriskToken, [SyntaxKind.Identifier, SyntaxKind.OpenParenToken], [isFunctionDeclarationOrFunctionExpressionContext], RuleAction.Space), + rule("SpaceAfterStarInGeneratorDeclaration", SyntaxKind.AsteriskToken, SyntaxKind.Identifier, [isFunctionDeclarationOrFunctionExpressionContext], RuleAction.Space), rule("SpaceAfterFunctionInFuncDecl", SyntaxKind.FunctionKeyword, anyToken, [isFunctionDeclContext], RuleAction.Space), // Insert new line after { and before } in multi-line contexts. @@ -241,8 +241,8 @@ namespace ts.formatting { rule("NoSpaceAfterComma", SyntaxKind.CommaToken, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], RuleAction.Delete), // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], RuleAction.Space), - rule("NoSpaceAfterAnonymousFunctionKeyword", SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], RuleAction.Delete), + rule("SpaceAfterAnonymousFunctionKeyword", [SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken], SyntaxKind.OpenParenToken, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], RuleAction.Space), + rule("NoSpaceAfterAnonymousFunctionKeyword", [SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken], SyntaxKind.OpenParenToken, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], RuleAction.Delete), // Insert space after keywords in control flow statements rule("SpaceAfterKeywordInControl", keywords, SyntaxKind.OpenParenToken, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], RuleAction.Space), diff --git a/src/services/services.ts b/src/services/services.ts index 5f0d3472a3e93..42d2278bcba93 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1833,30 +1833,15 @@ namespace ts { function applyCodeActionCommand(fileName: Path, action: CodeActionCommand[]): Promise; function applyCodeActionCommand(fileName: Path | CodeActionCommand | CodeActionCommand[], actionOrFormatSettingsOrUndefined?: CodeActionCommand | CodeActionCommand[] | FormatCodeSettings): Promise { const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined as CodeActionCommand | CodeActionCommand[] : fileName as CodeActionCommand[]; - const formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined as FormatCodeSettings : undefined; - return isArray(action) ? Promise.all(action.map(a => applySingleCodeActionCommand(a, formatSettings))) : applySingleCodeActionCommand(action, formatSettings); + return isArray(action) ? Promise.all(action.map(a => applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action); } - function applySingleCodeActionCommand(action: CodeActionCommand, formatSettings: FormatCodeSettings | undefined): Promise { + function applySingleCodeActionCommand(action: CodeActionCommand): Promise { const getPath = (path: string): Path => toPath(path, currentDirectory, getCanonicalFileName); - switch (action.type) { - case "install package": - return host.installPackage - ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) - : Promise.reject("Host does not implement `installPackage`"); - case "generate types": { - const { fileToGenerateTypesFor, outputFileName } = action; - if (!host.inspectValue) return Promise.reject("Host does not implement `installPackage`"); - const valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); - return valueInfoPromise.then(valueInfo => { - const fullOut = getPath(outputFileName); - host.writeFile!(fullOut, valueInfoToDeclarationFileText(valueInfo, formatSettings || testFormatSettings)); // TODO: GH#18217 - return { successMessage: `Wrote types to '${fullOut}'` }; - }); - } - default: - return Debug.assertNever(action); - } + Debug.assertEqual(action.type, "install package"); + return host.installPackage + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); } function getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index e3f2358be1059..93880ea0d9b10 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -73,7 +73,6 @@ "codefixes/helpers.ts", "codefixes/fixInvalidImportSyntax.ts", "codefixes/fixStrictClassInitialization.ts", - "codefixes/generateTypes.ts", "codefixes/requireInTs.ts", "codefixes/useDefaultImport.ts", "codefixes/fixAddModuleReferTypeMissingTypeof.ts", diff --git a/src/services/types.ts b/src/services/types.ts index 3502e3e06712f..d65a51d4dd342 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -230,7 +230,6 @@ namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - /* @internal */ inspectValue?(options: InspectValueOptions): Promise; writeFile?(fileName: string, content: string): void; /* @internal */ @@ -534,7 +533,7 @@ namespace ts { // Publicly, this type is just `{}`. Internally it is a union of all the actions we use. // See `commands?: {}[]` in protocol.ts - export type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + export type CodeActionCommand = InstallPackageAction; export interface InstallPackageAction { /* @internal */ readonly type: "install package"; @@ -542,16 +541,6 @@ namespace ts { /* @internal */ readonly packageName: string; } - export interface GenerateTypesAction extends GenerateTypesOptions { - /* @internal */ readonly type: "generate types"; - } - - export interface GenerateTypesOptions { - readonly file: string; // File that was importing fileToGenerateTypesFor; used for formatting options. - readonly fileToGenerateTypesFor: string; - readonly outputFileName: string; - } - /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 7dc96c108041d..5506b45d3808d 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1717,7 +1717,19 @@ namespace ts { export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { let clone; - if (isIdentifier(node) && renameMap && checker) { + if (renameMap && checker && isBindingElement(node) && isIdentifier(node.name) && isObjectBindingPattern(node.parent)) { + const symbol = checker.getSymbolAtLocation(node.name); + const renameInfo = symbol && renameMap.get(String(getSymbolId(symbol))); + + if (renameInfo && renameInfo.text !== (node.name || node.propertyName).getText()) { + clone = createBindingElement( + node.dotDotDotToken, + node.propertyName || node.name, + renameInfo, + node.initializer); + } + } + else if (renameMap && checker && isIdentifier(node)) { const symbol = checker.getSymbolAtLocation(node); const renameInfo = symbol && renameMap.get(String(getSymbolId(symbol))); diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 6b73324e2f737..fb0280bbc667c 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -92,6 +92,7 @@ "unittests/tsbuild/amdModulesWithOut.ts", "unittests/tsbuild/emptyFiles.ts", "unittests/tsbuild/graphOrdering.ts", + "unittests/tsbuild/inferredTypeFromTransitiveModule.ts", "unittests/tsbuild/lateBoundSymbol.ts", "unittests/tsbuild/missingExtendedFile.ts", "unittests/tsbuild/outFile.ts", diff --git a/src/testRunner/unittests/services/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts index 8c426effa4cdf..82a404297a3eb 100644 --- a/src/testRunner/unittests/services/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -347,6 +347,24 @@ interface Array {}` _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` function [#|f|](): Promise{ return fetch('https://typescriptlang.org').then(result => { console.log(result) }); +}`); + _testConvertToAsyncFunction("convertToAsyncFunction_arrayBindingPattern", ` +function [#|f|](): Promise{ + return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); +}`); + _testConvertToAsyncFunction("convertToAsyncFunction_objectBindingPattern", ` +function [#|f|](): Promise{ + return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); +}`); + _testConvertToAsyncFunction("convertToAsyncFunction_arrayBindingPatternRename", ` +function [#|f|](): Promise{ + const result = getResult(); + return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); +}`); + _testConvertToAsyncFunction("convertToAsyncFunction_objectBindingPatternRename", ` +function [#|f|](): Promise{ + const result = getResult(); + return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); }`); _testConvertToAsyncFunction("convertToAsyncFunction_basicNoReturnTypeAnnotation", ` function [#|f|]() { @@ -604,6 +622,50 @@ function [#|innerPromise|](): Promise { ` ); + _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding1", ` +function [#|innerPromise|](): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); + }).then(blob => { + return blob.toString(); + }); +} +` + ); + + _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding2", ` +function [#|innerPromise|](): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); + }).then(({ x }) => { + return x.toString(); + }); +} +` + ); + + _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding3", ` +function [#|innerPromise|](): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); + }).then(([x, y]) => { + return (x || y).toString(); + }); +} +` + ); + + _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding4", ` +function [#|innerPromise|](): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }: { blob: { byteOffset: number } }) => [0, blob.byteOffset]).catch(({ message }: Error) => ['Error ', message]); + }).then(([x, y]) => { + return (x || y).toString(); + }); +} +` + ); + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn01", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org").then(resp => console.log(resp)); @@ -1168,7 +1230,13 @@ const { length } = [#|function|] () { _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` function [#|f|]() { - return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParamsBindingPattern", ` +function [#|f|]() { + return Promise.resolve().then(() => ({ x: 3 })).catch(() => ({ x: "a" })).then(({ x }) => !!x); } `); diff --git a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts new file mode 100644 index 0000000000000..792fefb7ba7df --- /dev/null +++ b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts @@ -0,0 +1,49 @@ +namespace ts { + describe("unittests:: tsbuild:: inferredTypeFromTransitiveModule::", () => { + let projFs: vfs.FileSystem; + const { time, tick } = getTime(); + before(() => { + projFs = loadProjectFromDisk("tests/projects/inferredTypeFromTransitiveModule", time); + }); + after(() => { + projFs = undefined!; + }); + + verifyTsbuildOutput({ + scenario: "inferred type from transitive module", + projFs: () => projFs, + time, + tick, + proj: "inferredTypeFromTransitiveModule", + rootNames: ["/src"], + expectedMapFileNames: emptyArray, + lastProjectOutputJs: `/src/obj/index.js`, + outputFiles: [ + "/src/obj/bar.js", "/src/obj/bar.d.ts", + "/src/obj/bundling.js", "/src/obj/bundling.d.ts", + "/src/obj/lazyIndex.js", "/src/obj/lazyIndex.d.ts", + "/src/obj/index.js", "/src/obj/index.d.ts", + "/src/obj/tsconfig.tsbuildinfo" + ], + initialBuild: { + modifyFs: noop, + expectedDiagnostics: [ + getExpectedDiagnosticForProjectsInBuild("src/tsconfig.json"), + [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/tsconfig.json", "src/obj/bar.js"], + [Diagnostics.Building_project_0, "/src/tsconfig.json"] + ] + }, + incrementalDtsChangedBuild: { + modifyFs: fs => replaceText(fs, "/src/bar.ts", "param: string", ""), + expectedDiagnostics: [ + getExpectedDiagnosticForProjectsInBuild("src/tsconfig.json"), + [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/tsconfig.json", "src/obj/bar.js", "src/bar.ts"], + [Diagnostics.Building_project_0, "/src/tsconfig.json"], + [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, "/src/tsconfig.json"] + ] + }, + baselineOnly: true, + verifyDiagnostics: true + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 81a62c6832e60..ba1eae236a5ec 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -390,7 +390,6 @@ namespace ts.projectSystem { const typingsInstaller: server.ITypingsInstaller = { isKnownTypesPackageName: returnFalse, installPackage: notImplemented, - inspectValue: notImplemented, enqueueInstallTypingsRequest: (proj, typeAcquisition, unresolvedImports) => { assert.isUndefined(request); request = JSON.stringify(server.createInstallTypingsRequest(proj, typeAcquisition, unresolvedImports || server.emptyArray, cachePath)); diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 191d1b0e6d48e..43dc4638418ab 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -232,7 +232,6 @@ namespace ts.server { private static readonly maxActiveRequestCount = 10; private static readonly requestDelayMillis = 100; private packageInstalledPromise: { resolve(value: ApplyCodeActionCommandResult): void, reject(reason: unknown): void } | undefined; - private inspectValuePromise: { resolve(value: ValueInfo): void } | undefined; constructor( private readonly telemetryEnabled: boolean, @@ -270,12 +269,6 @@ namespace ts.server { }); } - inspectValue(options: InspectValueOptions): Promise { - this.send({ kind: "inspectValue", options }); - Debug.assert(this.inspectValuePromise === undefined); - return new Promise(resolve => { this.inspectValuePromise = { resolve }; }); - } - attach(projectService: ProjectService) { this.projectService = projectService; if (this.logger.hasLevel(LogLevel.requestTime)) { @@ -363,7 +356,7 @@ namespace ts.server { } } - private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { + private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Received response:${stringifyIndented(response)}`); } @@ -388,10 +381,6 @@ namespace ts.server { this.event(response, "setTypings"); break; } - case ActionValueInspected: - this.inspectValuePromise!.resolve(response.result); - this.inspectValuePromise = undefined; - break; case EventInitializationFailed: { const body: protocol.TypesInstallerInitializationFailedEventBody = { message: response.message diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 3e44a0d7d7b84..27be0107d8f40 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -168,11 +168,6 @@ namespace ts.server.typingsInstaller { } break; } - case "inspectValue": { - const response: InspectValueResponse = { kind: ActionValueInspected, result: inspectModule(req.options.fileNameToRequire) }; - this.sendResponse(response); - break; - } default: Debug.assertNever(req); } diff --git a/tests/baselines/reference/allowSyntheticDefaultImports6.errors.txt b/tests/baselines/reference/allowSyntheticDefaultImports6.errors.txt index 80b9cf8d074ab..916f50162a121 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports6.errors.txt +++ b/tests/baselines/reference/allowSyntheticDefaultImports6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(1,8): error TS1192: Module '"tests/cases/compiler/b"' has no default export. +tests/cases/compiler/a.ts(1,8): error TS1259: Module '"tests/cases/compiler/b"' can only be default-imported using the 'esModuleInterop' flag ==== tests/cases/compiler/b.d.ts (0 errors) ==== @@ -10,6 +10,7 @@ tests/cases/compiler/a.ts(1,8): error TS1192: Module '"tests/cases/compiler/b"' ==== tests/cases/compiler/a.ts (1 errors) ==== import Foo from "./b"; ~~~ -!!! error TS1192: Module '"tests/cases/compiler/b"' has no default export. +!!! error TS1259: Module '"tests/cases/compiler/b"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/b.d.ts:4:1: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. export var x = new Foo(); \ No newline at end of file diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 1b4acd88ebf79..5d5472e840592 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -628,7 +628,7 @@ declare namespace ts { initializer?: Expression; } interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ @@ -2492,6 +2492,7 @@ declare namespace ts { interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; + allowUmdGlobalAccess?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; alwaysStrict?: boolean; @@ -4543,13 +4544,12 @@ declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; - type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4982,16 +4982,9 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } - interface GenerateTypesAction extends GenerateTypesOptions { - } - interface GenerateTypesOptions { - readonly file: string; - readonly fileToGenerateTypesFor: string; - readonly outputFileName: string; - } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5615,10 +5608,6 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } -declare namespace ts { - function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; - function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; -} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index c25e1d733c0c8..e8e2bed3bb8f9 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -628,7 +628,7 @@ declare namespace ts { initializer?: Expression; } interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrandBrand: any; + _objectLiteralBrand: any; name?: PropertyName; } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ @@ -2492,6 +2492,7 @@ declare namespace ts { interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; + allowUmdGlobalAccess?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; alwaysStrict?: boolean; @@ -4543,13 +4544,12 @@ declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; - type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4982,16 +4982,9 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction | GenerateTypesAction; + type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } - interface GenerateTypesAction extends GenerateTypesOptions { - } - interface GenerateTypesOptions { - readonly file: string; - readonly fileToGenerateTypesFor: string; - readonly outputFileName: string; - } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5615,10 +5608,6 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } -declare namespace ts { - function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; - function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; -} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; diff --git a/tests/baselines/reference/assignmentIndexedToPrimitives.errors.txt b/tests/baselines/reference/assignmentIndexedToPrimitives.errors.txt new file mode 100644 index 0000000000000..88c822f6dcb60 --- /dev/null +++ b/tests/baselines/reference/assignmentIndexedToPrimitives.errors.txt @@ -0,0 +1,55 @@ +tests/cases/compiler/assignmentIndexedToPrimitives.ts(1,7): error TS2322: Type 'number[]' is not assignable to type 'number'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(2,7): error TS2322: Type 'string[]' is not assignable to type 'number'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(3,7): error TS2322: Type '(string | number)[]' is not assignable to type 'number'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(4,7): error TS2322: Type 'number[]' is not assignable to type '0'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(6,7): error TS2322: Type 'number[]' is not assignable to type 'string'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(7,7): error TS2322: Type 'string[]' is not assignable to type 'string'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(8,7): error TS2322: Type '(string | number)[]' is not assignable to type 'string'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(9,7): error TS2322: Type 'string[]' is not assignable to type '"01"'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(11,7): error TS2322: Type '{ 0: number; }' is not assignable to type 'number'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(13,7): error TS2322: Type '{ 0: number; }' is not assignable to type 'string'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(14,7): error TS2322: Type '{ "0": number; }' is not assignable to type 'string'. +tests/cases/compiler/assignmentIndexedToPrimitives.ts(15,7): error TS2322: Type '{ 0: string; }' is not assignable to type 'string'. + + +==== tests/cases/compiler/assignmentIndexedToPrimitives.ts (12 errors) ==== + const n1: number = [0]; + ~~ +!!! error TS2322: Type 'number[]' is not assignable to type 'number'. + const n2: number = ["0"]; + ~~ +!!! error TS2322: Type 'string[]' is not assignable to type 'number'. + const n3: number = [0, "1"]; + ~~ +!!! error TS2322: Type '(string | number)[]' is not assignable to type 'number'. + const n4: 0 = [0]; + ~~ +!!! error TS2322: Type 'number[]' is not assignable to type '0'. + + const s1: string = [0]; + ~~ +!!! error TS2322: Type 'number[]' is not assignable to type 'string'. + const s2: string = ["0"]; + ~~ +!!! error TS2322: Type 'string[]' is not assignable to type 'string'. + const s3: string = [0, "1"]; + ~~ +!!! error TS2322: Type '(string | number)[]' is not assignable to type 'string'. + const s4: "01" = ["0", "1"]; + ~~ +!!! error TS2322: Type 'string[]' is not assignable to type '"01"'. + + const no1: number = { 0: 1 }; + ~~~ +!!! error TS2322: Type '{ 0: number; }' is not assignable to type 'number'. + + const so1: string = { 0: 1 }; + ~~~ +!!! error TS2322: Type '{ 0: number; }' is not assignable to type 'string'. + const so2: string = { "0": 1 }; + ~~~ +!!! error TS2322: Type '{ "0": number; }' is not assignable to type 'string'. + const so3: string = { 0: "1" }; + ~~~ +!!! error TS2322: Type '{ 0: string; }' is not assignable to type 'string'. + \ No newline at end of file diff --git a/tests/baselines/reference/assignmentIndexedToPrimitives.js b/tests/baselines/reference/assignmentIndexedToPrimitives.js new file mode 100644 index 0000000000000..363d41fc14de9 --- /dev/null +++ b/tests/baselines/reference/assignmentIndexedToPrimitives.js @@ -0,0 +1,31 @@ +//// [assignmentIndexedToPrimitives.ts] +const n1: number = [0]; +const n2: number = ["0"]; +const n3: number = [0, "1"]; +const n4: 0 = [0]; + +const s1: string = [0]; +const s2: string = ["0"]; +const s3: string = [0, "1"]; +const s4: "01" = ["0", "1"]; + +const no1: number = { 0: 1 }; + +const so1: string = { 0: 1 }; +const so2: string = { "0": 1 }; +const so3: string = { 0: "1" }; + + +//// [assignmentIndexedToPrimitives.js] +var n1 = [0]; +var n2 = ["0"]; +var n3 = [0, "1"]; +var n4 = [0]; +var s1 = [0]; +var s2 = ["0"]; +var s3 = [0, "1"]; +var s4 = ["0", "1"]; +var no1 = { 0: 1 }; +var so1 = { 0: 1 }; +var so2 = { "0": 1 }; +var so3 = { 0: "1" }; diff --git a/tests/baselines/reference/assignmentIndexedToPrimitives.symbols b/tests/baselines/reference/assignmentIndexedToPrimitives.symbols new file mode 100644 index 0000000000000..37b41d2f9c9a3 --- /dev/null +++ b/tests/baselines/reference/assignmentIndexedToPrimitives.symbols @@ -0,0 +1,41 @@ +=== tests/cases/compiler/assignmentIndexedToPrimitives.ts === +const n1: number = [0]; +>n1 : Symbol(n1, Decl(assignmentIndexedToPrimitives.ts, 0, 5)) + +const n2: number = ["0"]; +>n2 : Symbol(n2, Decl(assignmentIndexedToPrimitives.ts, 1, 5)) + +const n3: number = [0, "1"]; +>n3 : Symbol(n3, Decl(assignmentIndexedToPrimitives.ts, 2, 5)) + +const n4: 0 = [0]; +>n4 : Symbol(n4, Decl(assignmentIndexedToPrimitives.ts, 3, 5)) + +const s1: string = [0]; +>s1 : Symbol(s1, Decl(assignmentIndexedToPrimitives.ts, 5, 5)) + +const s2: string = ["0"]; +>s2 : Symbol(s2, Decl(assignmentIndexedToPrimitives.ts, 6, 5)) + +const s3: string = [0, "1"]; +>s3 : Symbol(s3, Decl(assignmentIndexedToPrimitives.ts, 7, 5)) + +const s4: "01" = ["0", "1"]; +>s4 : Symbol(s4, Decl(assignmentIndexedToPrimitives.ts, 8, 5)) + +const no1: number = { 0: 1 }; +>no1 : Symbol(no1, Decl(assignmentIndexedToPrimitives.ts, 10, 5)) +>0 : Symbol(0, Decl(assignmentIndexedToPrimitives.ts, 10, 21)) + +const so1: string = { 0: 1 }; +>so1 : Symbol(so1, Decl(assignmentIndexedToPrimitives.ts, 12, 5)) +>0 : Symbol(0, Decl(assignmentIndexedToPrimitives.ts, 12, 21)) + +const so2: string = { "0": 1 }; +>so2 : Symbol(so2, Decl(assignmentIndexedToPrimitives.ts, 13, 5)) +>"0" : Symbol("0", Decl(assignmentIndexedToPrimitives.ts, 13, 21)) + +const so3: string = { 0: "1" }; +>so3 : Symbol(so3, Decl(assignmentIndexedToPrimitives.ts, 14, 5)) +>0 : Symbol(0, Decl(assignmentIndexedToPrimitives.ts, 14, 21)) + diff --git a/tests/baselines/reference/assignmentIndexedToPrimitives.types b/tests/baselines/reference/assignmentIndexedToPrimitives.types new file mode 100644 index 0000000000000..7c36c89b1e9fa --- /dev/null +++ b/tests/baselines/reference/assignmentIndexedToPrimitives.types @@ -0,0 +1,68 @@ +=== tests/cases/compiler/assignmentIndexedToPrimitives.ts === +const n1: number = [0]; +>n1 : number +>[0] : number[] +>0 : 0 + +const n2: number = ["0"]; +>n2 : number +>["0"] : string[] +>"0" : "0" + +const n3: number = [0, "1"]; +>n3 : number +>[0, "1"] : (string | number)[] +>0 : 0 +>"1" : "1" + +const n4: 0 = [0]; +>n4 : 0 +>[0] : number[] +>0 : 0 + +const s1: string = [0]; +>s1 : string +>[0] : number[] +>0 : 0 + +const s2: string = ["0"]; +>s2 : string +>["0"] : string[] +>"0" : "0" + +const s3: string = [0, "1"]; +>s3 : string +>[0, "1"] : (string | number)[] +>0 : 0 +>"1" : "1" + +const s4: "01" = ["0", "1"]; +>s4 : "01" +>["0", "1"] : string[] +>"0" : "0" +>"1" : "1" + +const no1: number = { 0: 1 }; +>no1 : number +>{ 0: 1 } : { 0: number; } +>0 : number +>1 : 1 + +const so1: string = { 0: 1 }; +>so1 : string +>{ 0: 1 } : { 0: number; } +>0 : number +>1 : 1 + +const so2: string = { "0": 1 }; +>so2 : string +>{ "0": 1 } : { "0": number; } +>"0" : number +>1 : 1 + +const so3: string = { 0: "1" }; +>so3 : string +>{ 0: "1" } : { 0: string; } +>0 : string +>"1" : "1" + diff --git a/tests/baselines/reference/capturedParametersInInitializers1.errors.txt b/tests/baselines/reference/capturedParametersInInitializers1.errors.txt new file mode 100644 index 0000000000000..fce7c6ee488d9 --- /dev/null +++ b/tests/baselines/reference/capturedParametersInInitializers1.errors.txt @@ -0,0 +1,52 @@ +tests/cases/compiler/capturedParametersInInitializers1.ts(18,20): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. +tests/cases/compiler/capturedParametersInInitializers1.ts(22,26): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. +tests/cases/compiler/capturedParametersInInitializers1.ts(38,21): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. + + +==== tests/cases/compiler/capturedParametersInInitializers1.ts (3 errors) ==== + // ok - usage is deferred + function foo1(y = class {c = x}, x = 1) { + new y().c; + } + + // ok - used in file + function foo2(y = function(x: typeof z) {}, z = 1) { + + } + + // ok -used in type + let a; + function foo3(y = { x: a }, z = 1) { + + } + + // error - used before declaration + function foo4(y = {z}, z = 1) { + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. + } + + // error - used before declaration, IIFEs are inlined + function foo5(y = (() => z)(), z = 1) { + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. + } + + // ok - IIFE inside another function + function foo6(y = () => (() => z)(), z = 1) { + } + + // ok - used inside immediately invoked generator function + function foo7(y = (function*() {yield z})(), z = 1) { + } + + // ok - used inside immediately invoked async function + function foo8(y = (async () => z)(), z = 1) { + } + + // error - used as computed name of method + function foo9(y = {[z]() { return z; }}, z = 1) { + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. + } + \ No newline at end of file diff --git a/tests/baselines/reference/capturedParametersInInitializers1.js b/tests/baselines/reference/capturedParametersInInitializers1.js index 49b031e8b199f..7ec393e2e39c3 100644 --- a/tests/baselines/reference/capturedParametersInInitializers1.js +++ b/tests/baselines/reference/capturedParametersInInitializers1.js @@ -13,28 +13,72 @@ function foo2(y = function(x: typeof z) {}, z = 1) { let a; function foo3(y = { x: a }, z = 1) { -} +} + +// error - used before declaration +function foo4(y = {z}, z = 1) { +} + +// error - used before declaration, IIFEs are inlined +function foo5(y = (() => z)(), z = 1) { +} + +// ok - IIFE inside another function +function foo6(y = () => (() => z)(), z = 1) { +} + +// ok - used inside immediately invoked generator function +function foo7(y = (function*() {yield z})(), z = 1) { +} + +// ok - used inside immediately invoked async function +function foo8(y = (async () => z)(), z = 1) { +} + +// error - used as computed name of method +function foo9(y = {[z]() { return z; }}, z = 1) { +} + //// [capturedParametersInInitializers1.js] +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()); + }); +}; // ok - usage is deferred -function foo1(y, x) { - if (y === void 0) { y = /** @class */ (function () { - function class_1() { - this.c = x; - } - return class_1; - }()); } - if (x === void 0) { x = 1; } +function foo1(y = class { + constructor() { + this.c = x; + } +}, x = 1) { new y().c; } // ok - used in file -function foo2(y, z) { - if (y === void 0) { y = function (x) { }; } - if (z === void 0) { z = 1; } +function foo2(y = function (x) { }, z = 1) { } // ok -used in type -var a; -function foo3(y, z) { - if (y === void 0) { y = { x: a }; } - if (z === void 0) { z = 1; } +let a; +function foo3(y = { x: a }, z = 1) { +} +// error - used before declaration +function foo4(y = { z }, z = 1) { +} +// error - used before declaration, IIFEs are inlined +function foo5(y = (() => z)(), z = 1) { +} +// ok - IIFE inside another function +function foo6(y = () => (() => z)(), z = 1) { +} +// ok - used inside immediately invoked generator function +function foo7(y = (function* () { yield z; })(), z = 1) { +} +// ok - used inside immediately invoked async function +function foo8(y = (() => __awaiter(this, void 0, void 0, function* () { return z; }))(), z = 1) { +} +// error - used as computed name of method +function foo9(y = { [z]() { return z; } }, z = 1) { } diff --git a/tests/baselines/reference/capturedParametersInInitializers1.symbols b/tests/baselines/reference/capturedParametersInInitializers1.symbols index b72a2c75ef160..d9ab1ef6cc25a 100644 --- a/tests/baselines/reference/capturedParametersInInitializers1.symbols +++ b/tests/baselines/reference/capturedParametersInInitializers1.symbols @@ -36,3 +36,54 @@ function foo3(y = { x: a }, z = 1) { >z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 12, 37)) } + +// error - used before declaration +function foo4(y = {z}, z = 1) { +>foo4 : Symbol(foo4, Decl(capturedParametersInInitializers1.ts, 14, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 17, 14)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 17, 19)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 17, 22)) +} + +// error - used before declaration, IIFEs are inlined +function foo5(y = (() => z)(), z = 1) { +>foo5 : Symbol(foo5, Decl(capturedParametersInInitializers1.ts, 18, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 21, 14)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 21, 30)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 21, 30)) +} + +// ok - IIFE inside another function +function foo6(y = () => (() => z)(), z = 1) { +>foo6 : Symbol(foo6, Decl(capturedParametersInInitializers1.ts, 22, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 25, 14)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 25, 36)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 25, 36)) +} + +// ok - used inside immediately invoked generator function +function foo7(y = (function*() {yield z})(), z = 1) { +>foo7 : Symbol(foo7, Decl(capturedParametersInInitializers1.ts, 26, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 29, 14)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 29, 44)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 29, 44)) +} + +// ok - used inside immediately invoked async function +function foo8(y = (async () => z)(), z = 1) { +>foo8 : Symbol(foo8, Decl(capturedParametersInInitializers1.ts, 30, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 33, 14)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 33, 36)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 33, 36)) +} + +// error - used as computed name of method +function foo9(y = {[z]() { return z; }}, z = 1) { +>foo9 : Symbol(foo9, Decl(capturedParametersInInitializers1.ts, 34, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 37, 14)) +>[z] : Symbol([z], Decl(capturedParametersInInitializers1.ts, 37, 19)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40)) +>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40)) +} + diff --git a/tests/baselines/reference/capturedParametersInInitializers1.types b/tests/baselines/reference/capturedParametersInInitializers1.types index 9e5dee1b82e2a..4819298d1afa3 100644 --- a/tests/baselines/reference/capturedParametersInInitializers1.types +++ b/tests/baselines/reference/capturedParametersInInitializers1.types @@ -44,3 +44,76 @@ function foo3(y = { x: a }, z = 1) { >1 : 1 } + +// error - used before declaration +function foo4(y = {z}, z = 1) { +>foo4 : (y?: { z: number; }, z?: number) => void +>y : { z: number; } +>{z} : { z: number; } +>z : number +>z : number +>1 : 1 +} + +// error - used before declaration, IIFEs are inlined +function foo5(y = (() => z)(), z = 1) { +>foo5 : (y?: number, z?: number) => void +>y : number +>(() => z)() : number +>(() => z) : () => number +>() => z : () => number +>z : number +>z : number +>1 : 1 +} + +// ok - IIFE inside another function +function foo6(y = () => (() => z)(), z = 1) { +>foo6 : (y?: () => number, z?: number) => void +>y : () => number +>() => (() => z)() : () => number +>(() => z)() : number +>(() => z) : () => number +>() => z : () => number +>z : number +>z : number +>1 : 1 +} + +// ok - used inside immediately invoked generator function +function foo7(y = (function*() {yield z})(), z = 1) { +>foo7 : (y?: IterableIterator, z?: number) => void +>y : IterableIterator +>(function*() {yield z})() : IterableIterator +>(function*() {yield z}) : () => IterableIterator +>function*() {yield z} : () => IterableIterator +>yield z : any +>z : number +>z : number +>1 : 1 +} + +// ok - used inside immediately invoked async function +function foo8(y = (async () => z)(), z = 1) { +>foo8 : (y?: Promise, z?: number) => void +>y : Promise +>(async () => z)() : Promise +>(async () => z) : () => Promise +>async () => z : () => Promise +>z : number +>z : number +>1 : 1 +} + +// error - used as computed name of method +function foo9(y = {[z]() { return z; }}, z = 1) { +>foo9 : (y?: { [x: number]: () => number; }, z?: number) => void +>y : { [x: number]: () => number; } +>{[z]() { return z; }} : { [x: number]: () => number; } +>[z] : () => number +>z : number +>z : number +>z : number +>1 : 1 +} + diff --git a/tests/baselines/reference/capturedParametersInInitializers2.errors.txt b/tests/baselines/reference/capturedParametersInInitializers2.errors.txt index 70435b77cee84..df6c71f544b1b 100644 --- a/tests/baselines/reference/capturedParametersInInitializers2.errors.txt +++ b/tests/baselines/reference/capturedParametersInInitializers2.errors.txt @@ -1,14 +1,32 @@ -tests/cases/compiler/capturedParametersInInitializers2.ts(1,36): error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. -tests/cases/compiler/capturedParametersInInitializers2.ts(4,26): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/compiler/capturedParametersInInitializers2.ts(3,20): error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. +tests/cases/compiler/capturedParametersInInitializers2.ts(4,14): error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. +tests/cases/compiler/capturedParametersInInitializers2.ts(6,10): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. +tests/cases/compiler/capturedParametersInInitializers2.ts(13,26): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/compiler/capturedParametersInInitializers2.ts(13,27): error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. -==== tests/cases/compiler/capturedParametersInInitializers2.ts (2 errors) ==== - function foo(y = class {static c = x}, x = 1) { - ~ +==== tests/cases/compiler/capturedParametersInInitializers2.ts (5 errors) ==== + function foo( + y = class { + static c = x; + ~ !!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. + get [x]() {return x;} + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. + constructor() { x; } + [z]() { return z; } + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it. + }, + x = 1, + z = 2 + ) { y.c } function foo2(y = class {[x] = x}, x = 1) { ~~~ !!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. + ~ +!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'x' declared after it. } \ No newline at end of file diff --git a/tests/baselines/reference/capturedParametersInInitializers2.js b/tests/baselines/reference/capturedParametersInInitializers2.js index 5b5f06fc5b022..26b01dbab9a5e 100644 --- a/tests/baselines/reference/capturedParametersInInitializers2.js +++ b/tests/baselines/reference/capturedParametersInInitializers2.js @@ -1,20 +1,37 @@ //// [capturedParametersInInitializers2.ts] -function foo(y = class {static c = x}, x = 1) { +function foo( + y = class { + static c = x; + get [x]() {return x;} + constructor() { x; } + [z]() { return z; } + }, + x = 1, + z = 2 +) { y.c } function foo2(y = class {[x] = x}, x = 1) { } //// [capturedParametersInInitializers2.js] -function foo(y, x) { +function foo(y, x, z) { if (y === void 0) { y = (_a = /** @class */ (function () { function class_1() { + x; } + Object.defineProperty(class_1.prototype, x, { + get: function () { return x; }, + enumerable: true, + configurable: true + }); + class_1.prototype[z] = function () { return z; }; return class_1; }()), _a.c = x, _a); } if (x === void 0) { x = 1; } + if (z === void 0) { z = 2; } var _a; y.c; } diff --git a/tests/baselines/reference/capturedParametersInInitializers2.symbols b/tests/baselines/reference/capturedParametersInInitializers2.symbols index 9de6714868d87..e3cf3a07dff6b 100644 --- a/tests/baselines/reference/capturedParametersInInitializers2.symbols +++ b/tests/baselines/reference/capturedParametersInInitializers2.symbols @@ -1,21 +1,45 @@ === tests/cases/compiler/capturedParametersInInitializers2.ts === -function foo(y = class {static c = x}, x = 1) { +function foo( >foo : Symbol(foo, Decl(capturedParametersInInitializers2.ts, 0, 0)) + + y = class { >y : Symbol(y, Decl(capturedParametersInInitializers2.ts, 0, 13)) ->c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 0, 24)) ->x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 0, 38)) ->x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 0, 38)) + static c = x; +>c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 1, 15)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 6, 6)) + + get [x]() {return x;} +>[x] : Symbol((Anonymous class)[x], Decl(capturedParametersInInitializers2.ts, 2, 21)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 6, 6)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 6, 6)) + + constructor() { x; } +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 6, 6)) + + [z]() { return z; } +>[z] : Symbol((Anonymous class)[z], Decl(capturedParametersInInitializers2.ts, 4, 28)) +>z : Symbol(z, Decl(capturedParametersInInitializers2.ts, 7, 10)) +>z : Symbol(z, Decl(capturedParametersInInitializers2.ts, 7, 10)) + + }, + x = 1, +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 6, 6)) + + z = 2 +>z : Symbol(z, Decl(capturedParametersInInitializers2.ts, 7, 10)) + +) { y.c ->y.c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 0, 24)) +>y.c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 1, 15)) >y : Symbol(y, Decl(capturedParametersInInitializers2.ts, 0, 13)) ->c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 0, 24)) +>c : Symbol((Anonymous class).c, Decl(capturedParametersInInitializers2.ts, 1, 15)) } function foo2(y = class {[x] = x}, x = 1) { ->foo2 : Symbol(foo2, Decl(capturedParametersInInitializers2.ts, 2, 1)) ->y : Symbol(y, Decl(capturedParametersInInitializers2.ts, 3, 14)) ->[x] : Symbol((Anonymous class)[x], Decl(capturedParametersInInitializers2.ts, 3, 25)) ->x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 3, 34)) ->x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 3, 34)) ->x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 3, 34)) +>foo2 : Symbol(foo2, Decl(capturedParametersInInitializers2.ts, 11, 1)) +>y : Symbol(y, Decl(capturedParametersInInitializers2.ts, 12, 14)) +>[x] : Symbol((Anonymous class)[x], Decl(capturedParametersInInitializers2.ts, 12, 25)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 12, 34)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 12, 34)) +>x : Symbol(x, Decl(capturedParametersInInitializers2.ts, 12, 34)) } diff --git a/tests/baselines/reference/capturedParametersInInitializers2.types b/tests/baselines/reference/capturedParametersInInitializers2.types index 89ce29f54761d..bc135347bcaa3 100644 --- a/tests/baselines/reference/capturedParametersInInitializers2.types +++ b/tests/baselines/reference/capturedParametersInInitializers2.types @@ -1,13 +1,38 @@ === tests/cases/compiler/capturedParametersInInitializers2.ts === -function foo(y = class {static c = x}, x = 1) { ->foo : (y?: typeof (Anonymous class), x?: number) => void +function foo( +>foo : (y?: typeof (Anonymous class), x?: number, z?: number) => void + + y = class { >y : typeof (Anonymous class) ->class {static c = x} : typeof (Anonymous class) +>class { static c = x; get [x]() {return x;} constructor() { x; } [z]() { return z; } } : typeof (Anonymous class) + + static c = x; >c : number +>x : number + + get [x]() {return x;} +>[x] : number >x : number +>x : number + + constructor() { x; } +>x : number + + [z]() { return z; } +>[z] : () => number +>z : number +>z : number + + }, + x = 1, >x : number >1 : 1 + z = 2 +>z : number +>2 : 2 + +) { y.c >y.c : number >y : typeof (Anonymous class) diff --git a/tests/baselines/reference/checkDestructuringShorthandAssigment.errors.txt b/tests/baselines/reference/checkDestructuringShorthandAssigment.errors.txt index aca20286905c6..f6b8576c834f7 100644 --- a/tests/baselines/reference/checkDestructuringShorthandAssigment.errors.txt +++ b/tests/baselines/reference/checkDestructuringShorthandAssigment.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/bug25434.js(4,9): error TS2304: Cannot find name 'b'. +tests/cases/compiler/bug25434.js(4,9): error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. ==== tests/cases/compiler/bug25434.js (1 errors) ==== @@ -7,5 +7,5 @@ tests/cases/compiler/bug25434.js(4,9): error TS2304: Cannot find name 'b'. Test(({ b = '5' } = {})); ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/clodulesDerivedClasses.errors.txt b/tests/baselines/reference/clodulesDerivedClasses.errors.txt index 958812b9b84b0..5bb3ff2983dca 100644 --- a/tests/baselines/reference/clodulesDerivedClasses.errors.txt +++ b/tests/baselines/reference/clodulesDerivedClasses.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/clodulesDerivedClasses.ts(9,7): error TS2417: Class static side 'typeof Path' incorrectly extends base class static side 'typeof Shape'. Types of property 'Utils' are incompatible. - Property 'convert' is missing in type 'typeof Utils' but required in type 'typeof Utils'. + Property 'convert' is missing in type 'typeof Path.Utils' but required in type 'typeof Shape.Utils'. ==== tests/cases/compiler/clodulesDerivedClasses.ts (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/clodulesDerivedClasses.ts(9,7): error TS2417: Class static ~~~~ !!! error TS2417: Class static side 'typeof Path' incorrectly extends base class static side 'typeof Shape'. !!! error TS2417: Types of property 'Utils' are incompatible. -!!! error TS2417: Property 'convert' is missing in type 'typeof Utils' but required in type 'typeof Utils'. +!!! error TS2417: Property 'convert' is missing in type 'typeof Path.Utils' but required in type 'typeof Shape.Utils'. !!! related TS2728 tests/cases/compiler/clodulesDerivedClasses.ts:6:21: 'convert' is declared here. name: string; diff --git a/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.errors.txt b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.errors.txt new file mode 100644 index 0000000000000..aa8a0572e6be8 --- /dev/null +++ b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts(5,5): error TS2367: This condition will always return 'false' since the types 'T' and '"x"' have no overlap. + + +==== tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts (1 errors) ==== + // Test for #26758 + + function foo(t: T) { + t === "a"; // Should be allowed + t === "x"; // Should be error + ~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'T' and '"x"' have no overlap. + } + \ No newline at end of file diff --git a/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.js b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.js new file mode 100644 index 0000000000000..6d7824cfd904d --- /dev/null +++ b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.js @@ -0,0 +1,15 @@ +//// [compareTypeParameterConstrainedByLiteralToLiteral.ts] +// Test for #26758 + +function foo(t: T) { + t === "a"; // Should be allowed + t === "x"; // Should be error +} + + +//// [compareTypeParameterConstrainedByLiteralToLiteral.js] +// Test for #26758 +function foo(t) { + t === "a"; // Should be allowed + t === "x"; // Should be error +} diff --git a/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.symbols b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.symbols new file mode 100644 index 0000000000000..dd8c591606322 --- /dev/null +++ b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts === +// Test for #26758 + +function foo(t: T) { +>foo : Symbol(foo, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 0, 0)) +>T : Symbol(T, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 2, 13)) +>t : Symbol(t, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 2, 34)) +>T : Symbol(T, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 2, 13)) + + t === "a"; // Should be allowed +>t : Symbol(t, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 2, 34)) + + t === "x"; // Should be error +>t : Symbol(t, Decl(compareTypeParameterConstrainedByLiteralToLiteral.ts, 2, 34)) +} + diff --git a/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.types b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.types new file mode 100644 index 0000000000000..96792a8b9f0e4 --- /dev/null +++ b/tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.types @@ -0,0 +1,18 @@ +=== tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts === +// Test for #26758 + +function foo(t: T) { +>foo : (t: T) => void +>t : T + + t === "a"; // Should be allowed +>t === "a" : boolean +>t : T +>"a" : "a" + + t === "x"; // Should be error +>t === "x" : boolean +>t : T +>"x" : "x" +} + diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols b/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols index d21db8eb90d5f..b5dcb78015b3f 100644 --- a/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols @@ -403,9 +403,9 @@ export enum PubSubRecordIsStoredInRedisAsA { fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), >fields : Symbol(fields, Decl(conditionalTypeDoesntSpinForever.ts, 94, 18)) >Set : Symbol(Set, Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) ->Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) >SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 92, 21)) diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.types b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types index d4fe4bf48261b..3109b19bacfaf 100644 --- a/tests/baselines/reference/conditionalTypeDoesntSpinForever.types +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types @@ -410,9 +410,9 @@ export enum PubSubRecordIsStoredInRedisAsA { >Set : SetConstructor >Object.keys(soFar) as (keyof SO_FAR)[] : (keyof SO_FAR)[] >Object.keys(soFar) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : { (o: object): string[]; (o: {}): string[]; } >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : { (o: object): string[]; (o: {}): string[]; } >soFar : SO_FAR hasField: (fieldName: string | number | symbol) => fieldName in soFar diff --git a/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.symbols b/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.symbols index fc44c97996c92..60dfdd9983ae3 100644 --- a/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.symbols +++ b/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.symbols @@ -21,9 +21,9 @@ export default class Operation { for(const parameterLocation of Object.keys(parameterValues)) { >parameterLocation : Symbol(parameterLocation, Decl(contextualExpressionTypecheckingDoesntBlowStack.ts, 8, 17)) ->Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >parameterValues : Symbol(parameterValues, Decl(contextualExpressionTypecheckingDoesntBlowStack.ts, 6, 23)) const parameter: any = (this as any).getParameter();; diff --git a/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.types b/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.types index 8d462f4dbd912..3e690f0844b1d 100644 --- a/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.types +++ b/tests/baselines/reference/contextualExpressionTypecheckingDoesntBlowStack.types @@ -21,9 +21,9 @@ export default class Operation { for(const parameterLocation of Object.keys(parameterValues)) { >parameterLocation : string >Object.keys(parameterValues) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : { (o: object): string[]; (o: {}): string[]; } >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : { (o: object): string[]; (o: {}): string[]; } >parameterValues : any const parameter: any = (this as any).getParameter();; diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding1.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding1.ts new file mode 100644 index 0000000000000..7f1559ff7cbff --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding1.ts @@ -0,0 +1,24 @@ +// ==ORIGINAL== + +function /*[#|*/innerPromise/*|]*/(): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); + }).then(blob => { + return blob.toString(); + }); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function innerPromise(): Promise { + const resp = await fetch("https://typescriptlang.org"); + let blob: any; + try { + const { blob } = await resp.blob(); + blob = blob.byteOffset; + } + catch ({ message }) { + blob = 'Error ' + message; + } + return blob.toString(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding2.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding2.ts new file mode 100644 index 0000000000000..fb8c32c5efd4d --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding2.ts @@ -0,0 +1,25 @@ +// ==ORIGINAL== + +function /*[#|*/innerPromise/*|]*/(): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); + }).then(({ x }) => { + return x.toString(); + }); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function innerPromise(): Promise { + const resp = await fetch("https://typescriptlang.org"); + let result: any; + try { + const blob = await resp.blob(); + result = blob.byteOffset; + } + catch (err) { + result = 'Error'; + } + const { x } = result; + return x.toString(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding3.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding3.ts new file mode 100644 index 0000000000000..f55184aa10f8c --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding3.ts @@ -0,0 +1,25 @@ +// ==ORIGINAL== + +function /*[#|*/innerPromise/*|]*/(): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); + }).then(([x, y]) => { + return (x || y).toString(); + }); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function innerPromise(): Promise { + const resp = await fetch("https://typescriptlang.org"); + let result: any; + try { + const { blob } = await resp.blob(); + result = blob.byteOffset; + } + catch ({ message }) { + result = 'Error ' + message; + } + const [x, y] = result; + return (x || y).toString(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding4.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding4.ts new file mode 100644 index 0000000000000..e4dff86ffd968 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerPromiseRetBinding4.ts @@ -0,0 +1,25 @@ +// ==ORIGINAL== + +function /*[#|*/innerPromise/*|]*/(): Promise { + return fetch("https://typescriptlang.org").then(resp => { + return resp.blob().then(({ blob }: { blob: { byteOffset: number } }) => [0, blob.byteOffset]).catch(({ message }: Error) => ['Error ', message]); + }).then(([x, y]) => { + return (x || y).toString(); + }); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function innerPromise(): Promise { + const resp = await fetch("https://typescriptlang.org"); + let result: any[]; + try { + const { blob } = await resp.blob(); + result = [0, blob.byteOffset]; + } + catch ({ message }) { + result = ['Error ', message]; + } + const [x, y] = result; + return (x || y).toString(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPattern.ts new file mode 100644 index 0000000000000..a2aa01edadef3 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPattern.ts @@ -0,0 +1,11 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/(): Promise{ + return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); +} +// ==ASYNC FUNCTION::Convert to async function== + +async function f(): Promise{ + const [result] = await fetch('https://typescriptlang.org'); + console.log(result); +} \ No newline at end of file diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPatternRename.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPatternRename.ts new file mode 100644 index 0000000000000..5847e01d57d1b --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_arrayBindingPatternRename.ts @@ -0,0 +1,13 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/(): Promise{ + const result = getResult(); + return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); +} +// ==ASYNC FUNCTION::Convert to async function== + +async function f(): Promise{ + const result = getResult(); + const [result_1] = await fetch('https://typescriptlang.org'); + console.log(result_1); +} \ No newline at end of file diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js index fa5d3babf7283..8bf267e91b506 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js @@ -1,13 +1,13 @@ // ==ORIGINAL== function /*[#|*/f/*|]*/() { - return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); } // ==ASYNC FUNCTION::Convert to async function== async function f() { - let x_2; + let x_2; try { const x = await Promise.resolve(); x_2 = 1; diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts index 15ec7ce93cfc8..20807ef140c5f 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts @@ -1,13 +1,13 @@ // ==ORIGINAL== function /*[#|*/f/*|]*/() { - return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); } // ==ASYNC FUNCTION::Convert to async function== async function f() { - let x_2: string | number; + let x_2: string | number; try { const x = await Promise.resolve(); x_2 = 1; diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.js new file mode 100644 index 0000000000000..628a16da1a98a --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.js @@ -0,0 +1,20 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return Promise.resolve().then(() => ({ x: 3 })).catch(() => ({ x: "a" })).then(({ x }) => !!x); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + let result; + try { + await Promise.resolve(); + result = ({ x: 3 }); + } + catch (e) { + result = ({ x: "a" }); + } + const { x } = result; + return !!x; +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.ts new file mode 100644 index 0000000000000..ff7ac4bc944b6 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParamsBindingPattern.ts @@ -0,0 +1,20 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return Promise.resolve().then(() => ({ x: 3 })).catch(() => ({ x: "a" })).then(({ x }) => !!x); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + let result: { x: number; } | { x: string; }; + try { + await Promise.resolve(); + result = ({ x: 3 }); + } + catch (e) { + result = ({ x: "a" }); + } + const { x } = result; + return !!x; +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPattern.ts new file mode 100644 index 0000000000000..2f5e19910938b --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPattern.ts @@ -0,0 +1,11 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/(): Promise{ + return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); +} +// ==ASYNC FUNCTION::Convert to async function== + +async function f(): Promise{ + const { result } = await fetch('https://typescriptlang.org'); + console.log(result); +} \ No newline at end of file diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPatternRename.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPatternRename.ts new file mode 100644 index 0000000000000..98b736f788de1 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_objectBindingPatternRename.ts @@ -0,0 +1,13 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/(): Promise{ + const result = getResult(); + return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); +} +// ==ASYNC FUNCTION::Convert to async function== + +async function f(): Promise{ + const result = getResult(); + const { result: result_1 } = await fetch('https://typescriptlang.org'); + console.log(result_1); +} \ No newline at end of file diff --git a/tests/baselines/reference/differentTypesWithSameName.errors.txt b/tests/baselines/reference/differentTypesWithSameName.errors.txt index b027d5be93efb..b8b4b6e859853 100644 --- a/tests/baselines/reference/differentTypesWithSameName.errors.txt +++ b/tests/baselines/reference/differentTypesWithSameName.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/differentTypesWithSameName.ts(16,15): error TS2345: Argument of type 'variable' is not assignable to parameter of type 'm.variable'. - Property 's' is missing in type 'variable' but required in type 'variable'. + Property 's' is missing in type 'variable' but required in type 'm.variable'. ==== tests/cases/compiler/differentTypesWithSameName.ts (1 errors) ==== @@ -21,5 +21,5 @@ tests/cases/compiler/differentTypesWithSameName.ts(16,15): error TS2345: Argumen m.doSomething(v); ~ !!! error TS2345: Argument of type 'variable' is not assignable to parameter of type 'm.variable'. -!!! error TS2345: Property 's' is missing in type 'variable' but required in type 'variable'. +!!! error TS2345: Property 's' is missing in type 'variable' but required in type 'm.variable'. !!! related TS2728 tests/cases/compiler/differentTypesWithSameName.ts:3:5: 's' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/errorWithSameNameType.errors.txt b/tests/baselines/reference/errorWithSameNameType.errors.txt new file mode 100644 index 0000000000000..2c5eeed900d9a --- /dev/null +++ b/tests/baselines/reference/errorWithSameNameType.errors.txt @@ -0,0 +1,32 @@ +tests/cases/compiler/c.ts(7,5): error TS2367: This condition will always return 'false' since the types 'import("tests/cases/compiler/a").F' and 'import("tests/cases/compiler/b").F' have no overlap. +tests/cases/compiler/c.ts(11,1): error TS2741: Property 'foo1' is missing in type 'import("tests/cases/compiler/b").F' but required in type 'import("tests/cases/compiler/a").F'. + + +==== tests/cases/compiler/a.ts (0 errors) ==== + export interface F { + foo1: number + } + +==== tests/cases/compiler/b.ts (0 errors) ==== + export interface F { + foo2: number + } + +==== tests/cases/compiler/c.ts (2 errors) ==== + import * as A from './a' + import * as B from './b' + + let a: A.F + let b: B.F + + if (a === b) { + ~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'import("tests/cases/compiler/a").F' and 'import("tests/cases/compiler/b").F' have no overlap. + + } + + a = b + ~ +!!! error TS2741: Property 'foo1' is missing in type 'import("tests/cases/compiler/b").F' but required in type 'import("tests/cases/compiler/a").F'. +!!! related TS2728 tests/cases/compiler/a.ts:2:5: 'foo1' is declared here. + \ No newline at end of file diff --git a/tests/baselines/reference/errorWithSameNameType.js b/tests/baselines/reference/errorWithSameNameType.js new file mode 100644 index 0000000000000..85dba75385364 --- /dev/null +++ b/tests/baselines/reference/errorWithSameNameType.js @@ -0,0 +1,40 @@ +//// [tests/cases/compiler/errorWithSameNameType.ts] //// + +//// [a.ts] +export interface F { + foo1: number +} + +//// [b.ts] +export interface F { + foo2: number +} + +//// [c.ts] +import * as A from './a' +import * as B from './b' + +let a: A.F +let b: B.F + +if (a === b) { + +} + +a = b + + +//// [a.js] +"use strict"; +exports.__esModule = true; +//// [b.js] +"use strict"; +exports.__esModule = true; +//// [c.js] +"use strict"; +exports.__esModule = true; +var a; +var b; +if (a === b) { +} +a = b; diff --git a/tests/baselines/reference/errorWithSameNameType.symbols b/tests/baselines/reference/errorWithSameNameType.symbols new file mode 100644 index 0000000000000..a197e578d642c --- /dev/null +++ b/tests/baselines/reference/errorWithSameNameType.symbols @@ -0,0 +1,43 @@ +=== tests/cases/compiler/a.ts === +export interface F { +>F : Symbol(F, Decl(a.ts, 0, 0)) + + foo1: number +>foo1 : Symbol(F.foo1, Decl(a.ts, 0, 20)) +} + +=== tests/cases/compiler/b.ts === +export interface F { +>F : Symbol(F, Decl(b.ts, 0, 0)) + + foo2: number +>foo2 : Symbol(F.foo2, Decl(b.ts, 0, 20)) +} + +=== tests/cases/compiler/c.ts === +import * as A from './a' +>A : Symbol(A, Decl(c.ts, 0, 6)) + +import * as B from './b' +>B : Symbol(B, Decl(c.ts, 1, 6)) + +let a: A.F +>a : Symbol(a, Decl(c.ts, 3, 3)) +>A : Symbol(A, Decl(c.ts, 0, 6)) +>F : Symbol(A.F, Decl(a.ts, 0, 0)) + +let b: B.F +>b : Symbol(b, Decl(c.ts, 4, 3)) +>B : Symbol(B, Decl(c.ts, 1, 6)) +>F : Symbol(B.F, Decl(b.ts, 0, 0)) + +if (a === b) { +>a : Symbol(a, Decl(c.ts, 3, 3)) +>b : Symbol(b, Decl(c.ts, 4, 3)) + +} + +a = b +>a : Symbol(a, Decl(c.ts, 3, 3)) +>b : Symbol(b, Decl(c.ts, 4, 3)) + diff --git a/tests/baselines/reference/errorWithSameNameType.types b/tests/baselines/reference/errorWithSameNameType.types new file mode 100644 index 0000000000000..472f9d1e81870 --- /dev/null +++ b/tests/baselines/reference/errorWithSameNameType.types @@ -0,0 +1,39 @@ +=== tests/cases/compiler/a.ts === +export interface F { + foo1: number +>foo1 : number +} + +=== tests/cases/compiler/b.ts === +export interface F { + foo2: number +>foo2 : number +} + +=== tests/cases/compiler/c.ts === +import * as A from './a' +>A : typeof A + +import * as B from './b' +>B : typeof B + +let a: A.F +>a : A.F +>A : any + +let b: B.F +>b : B.F +>B : any + +if (a === b) { +>a === b : boolean +>a : A.F +>b : B.F + +} + +a = b +>a = b : B.F +>a : A.F +>b : B.F + diff --git a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt index 5b8e83b3cca54..d7b992f2c1607 100644 --- a/tests/baselines/reference/es6ExportEqualsInterop.errors.txt +++ b/tests/baselines/reference/es6ExportEqualsInterop.errors.txt @@ -1,16 +1,16 @@ tests/cases/compiler/main.ts(15,1): error TS2693: 'z1' only refers to a type, but is being used as a value here. tests/cases/compiler/main.ts(21,4): error TS2339: Property 'a' does not exist on type '() => any'. tests/cases/compiler/main.ts(23,4): error TS2339: Property 'a' does not exist on type 'typeof Foo'. -tests/cases/compiler/main.ts(27,8): error TS1192: Module '"interface"' has no default export. -tests/cases/compiler/main.ts(28,8): error TS1192: Module '"variable"' has no default export. -tests/cases/compiler/main.ts(29,8): error TS1192: Module '"interface-variable"' has no default export. -tests/cases/compiler/main.ts(30,8): error TS1192: Module '"module"' has no default export. -tests/cases/compiler/main.ts(31,8): error TS1192: Module '"interface-module"' has no default export. -tests/cases/compiler/main.ts(32,8): error TS1192: Module '"variable-module"' has no default export. -tests/cases/compiler/main.ts(33,8): error TS1192: Module '"function"' has no default export. -tests/cases/compiler/main.ts(34,8): error TS1192: Module '"function-module"' has no default export. -tests/cases/compiler/main.ts(35,8): error TS1192: Module '"class"' has no default export. -tests/cases/compiler/main.ts(36,8): error TS1192: Module '"class-module"' has no default export. +tests/cases/compiler/main.ts(27,8): error TS1259: Module '"interface"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(28,8): error TS1259: Module '"variable"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(29,8): error TS1259: Module '"interface-variable"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(30,8): error TS1259: Module '"module"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(31,8): error TS1259: Module '"interface-module"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(32,8): error TS1259: Module '"variable-module"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(33,8): error TS1259: Module '"function"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(34,8): error TS1259: Module '"function-module"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(35,8): error TS1259: Module '"class"' can only be default-imported using the 'esModuleInterop' flag +tests/cases/compiler/main.ts(36,8): error TS1259: Module '"class-module"' can only be default-imported using the 'esModuleInterop' flag tests/cases/compiler/main.ts(39,21): error TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export. tests/cases/compiler/main.ts(45,21): error TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export. tests/cases/compiler/main.ts(47,21): error TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export. @@ -76,34 +76,44 @@ tests/cases/compiler/main.ts(106,15): error TS2498: Module '"class-module"' uses // default import import x1 from "interface"; ~~ -!!! error TS1192: Module '"interface"' has no default export. +!!! error TS1259: Module '"interface"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:6:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x2 from "variable"; ~~ -!!! error TS1192: Module '"variable"' has no default export. +!!! error TS1259: Module '"variable"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:14:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x3 from "interface-variable"; ~~ -!!! error TS1192: Module '"interface-variable"' has no default export. +!!! error TS1259: Module '"interface-variable"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:26:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x4 from "module"; ~~ -!!! error TS1192: Module '"module"' has no default export. +!!! error TS1259: Module '"module"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:34:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x5 from "interface-module"; ~~ -!!! error TS1192: Module '"interface-module"' has no default export. +!!! error TS1259: Module '"interface-module"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:46:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x6 from "variable-module"; ~~ -!!! error TS1192: Module '"variable-module"' has no default export. +!!! error TS1259: Module '"variable-module"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:60:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x7 from "function"; ~~ -!!! error TS1192: Module '"function"' has no default export. +!!! error TS1259: Module '"function"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:65:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x8 from "function-module"; ~~ -!!! error TS1192: Module '"function-module"' has no default export. +!!! error TS1259: Module '"function-module"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:74:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x9 from "class"; ~~ -!!! error TS1192: Module '"class"' has no default export. +!!! error TS1259: Module '"class"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:82:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. import x0 from "class-module"; ~~ -!!! error TS1192: Module '"class-module"' has no default export. +!!! error TS1259: Module '"class-module"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/modules.d.ts:94:5: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. // namespace import import * as y1 from "interface"; diff --git a/tests/baselines/reference/es6ImportDefaultBindingInEs5.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingInEs5.errors.txt index 604b27fd9c2b6..924792bf98adf 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingInEs5.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingInEs5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/es6ImportDefaultBindingInEs5_1.ts(1,8): error TS1192: Module '"tests/cases/compiler/es6ImportDefaultBindingInEs5_0"' has no default export. +tests/cases/compiler/es6ImportDefaultBindingInEs5_1.ts(1,8): error TS1259: Module '"tests/cases/compiler/es6ImportDefaultBindingInEs5_0"' can only be default-imported using the 'esModuleInterop' flag ==== tests/cases/compiler/es6ImportDefaultBindingInEs5_0.ts (0 errors) ==== @@ -8,4 +8,5 @@ tests/cases/compiler/es6ImportDefaultBindingInEs5_1.ts(1,8): error TS1192: Modul ==== tests/cases/compiler/es6ImportDefaultBindingInEs5_1.ts (1 errors) ==== import defaultBinding from "./es6ImportDefaultBindingInEs5_0"; ~~~~~~~~~~~~~~ -!!! error TS1192: Module '"tests/cases/compiler/es6ImportDefaultBindingInEs5_0"' has no default export. \ No newline at end of file +!!! error TS1259: Module '"tests/cases/compiler/es6ImportDefaultBindingInEs5_0"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 tests/cases/compiler/es6ImportDefaultBindingInEs5_0.ts:2:1: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. \ No newline at end of file diff --git a/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt b/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt index d052166905e38..31848458a87e8 100644 --- a/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt +++ b/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt @@ -19,7 +19,7 @@ tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAnd tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(50,5): error TS2322: Type 'typeof N' is not assignable to type 'typeof M'. Types of property 'A' are incompatible. Type 'typeof N.A' is not assignable to type 'typeof M.A'. - Property 'name' is missing in type 'A' but required in type 'A'. + Property 'name' is missing in type 'N.A' but required in type 'M.A'. tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(51,5): error TS2322: Type 'N.A' is not assignable to type 'M.A'. tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(52,5): error TS2322: Type '(x: number) => boolean' is not assignable to type '(x: number) => string'. Type 'boolean' is not assignable to type 'string'. @@ -114,7 +114,7 @@ tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAnd !!! error TS2322: Type 'typeof N' is not assignable to type 'typeof M'. !!! error TS2322: Types of property 'A' are incompatible. !!! error TS2322: Type 'typeof N.A' is not assignable to type 'typeof M.A'. -!!! error TS2322: Property 'name' is missing in type 'A' but required in type 'A'. +!!! error TS2322: Property 'name' is missing in type 'N.A' but required in type 'M.A'. !!! related TS2728 tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts:20:9: 'name' is declared here. var aClassInModule: M.A = new N.A(); ~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.errors.txt b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.errors.txt new file mode 100644 index 0000000000000..d59ec8b42c86f --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.errors.txt @@ -0,0 +1,15 @@ +/bar.ts(1,1): error TS1203: Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead. +/foo.ts(1,8): error TS1259: Module '"/bar"' can only be default-imported using the 'allowSyntheticDefaultImports' flag + + +==== /bar.ts (1 errors) ==== + export = bar; + ~~~~~~~~~~~~~ +!!! error TS1203: Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead. + function bar() {} + +==== /foo.ts (1 errors) ==== + import bar from './bar'; + ~~~ +!!! error TS1259: Module '"/bar"' can only be default-imported using the 'allowSyntheticDefaultImports' flag +!!! related TS2594 /bar.ts:1:1: This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag. \ No newline at end of file diff --git a/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.js b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.js new file mode 100644 index 0000000000000..5d433cba79b71 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/exportAssignmentWithoutAllowSyntheticDefaultImportsError.ts] //// + +//// [bar.ts] +export = bar; +function bar() {} + +//// [foo.ts] +import bar from './bar'; + +//// [bar.js] +function bar() { } +//// [foo.js] diff --git a/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.symbols b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.symbols new file mode 100644 index 0000000000000..8dca8faecf7a4 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.symbols @@ -0,0 +1,11 @@ +=== /bar.ts === +export = bar; +>bar : Symbol(bar, Decl(bar.ts, 0, 13)) + +function bar() {} +>bar : Symbol(bar, Decl(bar.ts, 0, 13)) + +=== /foo.ts === +import bar from './bar'; +>bar : Symbol(bar, Decl(foo.ts, 0, 6)) + diff --git a/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.types b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.types new file mode 100644 index 0000000000000..d5c22d809c9e1 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithoutAllowSyntheticDefaultImportsError.types @@ -0,0 +1,11 @@ +=== /bar.ts === +export = bar; +>bar : () => void + +function bar() {} +>bar : () => void + +=== /foo.ts === +import bar from './bar'; +>bar : any + diff --git a/tests/baselines/reference/exportDefaultNamespace.js b/tests/baselines/reference/exportDefaultNamespace.js new file mode 100644 index 0000000000000..39a70d5e231d7 --- /dev/null +++ b/tests/baselines/reference/exportDefaultNamespace.js @@ -0,0 +1,24 @@ +//// [exportDefaultNamespace.ts] +export default function someFunc() { + return 'hello!'; +} + +someFunc.someProp = 'yo'; + + +//// [exportDefaultNamespace.js] +"use strict"; +exports.__esModule = true; +function someFunc() { + return 'hello!'; +} +exports["default"] = someFunc; +someFunc.someProp = 'yo'; + + +//// [exportDefaultNamespace.d.ts] +declare function someFunc(): string; +declare namespace someFunc { + var someProp: string; +} +export default someFunc; diff --git a/tests/baselines/reference/exportDefaultNamespace.symbols b/tests/baselines/reference/exportDefaultNamespace.symbols new file mode 100644 index 0000000000000..eee148768948b --- /dev/null +++ b/tests/baselines/reference/exportDefaultNamespace.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/declarationEmit/exportDefaultNamespace.ts === +export default function someFunc() { +>someFunc : Symbol(someFunc, Decl(exportDefaultNamespace.ts, 0, 0), Decl(exportDefaultNamespace.ts, 2, 1)) + + return 'hello!'; +} + +someFunc.someProp = 'yo'; +>someFunc.someProp : Symbol(someFunc.someProp, Decl(exportDefaultNamespace.ts, 2, 1)) +>someFunc : Symbol(someFunc, Decl(exportDefaultNamespace.ts, 0, 0), Decl(exportDefaultNamespace.ts, 2, 1)) +>someProp : Symbol(someFunc.someProp, Decl(exportDefaultNamespace.ts, 2, 1)) + diff --git a/tests/baselines/reference/exportDefaultNamespace.types b/tests/baselines/reference/exportDefaultNamespace.types new file mode 100644 index 0000000000000..eebf33f51f4db --- /dev/null +++ b/tests/baselines/reference/exportDefaultNamespace.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/declarationEmit/exportDefaultNamespace.ts === +export default function someFunc() { +>someFunc : typeof someFunc + + return 'hello!'; +>'hello!' : "hello!" +} + +someFunc.someProp = 'yo'; +>someFunc.someProp = 'yo' : "yo" +>someFunc.someProp : string +>someFunc : typeof someFunc +>someProp : string +>'yo' : "yo" + diff --git a/tests/baselines/reference/expr.errors.txt b/tests/baselines/reference/expr.errors.txt index 5acfd691d586e..e1d6a9e4d451b 100644 --- a/tests/baselines/reference/expr.errors.txt +++ b/tests/baselines/reference/expr.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/expr.ts(87,5): error TS2367: This condition will always return 'false' since the types 'number' and 'string' have no overlap. -tests/cases/compiler/expr.ts(88,5): error TS2367: This condition will always return 'false' since the types 'number' and 'boolean' have no overlap. +tests/cases/compiler/expr.ts(88,5): error TS2367: This condition will always return 'false' since the types 'number' and 'false' have no overlap. tests/cases/compiler/expr.ts(94,5): error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. -tests/cases/compiler/expr.ts(95,5): error TS2367: This condition will always return 'false' since the types 'string' and 'boolean' have no overlap. +tests/cases/compiler/expr.ts(95,5): error TS2367: This condition will always return 'false' since the types 'string' and 'false' have no overlap. tests/cases/compiler/expr.ts(98,5): error TS2367: This condition will always return 'false' since the types 'string' and 'E' have no overlap. tests/cases/compiler/expr.ts(115,5): error TS2367: This condition will always return 'false' since the types 'E' and 'string' have no overlap. tests/cases/compiler/expr.ts(116,5): error TS2367: This condition will always return 'false' since the types 'E' and 'false' have no overlap. @@ -161,7 +161,7 @@ tests/cases/compiler/expr.ts(242,7): error TS2363: The right-hand side of an ari !!! error TS2367: This condition will always return 'false' since the types 'number' and 'string' have no overlap. n==b; ~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'number' and 'boolean' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types 'number' and 'false' have no overlap. n==i; n==n; n==e; @@ -172,7 +172,7 @@ tests/cases/compiler/expr.ts(242,7): error TS2363: The right-hand side of an ari !!! error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. s==b; ~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'string' and 'boolean' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types 'string' and 'false' have no overlap. s==i; s==s; s==e; diff --git a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt index 568412b563b66..3ba7a73367f8a 100644 --- a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt +++ b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(4,16): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(5,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. -tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(6,9): error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. +tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(6,9): error TS2367: This condition will always return 'false' since the types 'string' and '1' have no overlap. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(8,16): error TS2339: Property 'unknownProperty' does not exist on type 'string'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(12,10): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'string'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(16,10): error TS2403: Subsequent variable declarations must have the same type. Variable 'j' must be of type 'any', but here has type 'string'. @@ -18,7 +18,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors. !!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. if (x === 1) { ~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types 'string' and '1' have no overlap. } let a3 = x.unknownProperty; ~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/for-of10.errors.txt b/tests/baselines/reference/for-of10.errors.txt index 724b02dce6959..1636f1a02d045 100644 --- a/tests/baselines/reference/for-of10.errors.txt +++ b/tests/baselines/reference/for-of10.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/for-ofStatements/for-of10.ts(2,12): error TS2322: Type 'number' is not assignable to type 'string'. +tests/cases/conformance/es6/for-ofStatements/for-of10.ts(2,6): error TS2322: Type 'number' is not assignable to type 'string'. ==== tests/cases/conformance/es6/for-ofStatements/for-of10.ts (1 errors) ==== var v: string; for (v of [0]) { } - ~ + ~ !!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/for-of11.errors.txt b/tests/baselines/reference/for-of11.errors.txt index 9872108143394..dc527e73efe2b 100644 --- a/tests/baselines/reference/for-of11.errors.txt +++ b/tests/baselines/reference/for-of11.errors.txt @@ -1,8 +1,10 @@ -tests/cases/conformance/es6/for-ofStatements/for-of11.ts(2,12): error TS2322: Type 'number' is not assignable to type 'string'. +tests/cases/conformance/es6/for-ofStatements/for-of11.ts(2,6): error TS2322: Type 'string | number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. ==== tests/cases/conformance/es6/for-ofStatements/for-of11.ts (1 errors) ==== var v: string; for (v of [0, ""]) { } - ~ -!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file + ~ +!!! error TS2322: Type 'string | number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/functionLikeInParameterInitializer.errors.txt b/tests/baselines/reference/functionLikeInParameterInitializer.errors.txt deleted file mode 100644 index b6ae78623b8d6..0000000000000 --- a/tests/baselines/reference/functionLikeInParameterInitializer.errors.txt +++ /dev/null @@ -1,34 +0,0 @@ -tests/cases/compiler/functionLikeInParameterInitializer.ts(2,34): error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. -tests/cases/compiler/functionLikeInParameterInitializer.ts(6,44): error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. -tests/cases/compiler/functionLikeInParameterInitializer.ts(11,50): error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. -tests/cases/compiler/functionLikeInParameterInitializer.ts(16,41): error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. - - -==== tests/cases/compiler/functionLikeInParameterInitializer.ts (4 errors) ==== - // error - export function bar(func = () => foo) { - ~~~ -!!! error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. - let foo = "in"; - } - // error - export function baz1(func = { f() { return foo } }) { - ~~~ -!!! error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. - let foo = "in"; - } - - // error - export function baz2(func = function () { return foo }) { - ~~~ -!!! error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. - let foo = "in"; - } - - // error - export function baz3(func = class { x = foo }) { - ~~~ -!!! error TS2373: Initializer of parameter 'func' cannot reference identifier 'foo' declared after it. - let foo = "in"; - } - \ No newline at end of file diff --git a/tests/baselines/reference/generateTypes/global.d.ts b/tests/baselines/reference/generateTypes/global.d.ts deleted file mode 100644 index 000e38953a228..0000000000000 --- a/tests/baselines/reference/generateTypes/global.d.ts +++ /dev/null @@ -1,236 +0,0 @@ -export class Array { - static from(p0: any): any; - static isArray(p0: any): any; - static of(): any; - concat(p0: any): any; - copyWithin(p0: any, p1: any): any; - entries(): any; - every(p0: any): any; - fill(p0: any): any; - filter(p0: any): any; - find(p0: any): any; - findIndex(p0: any): any; - forEach(p0: any): any; - includes(p0: any): any; - indexOf(p0: any): any; - join(p0: any): any; - keys(): any; - lastIndexOf(p0: any): any; - map(p0: any): any; - pop(): any; - push(p0: any): any; - reduce(p0: any): any; - reduceRight(p0: any): any; - reverse(): any; - shift(): any; - slice(p0: any, p1: any): any; - some(p0: any): any; - sort(p0: any): any; - splice(p0: any, p1: any): any; - toLocaleString(): any; - unshift(p0: any): any; -} -export class Boolean { - constructor(p0: any); - valueOf(): any; -} -export class Date { - static UTC(p0: any, p1: any, p2: any, p3: any, p4: any, p5: any, p6: any): any; - static now(): any; - static parse(p0: any): any; - constructor(p0: any, p1: any, p2: any, p3: any, p4: any, p5: any, p6: any); - getDate(): any; - getDay(): any; - getFullYear(): any; - getHours(): any; - getMilliseconds(): any; - getMinutes(): any; - getMonth(): any; - getSeconds(): any; - getTime(): any; - getTimezoneOffset(): any; - getUTCDate(): any; - getUTCDay(): any; - getUTCFullYear(): any; - getUTCHours(): any; - getUTCMilliseconds(): any; - getUTCMinutes(): any; - getUTCMonth(): any; - getUTCSeconds(): any; - getYear(): any; - setDate(p0: any): any; - setFullYear(p0: any, p1: any, p2: any): any; - setHours(p0: any, p1: any, p2: any, p3: any): any; - setMilliseconds(p0: any): any; - setMinutes(p0: any, p1: any, p2: any): any; - setMonth(p0: any, p1: any): any; - setSeconds(p0: any, p1: any): any; - setTime(p0: any): any; - setUTCDate(p0: any): any; - setUTCFullYear(p0: any, p1: any, p2: any): any; - setUTCHours(p0: any, p1: any, p2: any, p3: any): any; - setUTCMilliseconds(p0: any): any; - setUTCMinutes(p0: any, p1: any, p2: any): any; - setUTCMonth(p0: any, p1: any): any; - setUTCSeconds(p0: any, p1: any): any; - setYear(p0: any): any; - toDateString(): any; - toGMTString(): any; - toISOString(): any; - toJSON(p0: any): any; - toLocaleDateString(): any; - toLocaleString(): any; - toLocaleTimeString(): any; - toTimeString(): any; - toUTCString(): any; - valueOf(): any; -} -export namespace Math { - const E: number; - const LN10: number; - const LN2: number; - const LOG10E: number; - const LOG2E: number; - const PI: number; - const SQRT1_2: number; - const SQRT2: number; - function abs(p0: any): any; - function acos(p0: any): any; - function acosh(p0: any): any; - function asin(p0: any): any; - function asinh(p0: any): any; - function atan(p0: any): any; - function atan2(p0: any, p1: any): any; - function atanh(p0: any): any; - function cbrt(p0: any): any; - function ceil(p0: any): any; - function clz32(p0: any): any; - function cos(p0: any): any; - function cosh(p0: any): any; - function exp(p0: any): any; - function expm1(p0: any): any; - function floor(p0: any): any; - function fround(p0: any): any; - function hypot(p0: any, p1: any): any; - function imul(p0: any, p1: any): any; - function log(p0: any): any; - function log10(p0: any): any; - function log1p(p0: any): any; - function log2(p0: any): any; - function max(p0: any, p1: any): any; - function min(p0: any, p1: any): any; - function pow(p0: any, p1: any): any; - function random(): any; - function round(p0: any): any; - function sign(p0: any): any; - function sin(p0: any): any; - function sinh(p0: any): any; - function sqrt(p0: any): any; - function tan(p0: any): any; - function tanh(p0: any): any; - function trunc(p0: any): any; -} -export class Number { - static EPSILON: number; - static MAX_SAFE_INTEGER: number; - static MAX_VALUE: number; - static MIN_SAFE_INTEGER: number; - static MIN_VALUE: number; - static NEGATIVE_INFINITY: number; - static NaN: number; - static POSITIVE_INFINITY: number; - static isFinite(p0: any): any; - static isInteger(p0: any): any; - static isNaN(p0: any): any; - static isSafeInteger(p0: any): any; - static parseFloat(p0: any): any; - static parseInt(p0: any, p1: any): any; - constructor(p0: any); - toExponential(p0: any): any; - toFixed(p0: any): any; - toLocaleString(): any; - toPrecision(p0: any): any; - toString(p0: any): any; - valueOf(): any; -} -export class RegExp { - static $1: any; - static $2: any; - static $3: any; - static $4: any; - static $5: any; - static $6: any; - static $7: any; - static $8: any; - static $9: any; - static $_: any; - static input: any; - static lastMatch: any; - static lastParen: any; - static leftContext: any; - static rightContext: any; - constructor(p0: any, p1: any); - compile(p0: any, p1: any): any; - exec(p0: any): any; - test(p0: any): any; -} -export class String { - static fromCharCode(p0: any): any; - static fromCodePoint(p0: any): any; - static raw(p0: any): any; - anchor(p0: any): any; - big(): any; - blink(): any; - bold(): any; - charAt(p0: any): any; - charCodeAt(p0: any): any; - codePointAt(p0: any): any; - concat(p0: any): any; - endsWith(p0: any): any; - fixed(): any; - fontcolor(p0: any): any; - fontsize(p0: any): any; - includes(p0: any): any; - indexOf(p0: any): any; - italics(): any; - lastIndexOf(p0: any): any; - link(p0: any): any; - localeCompare(p0: any): any; - match(p0: any): any; - normalize(): any; - repeat(p0: any): any; - replace(p0: any, p1: any): any; - search(p0: any): any; - slice(p0: any, p1: any): any; - small(): any; - split(p0: any, p1: any): any; - startsWith(p0: any): any; - strike(): any; - sub(): any; - substr(p0: any, p1: any): any; - substring(p0: any, p1: any): any; - sup(): any; - toLocaleLowerCase(): any; - toLocaleUpperCase(): any; - toLowerCase(): any; - toUpperCase(): any; - trim(): any; - trimLeft(): any; - trimRight(): any; - valueOf(): any; -} -export class Symbol { - static hasInstance: symbol; - static isConcatSpreadable: symbol; - static iterator: symbol; - static keyFor(p0: any): any; - static match: symbol; - static replace: symbol; - static search: symbol; - static species: symbol; - static split: symbol; - static toPrimitive: symbol; - static toStringTag: symbol; - static unscopables: symbol; - valueOf(): any; -} diff --git a/tests/baselines/reference/generateTypes/lodash.d.ts b/tests/baselines/reference/generateTypes/lodash.d.ts deleted file mode 100644 index ff729b36320be..0000000000000 --- a/tests/baselines/reference/generateTypes/lodash.d.ts +++ /dev/null @@ -1,668 +0,0 @@ -export = example; -declare class example { - static VERSION: string; - static add(value: any, other: any): any; - static after(n: any, func: any): any; - static ary(func: any, n: any, guard: any): any; - static assign(...args: any[]): any; - static assignIn(...args: any[]): any; - static assignInWith(...args: any[]): any; - static assignWith(...args: any[]): any; - static at(...args: any[]): any; - static attempt(...args: any[]): any; - static before(n: any, func: any): any; - static bindAll(...args: any[]): any; - static camelCase(string: any): any; - static capitalize(string: any): any; - static castArray(...args: any[]): any; - static ceil(number: any, precision: any): any; - static chain(value: any): any; - static chunk(array: any, size: any, guard: any): any; - static clamp(number: any, lower: any, upper: any): any; - static clone(value: any): any; - static cloneDeep(value: any): any; - static cloneDeepWith(value: any, customizer: any): any; - static cloneWith(value: any, customizer: any): any; - static compact(array: any): any; - static concat(...args: any[]): any; - static cond(pairs: any): any; - static conforms(source: any): any; - static conformsTo(object: any, source: any): any; - static constant(value: any): any; - static countBy(collection: any, iteratee: any): any; - static create(prototype: any, properties: any): any; - static debounce(func: any, wait: any, options: any): any; - static deburr(string: any): any; - static defaultTo(value: any, defaultValue: any): any; - static defaults(...args: any[]): any; - static defaultsDeep(...args: any[]): any; - static defer(...args: any[]): any; - static delay(...args: any[]): any; - static difference(...args: any[]): any; - static differenceBy(...args: any[]): any; - static differenceWith(...args: any[]): any; - static divide(value: any, other: any): any; - static drop(array: any, n: any, guard: any): any; - static dropRight(array: any, n: any, guard: any): any; - static dropRightWhile(array: any, predicate: any): any; - static dropWhile(array: any, predicate: any): any; - static each(collection: any, iteratee: any): any; - static eachRight(collection: any, iteratee: any): any; - static endsWith(string: any, target: any, position: any): any; - static entries(object: any): any; - static entriesIn(object: any): any; - static eq(value: any, other: any): any; - static escape(string: any): any; - static escapeRegExp(string: any): any; - static every(collection: any, predicate: any, guard: any): any; - static extend(...args: any[]): any; - static extendWith(...args: any[]): any; - static fill(array: any, value: any, start: any, end: any): any; - static filter(collection: any, predicate: any): any; - static find(collection: any, predicate: any, fromIndex: any): any; - static findIndex(array: any, predicate: any, fromIndex: any): any; - static findKey(object: any, predicate: any): any; - static findLast(collection: any, predicate: any, fromIndex: any): any; - static findLastIndex(array: any, predicate: any, fromIndex: any): any; - static findLastKey(object: any, predicate: any): any; - static first(array: any): any; - static flatMap(collection: any, iteratee: any): any; - static flatMapDeep(collection: any, iteratee: any): any; - static flatMapDepth(collection: any, iteratee: any, depth: any): any; - static flatten(array: any): any; - static flattenDeep(array: any): any; - static flattenDepth(array: any, depth: any): any; - static flip(func: any): any; - static floor(number: any, precision: any): any; - static flow(...args: any[]): any; - static flowRight(...args: any[]): any; - static forEach(collection: any, iteratee: any): any; - static forEachRight(collection: any, iteratee: any): any; - static forIn(object: any, iteratee: any): any; - static forInRight(object: any, iteratee: any): any; - static forOwn(object: any, iteratee: any): any; - static forOwnRight(object: any, iteratee: any): any; - static fromPairs(pairs: any): any; - static functions(object: any): any; - static functionsIn(object: any): any; - static get(object: any, path: any, defaultValue: any): any; - static groupBy(collection: any, iteratee: any): any; - static gt(value: any, other: any): any; - static gte(value: any, other: any): any; - static has(object: any, path: any): any; - static hasIn(object: any, path: any): any; - static head(array: any): any; - static identity(value: any): any; - static inRange(number: any, start: any, end: any): any; - static includes(collection: any, value: any, fromIndex: any, guard: any): any; - static indexOf(array: any, value: any, fromIndex: any): any; - static initial(array: any): any; - static intersection(...args: any[]): any; - static intersectionBy(...args: any[]): any; - static intersectionWith(...args: any[]): any; - static invert(object: any, iteratee: any): any; - static invertBy(object: any, iteratee: any): any; - static invoke(...args: any[]): any; - static invokeMap(...args: any[]): any; - static isArguments(value: any): any; - static isArray(p0: any): any; - static isArrayBuffer(value: any): any; - static isArrayLike(value: any): any; - static isArrayLikeObject(value: any): any; - static isBoolean(value: any): any; - static isBuffer(b: any): any; - static isDate(value: any): any; - static isElement(value: any): any; - static isEmpty(value: any): any; - static isEqual(value: any, other: any): any; - static isEqualWith(value: any, other: any, customizer: any): any; - static isError(value: any): any; - static isFinite(value: any): any; - static isFunction(value: any): any; - static isInteger(value: any): any; - static isLength(value: any): any; - static isMap(value: any): any; - static isMatch(object: any, source: any): any; - static isMatchWith(object: any, source: any, customizer: any): any; - static isNaN(value: any): any; - static isNative(value: any): any; - static isNil(value: any): any; - static isNull(value: any): any; - static isNumber(value: any): any; - static isObject(value: any): any; - static isObjectLike(value: any): any; - static isPlainObject(value: any): any; - static isRegExp(value: any): any; - static isSafeInteger(value: any): any; - static isSet(value: any): any; - static isString(value: any): any; - static isSymbol(value: any): any; - static isTypedArray(value: any): any; - static isUndefined(value: any): any; - static isWeakMap(value: any): any; - static isWeakSet(value: any): any; - static iteratee(func: any): any; - static join(array: any, separator: any): any; - static kebabCase(string: any): any; - static keyBy(collection: any, iteratee: any): any; - static keys(object: any): any; - static keysIn(object: any): any; - static last(array: any): any; - static lastIndexOf(array: any, value: any, fromIndex: any): any; - static lowerCase(string: any): any; - static lowerFirst(string: any): any; - static lt(value: any, other: any): any; - static lte(value: any, other: any): any; - static map(collection: any, iteratee: any): any; - static mapKeys(object: any, iteratee: any): any; - static mapValues(object: any, iteratee: any): any; - static matches(source: any): any; - static matchesProperty(path: any, srcValue: any): any; - static max(array: any): any; - static maxBy(array: any, iteratee: any): any; - static mean(array: any): any; - static meanBy(array: any, iteratee: any): any; - static merge(...args: any[]): any; - static mergeWith(...args: any[]): any; - static method(...args: any[]): any; - static methodOf(...args: any[]): any; - static min(array: any): any; - static minBy(array: any, iteratee: any): any; - static mixin(object: any, source: any, options: any): any; - static multiply(value: any, other: any): any; - static negate(predicate: any): any; - static noConflict(): any; - static noop(): void; - static now(): any; - static nth(array: any, n: any): any; - static nthArg(n: any): any; - static omit(...args: any[]): any; - static omitBy(object: any, predicate: any): any; - static once(func: any): any; - static orderBy(collection: any, iteratees: any, orders: any, guard: any): any; - static over(...args: any[]): any; - static overArgs(...args: any[]): any; - static overEvery(...args: any[]): any; - static overSome(...args: any[]): any; - static pad(string: any, length: any, chars: any): any; - static padEnd(string: any, length: any, chars: any): any; - static padStart(string: any, length: any, chars: any): any; - static parseInt(string: any, radix: any, guard: any): any; - static partition(collection: any, iteratee: any): any; - static pick(...args: any[]): any; - static pickBy(object: any, predicate: any): any; - static property(path: any): any; - static propertyOf(object: any): any; - static pull(...args: any[]): any; - static pullAll(array: any, values: any): any; - static pullAllBy(array: any, values: any, iteratee: any): any; - static pullAllWith(array: any, values: any, comparator: any): any; - static pullAt(...args: any[]): any; - static random(lower: any, upper: any, floating: any): any; - static range(start: any, end: any, step: any): any; - static rangeRight(start: any, end: any, step: any): any; - static rearg(...args: any[]): any; - static reduce(collection: any, iteratee: any, accumulator: any, ...args: any[]): any; - static reduceRight(collection: any, iteratee: any, accumulator: any, ...args: any[]): any; - static reject(collection: any, predicate: any): any; - static remove(array: any, predicate: any): any; - static repeat(string: any, n: any, guard: any): any; - static replace(...args: any[]): any; - static rest(func: any, start: any): any; - static result(object: any, path: any, defaultValue: any): any; - static reverse(array: any): any; - static round(number: any, precision: any): any; - static runInContext(context: any): any; - static sample(collection: any): any; - static sampleSize(collection: any, n: any, guard: any): any; - static set(object: any, path: any, value: any): any; - static setWith(object: any, path: any, value: any, customizer: any): any; - static shuffle(collection: any): any; - static size(collection: any): any; - static slice(array: any, start: any, end: any): any; - static snakeCase(string: any): any; - static some(collection: any, predicate: any, guard: any): any; - static sortBy(...args: any[]): any; - static sortedIndex(array: any, value: any): any; - static sortedIndexBy(array: any, value: any, iteratee: any): any; - static sortedIndexOf(array: any, value: any): any; - static sortedLastIndex(array: any, value: any): any; - static sortedLastIndexBy(array: any, value: any, iteratee: any): any; - static sortedLastIndexOf(array: any, value: any): any; - static sortedUniq(array: any): any; - static sortedUniqBy(array: any, iteratee: any): any; - static split(string: any, separator: any, limit: any): any; - static spread(func: any, start: any): any; - static startCase(string: any): any; - static startsWith(string: any, target: any, position: any): any; - static stubArray(): any; - static stubFalse(): any; - static stubObject(): any; - static stubString(): any; - static stubTrue(): any; - static subtract(value: any, other: any): any; - static sum(array: any): any; - static sumBy(array: any, iteratee: any): any; - static tail(array: any): any; - static take(array: any, n: any, guard: any): any; - static takeRight(array: any, n: any, guard: any): any; - static takeRightWhile(array: any, predicate: any): any; - static takeWhile(array: any, predicate: any): any; - static tap(value: any, interceptor: any): any; - static template(string: any, options: any, guard: any): any; - static templateSettings: { - escape: RegExp; - evaluate: RegExp; - imports: {}; - interpolate: RegExp; - variable: string; - }; - static throttle(func: any, wait: any, options: any): any; - static thru(value: any, interceptor: any): any; - static times(n: any, iteratee: any): any; - static toArray(value: any): any; - static toFinite(value: any): any; - static toInteger(value: any): any; - static toLength(value: any): any; - static toLower(value: any): any; - static toNumber(value: any): any; - static toPairs(object: any): any; - static toPairsIn(object: any): any; - static toPath(value: any): any; - static toPlainObject(value: any): any; - static toSafeInteger(value: any): any; - static toString(value: any): any; - static toUpper(value: any): any; - static transform(object: any, iteratee: any, accumulator: any): any; - static trim(string: any, chars: any, guard: any): any; - static trimEnd(string: any, chars: any, guard: any): any; - static trimStart(string: any, chars: any, guard: any): any; - static truncate(string: any, options: any): any; - static unary(func: any): any; - static unescape(string: any): any; - static union(...args: any[]): any; - static unionBy(...args: any[]): any; - static unionWith(...args: any[]): any; - static uniq(array: any): any; - static uniqBy(array: any, iteratee: any): any; - static uniqWith(array: any, comparator: any): any; - static uniqueId(prefix: any): any; - static unset(object: any, path: any): any; - static unzip(array: any): any; - static unzipWith(array: any, iteratee: any): any; - static update(object: any, path: any, updater: any): any; - static updateWith(object: any, path: any, updater: any, customizer: any): any; - static upperCase(string: any): any; - static upperFirst(string: any): any; - static values(object: any): any; - static valuesIn(object: any): any; - static without(...args: any[]): any; - static words(string: any, pattern: any, guard: any): any; - static wrap(value: any, wrapper: any): any; - static xor(...args: any[]): any; - static xorBy(...args: any[]): any; - static xorWith(...args: any[]): any; - static zip(...args: any[]): any; - static zipObject(props: any, values: any): any; - static zipObjectDeep(props: any, values: any): any; - static zipWith(...args: any[]): any; - constructor(value: any); - add(...args: any[]): any; - after(...args: any[]): any; - ary(...args: any[]): any; - assign(...args: any[]): any; - assignIn(...args: any[]): any; - assignInWith(...args: any[]): any; - assignWith(...args: any[]): any; - at(...args: any[]): any; - attempt(...args: any[]): any; - before(...args: any[]): any; - bind(...args: any[]): any; - bindAll(...args: any[]): any; - bindKey(...args: any[]): any; - camelCase(...args: any[]): any; - capitalize(...args: any[]): any; - castArray(...args: any[]): any; - ceil(...args: any[]): any; - chain(): any; - chunk(...args: any[]): any; - clamp(...args: any[]): any; - clone(...args: any[]): any; - cloneDeep(...args: any[]): any; - cloneDeepWith(...args: any[]): any; - cloneWith(...args: any[]): any; - commit(): any; - compact(...args: any[]): any; - concat(...args: any[]): any; - cond(...args: any[]): any; - conforms(...args: any[]): any; - conformsTo(...args: any[]): any; - constant(...args: any[]): any; - countBy(...args: any[]): any; - create(...args: any[]): any; - curry(...args: any[]): any; - curryRight(...args: any[]): any; - debounce(...args: any[]): any; - deburr(...args: any[]): any; - defaultTo(...args: any[]): any; - defaults(...args: any[]): any; - defaultsDeep(...args: any[]): any; - defer(...args: any[]): any; - delay(...args: any[]): any; - difference(...args: any[]): any; - differenceBy(...args: any[]): any; - differenceWith(...args: any[]): any; - divide(...args: any[]): any; - drop(...args: any[]): any; - dropRight(...args: any[]): any; - dropRightWhile(...args: any[]): any; - dropWhile(...args: any[]): any; - each(...args: any[]): any; - eachRight(...args: any[]): any; - endsWith(...args: any[]): any; - entries(...args: any[]): any; - entriesIn(...args: any[]): any; - eq(...args: any[]): any; - escape(...args: any[]): any; - escapeRegExp(...args: any[]): any; - every(...args: any[]): any; - extend(...args: any[]): any; - extendWith(...args: any[]): any; - fill(...args: any[]): any; - filter(...args: any[]): any; - find(...args: any[]): any; - findIndex(...args: any[]): any; - findKey(...args: any[]): any; - findLast(...args: any[]): any; - findLastIndex(...args: any[]): any; - findLastKey(...args: any[]): any; - first(...args: any[]): any; - flatMap(...args: any[]): any; - flatMapDeep(...args: any[]): any; - flatMapDepth(...args: any[]): any; - flatten(...args: any[]): any; - flattenDeep(...args: any[]): any; - flattenDepth(...args: any[]): any; - flip(...args: any[]): any; - floor(...args: any[]): any; - flow(...args: any[]): any; - flowRight(...args: any[]): any; - forEach(...args: any[]): any; - forEachRight(...args: any[]): any; - forIn(...args: any[]): any; - forInRight(...args: any[]): any; - forOwn(...args: any[]): any; - forOwnRight(...args: any[]): any; - fromPairs(...args: any[]): any; - functions(...args: any[]): any; - functionsIn(...args: any[]): any; - get(...args: any[]): any; - groupBy(...args: any[]): any; - gt(...args: any[]): any; - gte(...args: any[]): any; - has(...args: any[]): any; - hasIn(...args: any[]): any; - head(...args: any[]): any; - identity(...args: any[]): any; - inRange(...args: any[]): any; - includes(...args: any[]): any; - indexOf(...args: any[]): any; - initial(...args: any[]): any; - intersection(...args: any[]): any; - intersectionBy(...args: any[]): any; - intersectionWith(...args: any[]): any; - invert(...args: any[]): any; - invertBy(...args: any[]): any; - invoke(...args: any[]): any; - invokeMap(...args: any[]): any; - isArguments(...args: any[]): any; - isArray(...args: any[]): any; - isArrayBuffer(...args: any[]): any; - isArrayLike(...args: any[]): any; - isArrayLikeObject(...args: any[]): any; - isBoolean(...args: any[]): any; - isBuffer(...args: any[]): any; - isDate(...args: any[]): any; - isElement(...args: any[]): any; - isEmpty(...args: any[]): any; - isEqual(...args: any[]): any; - isEqualWith(...args: any[]): any; - isError(...args: any[]): any; - isFinite(...args: any[]): any; - isFunction(...args: any[]): any; - isInteger(...args: any[]): any; - isLength(...args: any[]): any; - isMap(...args: any[]): any; - isMatch(...args: any[]): any; - isMatchWith(...args: any[]): any; - isNaN(...args: any[]): any; - isNative(...args: any[]): any; - isNil(...args: any[]): any; - isNull(...args: any[]): any; - isNumber(...args: any[]): any; - isObject(...args: any[]): any; - isObjectLike(...args: any[]): any; - isPlainObject(...args: any[]): any; - isRegExp(...args: any[]): any; - isSafeInteger(...args: any[]): any; - isSet(...args: any[]): any; - isString(...args: any[]): any; - isSymbol(...args: any[]): any; - isTypedArray(...args: any[]): any; - isUndefined(...args: any[]): any; - isWeakMap(...args: any[]): any; - isWeakSet(...args: any[]): any; - iteratee(...args: any[]): any; - join(...args: any[]): any; - kebabCase(...args: any[]): any; - keyBy(...args: any[]): any; - keys(...args: any[]): any; - keysIn(...args: any[]): any; - last(...args: any[]): any; - lastIndexOf(...args: any[]): any; - lowerCase(...args: any[]): any; - lowerFirst(...args: any[]): any; - lt(...args: any[]): any; - lte(...args: any[]): any; - map(...args: any[]): any; - mapKeys(...args: any[]): any; - mapValues(...args: any[]): any; - matches(...args: any[]): any; - matchesProperty(...args: any[]): any; - max(...args: any[]): any; - maxBy(...args: any[]): any; - mean(...args: any[]): any; - meanBy(...args: any[]): any; - memoize(...args: any[]): any; - merge(...args: any[]): any; - mergeWith(...args: any[]): any; - method(...args: any[]): any; - methodOf(...args: any[]): any; - min(...args: any[]): any; - minBy(...args: any[]): any; - mixin(...args: any[]): any; - multiply(...args: any[]): any; - negate(...args: any[]): any; - next(): any; - noConflict(...args: any[]): any; - noop(...args: any[]): any; - now(...args: any[]): any; - nth(...args: any[]): any; - nthArg(...args: any[]): any; - omit(...args: any[]): any; - omitBy(...args: any[]): any; - once(...args: any[]): any; - orderBy(...args: any[]): any; - over(...args: any[]): any; - overArgs(...args: any[]): any; - overEvery(...args: any[]): any; - overSome(...args: any[]): any; - pad(...args: any[]): any; - padEnd(...args: any[]): any; - padStart(...args: any[]): any; - parseInt(...args: any[]): any; - partial(...args: any[]): any; - partialRight(...args: any[]): any; - partition(...args: any[]): any; - pick(...args: any[]): any; - pickBy(...args: any[]): any; - plant(value: any): any; - pop(...args: any[]): any; - property(...args: any[]): any; - propertyOf(...args: any[]): any; - pull(...args: any[]): any; - pullAll(...args: any[]): any; - pullAllBy(...args: any[]): any; - pullAllWith(...args: any[]): any; - pullAt(...args: any[]): any; - push(...args: any[]): any; - random(...args: any[]): any; - range(...args: any[]): any; - rangeRight(...args: any[]): any; - rearg(...args: any[]): any; - reduce(...args: any[]): any; - reduceRight(...args: any[]): any; - reject(...args: any[]): any; - remove(...args: any[]): any; - repeat(...args: any[]): any; - replace(...args: any[]): any; - rest(...args: any[]): any; - result(...args: any[]): any; - reverse(): any; - round(...args: any[]): any; - runInContext(...args: any[]): any; - sample(...args: any[]): any; - sampleSize(...args: any[]): any; - set(...args: any[]): any; - setWith(...args: any[]): any; - shift(...args: any[]): any; - shuffle(...args: any[]): any; - size(...args: any[]): any; - slice(...args: any[]): any; - snakeCase(...args: any[]): any; - some(...args: any[]): any; - sort(...args: any[]): any; - sortBy(...args: any[]): any; - sortedIndex(...args: any[]): any; - sortedIndexBy(...args: any[]): any; - sortedIndexOf(...args: any[]): any; - sortedLastIndex(...args: any[]): any; - sortedLastIndexBy(...args: any[]): any; - sortedLastIndexOf(...args: any[]): any; - sortedUniq(...args: any[]): any; - sortedUniqBy(...args: any[]): any; - splice(...args: any[]): any; - split(...args: any[]): any; - spread(...args: any[]): any; - startCase(...args: any[]): any; - startsWith(...args: any[]): any; - stubArray(...args: any[]): any; - stubFalse(...args: any[]): any; - stubObject(...args: any[]): any; - stubString(...args: any[]): any; - stubTrue(...args: any[]): any; - subtract(...args: any[]): any; - sum(...args: any[]): any; - sumBy(...args: any[]): any; - tail(...args: any[]): any; - take(...args: any[]): any; - takeRight(...args: any[]): any; - takeRightWhile(...args: any[]): any; - takeWhile(...args: any[]): any; - tap(...args: any[]): any; - template(...args: any[]): any; - throttle(...args: any[]): any; - thru(...args: any[]): any; - times(...args: any[]): any; - toArray(...args: any[]): any; - toFinite(...args: any[]): any; - toInteger(...args: any[]): any; - toJSON(): any; - toLength(...args: any[]): any; - toLower(...args: any[]): any; - toNumber(...args: any[]): any; - toPairs(...args: any[]): any; - toPairsIn(...args: any[]): any; - toPath(...args: any[]): any; - toPlainObject(...args: any[]): any; - toSafeInteger(...args: any[]): any; - toUpper(...args: any[]): any; - transform(...args: any[]): any; - trim(...args: any[]): any; - trimEnd(...args: any[]): any; - trimStart(...args: any[]): any; - truncate(...args: any[]): any; - unary(...args: any[]): any; - unescape(...args: any[]): any; - union(...args: any[]): any; - unionBy(...args: any[]): any; - unionWith(...args: any[]): any; - uniq(...args: any[]): any; - uniqBy(...args: any[]): any; - uniqWith(...args: any[]): any; - uniqueId(...args: any[]): any; - unset(...args: any[]): any; - unshift(...args: any[]): any; - unzip(...args: any[]): any; - unzipWith(...args: any[]): any; - update(...args: any[]): any; - updateWith(...args: any[]): any; - upperCase(...args: any[]): any; - upperFirst(...args: any[]): any; - value(): any; - valueOf(): any; - values(...args: any[]): any; - valuesIn(...args: any[]): any; - without(...args: any[]): any; - words(...args: any[]): any; - wrap(...args: any[]): any; - xor(...args: any[]): any; - xorBy(...args: any[]): any; - xorWith(...args: any[]): any; - zip(...args: any[]): any; - zipObject(...args: any[]): any; - zipObjectDeep(...args: any[]): any; - zipWith(...args: any[]): any; -} -declare namespace example { - function bind(...args: any[]): any; - namespace bind { - // Circular reference from example.bind - const placeholder: any; - } - function bindKey(...args: any[]): any; - namespace bindKey { - // Circular reference from example.bindKey - const placeholder: any; - } - function curry(func: any, arity: any, guard: any): any; - namespace curry { - // Circular reference from example.curry - const placeholder: any; - } - function curryRight(func: any, arity: any, guard: any): any; - namespace curryRight { - // Circular reference from example.curryRight - const placeholder: any; - } - function memoize(func: any, resolver: any): any; - namespace memoize { - class Cache { - constructor(entries: any); - clear(): void; - get(key: any): any; - has(key: any): any; - set(key: any, value: any): any; - } - } - function partial(...args: any[]): any; - namespace partial { - // Circular reference from example.partial - const placeholder: any; - } - function partialRight(...args: any[]): any; - namespace partialRight { - // Circular reference from example.partialRight - const placeholder: any; - } -} diff --git a/tests/baselines/reference/genericIndexedAccessMethodIntersectionCanBeAccessed.types b/tests/baselines/reference/genericIndexedAccessMethodIntersectionCanBeAccessed.types index d16a75912f491..f5d2f78e0f6c7 100644 --- a/tests/baselines/reference/genericIndexedAccessMethodIntersectionCanBeAccessed.types +++ b/tests/baselines/reference/genericIndexedAccessMethodIntersectionCanBeAccessed.types @@ -32,9 +32,9 @@ export const createService = ( >Object.keys(ServiceCtr).forEach(key => { const method = (ServiceCtr)[key as keyof T]; const {__$daemonMode, __$action, id} = method; }) : void >Object.keys(ServiceCtr).forEach : (callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void >Object.keys(ServiceCtr) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : (o: object) => string[] >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : (o: object) => string[] >ServiceCtr : ExtendedService & Service >forEach : (callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void >key => { const method = (ServiceCtr)[key as keyof T]; const {__$daemonMode, __$action, id} = method; } : (key: string) => void diff --git a/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.js b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.js new file mode 100644 index 0000000000000..e74990005dbde --- /dev/null +++ b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.js @@ -0,0 +1,41 @@ +//// [tests/cases/compiler/importTypeGenericArrowTypeParenthesized.ts] //// + +//// [module.d.ts] +declare module "module" { + export interface Modifier { } + + export function fn(x: T): Modifier; +} +//// [index.ts] +import { fn } from "module"; + +export const fail1 = fn((x: T): T => x); +export const fail2 = fn(function(x: T): T { + return x; +}); + +export const works1 = fn((x: number) => x); +type MakeItWork = (x: T) => T; +export const works2 = fn(x => x); + + +//// [index.js] +"use strict"; +exports.__esModule = true; +var module_1 = require("module"); +exports.fail1 = module_1.fn(function (x) { return x; }); +exports.fail2 = module_1.fn(function (x) { + return x; +}); +exports.works1 = module_1.fn(function (x) { return x; }); +exports.works2 = module_1.fn(function (x) { return x; }); + + +//// [index.d.ts] +/// +export declare const fail1: import("module").Modifier<((x: T) => T)>; +export declare const fail2: import("module").Modifier<((x: T) => T)>; +export declare const works1: import("module").Modifier<(x: number) => number>; +declare type MakeItWork = (x: T) => T; +export declare const works2: import("module").Modifier; +export {}; diff --git a/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.symbols b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.symbols new file mode 100644 index 0000000000000..b6d30bcb8ad25 --- /dev/null +++ b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.symbols @@ -0,0 +1,62 @@ +=== tests/cases/compiler/module.d.ts === +declare module "module" { +>"module" : Symbol("module", Decl(module.d.ts, 0, 0)) + + export interface Modifier { } +>Modifier : Symbol(Modifier, Decl(module.d.ts, 0, 25)) +>T : Symbol(T, Decl(module.d.ts, 1, 30)) + + export function fn(x: T): Modifier; +>fn : Symbol(fn, Decl(module.d.ts, 1, 36)) +>T : Symbol(T, Decl(module.d.ts, 3, 23)) +>x : Symbol(x, Decl(module.d.ts, 3, 26)) +>T : Symbol(T, Decl(module.d.ts, 3, 23)) +>Modifier : Symbol(Modifier, Decl(module.d.ts, 0, 25)) +>T : Symbol(T, Decl(module.d.ts, 3, 23)) +} +=== tests/cases/compiler/index.ts === +import { fn } from "module"; +>fn : Symbol(fn, Decl(index.ts, 0, 8)) + +export const fail1 = fn((x: T): T => x); +>fail1 : Symbol(fail1, Decl(index.ts, 2, 12)) +>fn : Symbol(fn, Decl(index.ts, 0, 8)) +>T : Symbol(T, Decl(index.ts, 2, 25)) +>x : Symbol(x, Decl(index.ts, 2, 28)) +>T : Symbol(T, Decl(index.ts, 2, 25)) +>T : Symbol(T, Decl(index.ts, 2, 25)) +>x : Symbol(x, Decl(index.ts, 2, 28)) + +export const fail2 = fn(function(x: T): T { +>fail2 : Symbol(fail2, Decl(index.ts, 3, 12)) +>fn : Symbol(fn, Decl(index.ts, 0, 8)) +>T : Symbol(T, Decl(index.ts, 3, 33)) +>x : Symbol(x, Decl(index.ts, 3, 36)) +>T : Symbol(T, Decl(index.ts, 3, 33)) +>T : Symbol(T, Decl(index.ts, 3, 33)) + + return x; +>x : Symbol(x, Decl(index.ts, 3, 36)) + +}); + +export const works1 = fn((x: number) => x); +>works1 : Symbol(works1, Decl(index.ts, 7, 12)) +>fn : Symbol(fn, Decl(index.ts, 0, 8)) +>x : Symbol(x, Decl(index.ts, 7, 26)) +>x : Symbol(x, Decl(index.ts, 7, 26)) + +type MakeItWork = (x: T) => T; +>MakeItWork : Symbol(MakeItWork, Decl(index.ts, 7, 43)) +>T : Symbol(T, Decl(index.ts, 8, 19)) +>x : Symbol(x, Decl(index.ts, 8, 22)) +>T : Symbol(T, Decl(index.ts, 8, 19)) +>T : Symbol(T, Decl(index.ts, 8, 19)) + +export const works2 = fn(x => x); +>works2 : Symbol(works2, Decl(index.ts, 9, 12)) +>fn : Symbol(fn, Decl(index.ts, 0, 8)) +>MakeItWork : Symbol(MakeItWork, Decl(index.ts, 7, 43)) +>x : Symbol(x, Decl(index.ts, 9, 37)) +>x : Symbol(x, Decl(index.ts, 9, 37)) + diff --git a/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.types b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.types new file mode 100644 index 0000000000000..1da9f5906973f --- /dev/null +++ b/tests/baselines/reference/importTypeGenericArrowTypeParenthesized.types @@ -0,0 +1,54 @@ +=== tests/cases/compiler/module.d.ts === +declare module "module" { +>"module" : typeof import("module") + + export interface Modifier { } + + export function fn(x: T): Modifier; +>fn : (x: T) => Modifier +>x : T +} +=== tests/cases/compiler/index.ts === +import { fn } from "module"; +>fn : (x: T) => import("module").Modifier + +export const fail1 = fn((x: T): T => x); +>fail1 : import("module").Modifier<((x: T) => T)> +>fn((x: T): T => x) : import("module").Modifier<((x: T) => T)> +>fn : (x: T) => import("module").Modifier +>(x: T): T => x : (x: T) => T +>x : T +>x : T + +export const fail2 = fn(function(x: T): T { +>fail2 : import("module").Modifier<((x: T) => T)> +>fn(function(x: T): T { return x;}) : import("module").Modifier<((x: T) => T)> +>fn : (x: T) => import("module").Modifier +>function(x: T): T { return x;} : (x: T) => T +>x : T + + return x; +>x : T + +}); + +export const works1 = fn((x: number) => x); +>works1 : import("module").Modifier<(x: number) => number> +>fn((x: number) => x) : import("module").Modifier<(x: number) => number> +>fn : (x: T) => import("module").Modifier +>(x: number) => x : (x: number) => number +>x : number +>x : number + +type MakeItWork = (x: T) => T; +>MakeItWork : MakeItWork +>x : T + +export const works2 = fn(x => x); +>works2 : import("module").Modifier +>fn(x => x) : import("module").Modifier +>fn : (x: T) => import("module").Modifier +>x => x : (x: T) => T +>x : T +>x : T + diff --git a/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.errors.txt b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.errors.txt new file mode 100644 index 0000000000000..4c40245d8da55 --- /dev/null +++ b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.errors.txt @@ -0,0 +1,7 @@ +tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts(1,36): error TS2307: Cannot find module 'module'. + + +==== tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts (1 errors) ==== + export declare const fail1: import("module").Modifier<(x: T) => T>; // shouldn't be a parse error + ~~~~~~~~ +!!! error TS2307: Cannot find module 'module'. \ No newline at end of file diff --git a/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.js b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.js new file mode 100644 index 0000000000000..2ff17635dbc4d --- /dev/null +++ b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.js @@ -0,0 +1,6 @@ +//// [importTypeWithUnparenthesizedGenericFunctionParsed.ts] +export declare const fail1: import("module").Modifier<(x: T) => T>; // shouldn't be a parse error + +//// [importTypeWithUnparenthesizedGenericFunctionParsed.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.symbols b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.symbols new file mode 100644 index 0000000000000..33c9bdfb0ed3c --- /dev/null +++ b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.symbols @@ -0,0 +1,8 @@ +=== tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts === +export declare const fail1: import("module").Modifier<(x: T) => T>; // shouldn't be a parse error +>fail1 : Symbol(fail1, Decl(importTypeWithUnparenthesizedGenericFunctionParsed.ts, 0, 20)) +>T : Symbol(T, Decl(importTypeWithUnparenthesizedGenericFunctionParsed.ts, 0, 55)) +>x : Symbol(x, Decl(importTypeWithUnparenthesizedGenericFunctionParsed.ts, 0, 58)) +>T : Symbol(T, Decl(importTypeWithUnparenthesizedGenericFunctionParsed.ts, 0, 55)) +>T : Symbol(T, Decl(importTypeWithUnparenthesizedGenericFunctionParsed.ts, 0, 55)) + diff --git a/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.types b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.types new file mode 100644 index 0000000000000..6a0ae0401cd77 --- /dev/null +++ b/tests/baselines/reference/importTypeWithUnparenthesizedGenericFunctionParsed.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts === +export declare const fail1: import("module").Modifier<(x: T) => T>; // shouldn't be a parse error +>fail1 : any +>x : T + diff --git a/tests/baselines/reference/incompleteObjectLiteral1.errors.txt b/tests/baselines/reference/incompleteObjectLiteral1.errors.txt index 9122063302e4f..453ba9da5893f 100644 --- a/tests/baselines/reference/incompleteObjectLiteral1.errors.txt +++ b/tests/baselines/reference/incompleteObjectLiteral1.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/incompleteObjectLiteral1.ts(1,12): error TS2304: Cannot find name 'aa'. +tests/cases/compiler/incompleteObjectLiteral1.ts(1,12): error TS18004: No value exists in scope for the shorthand property 'aa'. Either declare one or provide an initializer. tests/cases/compiler/incompleteObjectLiteral1.ts(1,14): error TS1005: ',' expected. ==== tests/cases/compiler/incompleteObjectLiteral1.ts (2 errors) ==== var tt = { aa; } ~~ -!!! error TS2304: Cannot find name 'aa'. +!!! error TS18004: No value exists in scope for the shorthand property 'aa'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. var x = tt; \ No newline at end of file diff --git a/tests/baselines/reference/indexerConstraints2.errors.txt b/tests/baselines/reference/indexerConstraints2.errors.txt index 7e104e77f9865..aca2af28adc12 100644 --- a/tests/baselines/reference/indexerConstraints2.errors.txt +++ b/tests/baselines/reference/indexerConstraints2.errors.txt @@ -9,9 +9,10 @@ tests/cases/compiler/indexerConstraints2.ts(58,6): error TS1023: An index signat tests/cases/compiler/indexerConstraints2.ts(64,6): error TS1023: An index signature parameter type must be 'string' or 'number'. tests/cases/compiler/indexerConstraints2.ts(70,6): error TS1023: An index signature parameter type must be 'string' or 'number'. tests/cases/compiler/indexerConstraints2.ts(74,6): error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. +tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[key: string]: any' instead. -==== tests/cases/compiler/indexerConstraints2.ts (11 errors) ==== +==== tests/cases/compiler/indexerConstraints2.ts (12 errors) ==== class A { a: number; } class B extends A { b: number; } @@ -108,4 +109,12 @@ tests/cases/compiler/indexerConstraints2.ts(74,6): error TS1337: An index signat [u: "foo" | "bar"]: A; ~ !!! error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. - } \ No newline at end of file + } + + type Key = string; + interface T { + [key: Key] + ~~~ +!!! error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[key: string]: any' instead. + } + \ No newline at end of file diff --git a/tests/baselines/reference/indexerConstraints2.js b/tests/baselines/reference/indexerConstraints2.js index 95d9425519525..634be50d22b76 100644 --- a/tests/baselines/reference/indexerConstraints2.js +++ b/tests/baselines/reference/indexerConstraints2.js @@ -73,7 +73,13 @@ interface R { interface S { [u: "foo" | "bar"]: A; -} +} + +type Key = string; +interface T { + [key: Key] +} + //// [indexerConstraints2.js] var __extends = (this && this.__extends) || (function () { diff --git a/tests/baselines/reference/indexerConstraints2.symbols b/tests/baselines/reference/indexerConstraints2.symbols index 4cb5558a8cea5..b2c90f0c1d29d 100644 --- a/tests/baselines/reference/indexerConstraints2.symbols +++ b/tests/baselines/reference/indexerConstraints2.symbols @@ -155,3 +155,15 @@ interface S { >u : Symbol(u, Decl(indexerConstraints2.ts, 73, 5)) >A : Symbol(A, Decl(indexerConstraints2.ts, 0, 0)) } + +type Key = string; +>Key : Symbol(Key, Decl(indexerConstraints2.ts, 74, 1)) + +interface T { +>T : Symbol(T, Decl(indexerConstraints2.ts, 76, 18)) + + [key: Key] +>key : Symbol(key, Decl(indexerConstraints2.ts, 78, 5)) +>Key : Symbol(Key, Decl(indexerConstraints2.ts, 74, 1)) +} + diff --git a/tests/baselines/reference/indexerConstraints2.types b/tests/baselines/reference/indexerConstraints2.types index dabe7bca687dc..1f5423b594878 100644 --- a/tests/baselines/reference/indexerConstraints2.types +++ b/tests/baselines/reference/indexerConstraints2.types @@ -118,3 +118,12 @@ interface S { [u: "foo" | "bar"]: A; >u : IndexableUnion } + +type Key = string; +>Key : string + +interface T { + [key: Key] +>key : string +} + diff --git a/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.symbols b/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.symbols index 7281886e627e0..f89421cde07a7 100644 --- a/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.symbols +++ b/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.symbols @@ -204,9 +204,9 @@ function objectToMap(obj: any) { return new Map(Object.keys(obj).map(key => [key, obj[key]])); >Map : Symbol(Map, Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Object.keys(obj).map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) ->Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >obj : Symbol(obj, Decl(inferFromGenericFunctionReturnTypes3.ts, 83, 21)) >map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) >key : Symbol(key, Decl(inferFromGenericFunctionReturnTypes3.ts, 84, 37)) diff --git a/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.types b/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.types index ccbeb99a11379..fd83694a171a3 100644 --- a/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.types +++ b/tests/baselines/reference/inferFromGenericFunctionReturnTypes3.types @@ -231,9 +231,9 @@ function objectToMap(obj: any) { >Object.keys(obj).map(key => [key, obj[key]]) : [string, any][] >Object.keys(obj).map : (callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[] >Object.keys(obj) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : { (o: object): string[]; (o: {}): string[]; } >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : { (o: object): string[]; (o: {}): string[]; } >obj : any >map : (callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[] >key => [key, obj[key]] : (key: string) => [string, any] diff --git a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.errors.txt b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.errors.txt index 09653e2d35992..c4a7c6809bcc5 100644 --- a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.errors.txt +++ b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/jsx/inline/index.tsx(5,1): error TS2741: Property '__predomBrand' is missing in type 'Element' but required in type 'Element'. +tests/cases/conformance/jsx/inline/index.tsx(5,1): error TS2741: Property '__predomBrand' is missing in type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. tests/cases/conformance/jsx/inline/index.tsx(21,40): error TS2322: Type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element' is not assignable to type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. tests/cases/conformance/jsx/inline/index.tsx(21,40): error TS2605: JSX element type 'MyClass' is not a constructor function for JSX elements. Property '__domBrand' is missing in type 'MyClass' but required in type 'ElementClass'. tests/cases/conformance/jsx/inline/index.tsx(21,63): error TS2322: Type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element' is not assignable to type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. tests/cases/conformance/jsx/inline/index.tsx(21,63): error TS2605: JSX element type 'MyClass' is not a constructor function for JSX elements. -tests/cases/conformance/jsx/inline/index.tsx(24,42): error TS2741: Property '__domBrand' is missing in type 'Element' but required in type 'Element'. +tests/cases/conformance/jsx/inline/index.tsx(24,42): error TS2741: Property '__domBrand' is missing in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element'. tests/cases/conformance/jsx/inline/index.tsx(24,48): error TS2322: Type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element' is not assignable to type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element'. @@ -75,7 +75,7 @@ tests/cases/conformance/jsx/inline/index.tsx(24,48): error TS2322: Type 'import( let elem = prerendered; elem = ; // Expect assignability error here ~~~~ -!!! error TS2741: Property '__predomBrand' is missing in type 'Element' but required in type 'Element'. +!!! error TS2741: Property '__predomBrand' is missing in type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. !!! related TS2728 tests/cases/conformance/jsx/inline/renderer2.d.ts:7:13: '__predomBrand' is declared here. const DOMSFC = (props: {x: number, y: number, children?: dom.JSX.Element[]}) =>

{props.x} + {props.y} = {props.x + props.y}{props.children}

; @@ -107,7 +107,7 @@ tests/cases/conformance/jsx/inline/index.tsx(24,48): error TS2322: Type 'import( // Should fail, nondom isn't allowed as children of dom const _brokenTree2 = {tree}{tree} ~~~~~~ -!!! error TS2741: Property '__domBrand' is missing in type 'Element' but required in type 'Element'. +!!! error TS2741: Property '__domBrand' is missing in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element'. !!! related TS2728 tests/cases/conformance/jsx/inline/renderer.d.ts:7:13: '__domBrand' is declared here. ~~~~~~ !!! error TS2322: Type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element' is not assignable to type 'import("tests/cases/conformance/jsx/inline/renderer").dom.JSX.Element'. diff --git a/tests/baselines/reference/inlineJsxFactoryLocalTypeGlobalFallback.errors.txt b/tests/baselines/reference/inlineJsxFactoryLocalTypeGlobalFallback.errors.txt index df487eb72e075..c8490e7e33f7e 100644 --- a/tests/baselines/reference/inlineJsxFactoryLocalTypeGlobalFallback.errors.txt +++ b/tests/baselines/reference/inlineJsxFactoryLocalTypeGlobalFallback.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/jsx/inline/index.tsx(5,1): error TS2741: Property '__predomBrand' is missing in type 'Element' but required in type 'Element'. +tests/cases/conformance/jsx/inline/index.tsx(5,1): error TS2741: Property '__predomBrand' is missing in type 'JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. ==== tests/cases/conformance/jsx/inline/renderer.d.ts (0 errors) ==== @@ -45,6 +45,6 @@ tests/cases/conformance/jsx/inline/index.tsx(5,1): error TS2741: Property '__pre let elem = prerendered; elem = ; // Expect assignability error here ~~~~ -!!! error TS2741: Property '__predomBrand' is missing in type 'Element' but required in type 'Element'. +!!! error TS2741: Property '__predomBrand' is missing in type 'JSX.Element' but required in type 'import("tests/cases/conformance/jsx/inline/renderer2").predom.JSX.Element'. !!! related TS2728 tests/cases/conformance/jsx/inline/renderer2.d.ts:7:13: '__predomBrand' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.errors.txt b/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.errors.txt index b8f4ed8b2a894..f7750b86b7a65 100644 --- a/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.errors.txt +++ b/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.errors.txt @@ -2,6 +2,7 @@ tests/cases/compiler/index.tsx(14,9): error TS2322: Type 'number' is not assigna tests/cases/compiler/index.tsx(18,15): error TS2747: 'Blah' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of 'children' is '(x: number) => string'. tests/cases/compiler/index.tsx(23,10): error TS2746: This JSX tag's 'children' prop expects a single child of type '(x: number) => string', but multiple children were provided. tests/cases/compiler/index.tsx(37,10): error TS2745: This JSX tag's 'children' prop expects type '((x: number) => string)[]' which requires multiple children, but only a single child was provided. +tests/cases/compiler/index.tsx(38,4): error TS7006: Parameter 'x' implicitly has an 'any' type. tests/cases/compiler/index.tsx(42,10): error TS2745: This JSX tag's 'children' prop expects type '((x: number) => string)[]' which requires multiple children, but only a single child was provided. tests/cases/compiler/index.tsx(48,9): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/compiler/index.tsx(49,9): error TS2322: Type 'number' is not assignable to type 'string'. @@ -13,7 +14,7 @@ tests/cases/compiler/index.tsx(73,9): error TS2322: Type 'number' is not assigna tests/cases/compiler/index.tsx(74,9): error TS2322: Type 'number' is not assignable to type 'string'. -==== tests/cases/compiler/index.tsx (11 errors) ==== +==== tests/cases/compiler/index.tsx (12 errors) ==== /// import * as React from "react"; @@ -64,6 +65,8 @@ tests/cases/compiler/index.tsx(74,9): error TS2322: Type 'number' is not assigna ~~~~~ !!! error TS2745: This JSX tag's 'children' prop expects type '((x: number) => string)[]' which requires multiple children, but only a single child was provided. {x => x} + ~ +!!! error TS7006: Parameter 'x' implicitly has an 'any' type. // Blah2 components don't accept text as child elements diff --git a/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.types b/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.types index d466a71ecc32b..267e3a7027e57 100644 --- a/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.types +++ b/tests/baselines/reference/jsxChildrenIndividualErrorElaborations.types @@ -85,9 +85,9 @@ var a = >Blah2 : (props: PropsArr) => JSX.Element {x => x} ->x => x : (x: number) => number ->x : number ->x : number +>x => x : (x: any) => any +>x : any +>x : any >Blah2 : (props: PropsArr) => JSX.Element diff --git a/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.js b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.js new file mode 100644 index 0000000000000..7ccea1b36aef6 --- /dev/null +++ b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.js @@ -0,0 +1,61 @@ +//// [jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx] +/// + +import * as React from 'react' + +type Tab = [string, React.ReactNode] // [tabName, tabContent] + +interface Props { + children: Tab[] +} + +function TabLayout(props: Props) { + return
+} + +export class App extends React.Component<{}> { + render() { + return + {[ + ['Users',
], + ['Products',
] + ]} + + } +} + +//// [jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.js] +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +function TabLayout(props) { + return React.createElement("div", null); +} +var App = /** @class */ (function (_super) { + __extends(App, _super); + function App() { + return _super !== null && _super.apply(this, arguments) || this; + } + App.prototype.render = function () { + return React.createElement(TabLayout, null, [ + ['Users', React.createElement("div", null)], + ['Products', React.createElement("div", null)] + ]); + }; + return App; +}(React.Component)); +exports.App = App; diff --git a/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.symbols b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.symbols new file mode 100644 index 0000000000000..93737d2a6f8a0 --- /dev/null +++ b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.symbols @@ -0,0 +1,52 @@ +=== tests/cases/compiler/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx === +/// + +import * as React from 'react' +>React : Symbol(React, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 2, 6)) + +type Tab = [string, React.ReactNode] // [tabName, tabContent] +>Tab : Symbol(Tab, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 2, 30)) +>React : Symbol(React, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 2, 6)) +>ReactNode : Symbol(React.ReactNode, Decl(react16.d.ts, 216, 49)) + +interface Props { +>Props : Symbol(Props, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 4, 36)) + + children: Tab[] +>children : Symbol(Props.children, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 6, 17)) +>Tab : Symbol(Tab, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 2, 30)) +} + +function TabLayout(props: Props) { +>TabLayout : Symbol(TabLayout, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 8, 1)) +>props : Symbol(props, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 10, 19)) +>Props : Symbol(Props, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 4, 36)) + + return
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) +} + +export class App extends React.Component<{}> { +>App : Symbol(App, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 12, 1)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 2, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) + + render() { +>render : Symbol(App.render, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 14, 46)) + + return +>TabLayout : Symbol(TabLayout, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 8, 1)) + + {[ + ['Users',
], +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + ['Products',
] +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + ]} + +>TabLayout : Symbol(TabLayout, Decl(jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx, 8, 1)) + } +} diff --git a/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.types b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.types new file mode 100644 index 0000000000000..dd302f4067963 --- /dev/null +++ b/tests/baselines/reference/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.types @@ -0,0 +1,57 @@ +=== tests/cases/compiler/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx === +/// + +import * as React from 'react' +>React : typeof React + +type Tab = [string, React.ReactNode] // [tabName, tabContent] +>Tab : [string, React.ReactNode] +>React : any + +interface Props { + children: Tab[] +>children : [string, React.ReactNode][] +} + +function TabLayout(props: Props) { +>TabLayout : (props: Props) => JSX.Element +>props : Props + + return
+>
: JSX.Element +>div : any +} + +export class App extends React.Component<{}> { +>App : App +>React.Component : React.Component<{}, {}, any> +>React : typeof React +>Component : typeof React.Component + + render() { +>render : () => JSX.Element + + return +> {[ ['Users',
], ['Products',
] ]} : JSX.Element +>TabLayout : (props: Props) => JSX.Element + + {[ +>[ ['Users',
], ['Products',
] ] : [string, JSX.Element][] + + ['Users',
], +>['Users',
] : [string, JSX.Element] +>'Users' : "Users" +>
: JSX.Element +>div : any + + ['Products',
] +>['Products',
] : [string, JSX.Element] +>'Products' : "Products" +>
: JSX.Element +>div : any + + ]} + +>TabLayout : (props: Props) => JSX.Element + } +} diff --git a/tests/baselines/reference/literalTypeWidening.types b/tests/baselines/reference/literalTypeWidening.types index a96ddc8c5da3e..95bde9a08ac3d 100644 --- a/tests/baselines/reference/literalTypeWidening.types +++ b/tests/baselines/reference/literalTypeWidening.types @@ -391,9 +391,9 @@ export function keys(obj: Record): K[] { return Object.keys(obj) as K[] >Object.keys(obj) as K[] : K[] >Object.keys(obj) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : (o: object) => string[] >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : (o: object) => string[] >obj : Record } diff --git a/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.js b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.js new file mode 100644 index 0000000000000..34413e8f72ba5 --- /dev/null +++ b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.js @@ -0,0 +1,54 @@ +//// [nearbyIdenticalGenericLambdasAssignable.ts] +declare const fA: () => { v: T }; +const fB = () => { + return { v: '' as any as T }; +}; +const fC = () => { + return {} as any as { v: T }; +}; + +// Hover display is identical on all of these +type TA = typeof fA; +type TB = typeof fB; +type TC = typeof fC; +type TL = () => { v: T }; + +declare function accA(x: TA): void; +declare function accB(x: TB): void; +declare function accC(x: TC): void; +declare function accL(x: TL): void; + +// These should all be OK, every type is identical +accA(fA); accA(fB); accA(fC); +// ~~ previously an error +accB(fA); accB(fB); accB(fC); +// OK +accC(fA); accC(fB); accC(fC); +// ~~ previously an error +accL(fA); accL(fB); accL(fC); +// ~~ previously an error + +//// [nearbyIdenticalGenericLambdasAssignable.js] +var fB = function () { + return { v: '' }; +}; +var fC = function () { + return {}; +}; +// These should all be OK, every type is identical +accA(fA); +accA(fB); +accA(fC); +// ~~ previously an error +accB(fA); +accB(fB); +accB(fC); +// OK +accC(fA); +accC(fB); +accC(fC); +// ~~ previously an error +accL(fA); +accL(fB); +accL(fC); +// ~~ previously an error diff --git a/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.symbols b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.symbols new file mode 100644 index 0000000000000..b9236cc887daf --- /dev/null +++ b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.symbols @@ -0,0 +1,102 @@ +=== tests/cases/compiler/nearbyIdenticalGenericLambdasAssignable.ts === +declare const fA: () => { v: T }; +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 19)) +>v : Symbol(v, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 28)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 19)) + +const fB = () => { +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 12)) + + return { v: '' as any as T }; +>v : Symbol(v, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 2, 12)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 12)) + +}; +const fC = () => { +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 12)) + + return {} as any as { v: T }; +>v : Symbol(v, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 5, 25)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 12)) + +}; + +// Hover display is identical on all of these +type TA = typeof fA; +>TA : Symbol(TA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 6, 2)) +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) + +type TB = typeof fB; +>TB : Symbol(TB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 9, 20)) +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) + +type TC = typeof fC; +>TC : Symbol(TC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 10, 20)) +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) + +type TL = () => { v: T }; +>TL : Symbol(TL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 11, 20)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 11)) +>v : Symbol(v, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 20)) +>T : Symbol(T, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 11)) + +declare function accA(x: TA): void; +>accA : Symbol(accA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 28)) +>x : Symbol(x, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 14, 22)) +>TA : Symbol(TA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 6, 2)) + +declare function accB(x: TB): void; +>accB : Symbol(accB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 14, 35)) +>x : Symbol(x, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 15, 22)) +>TB : Symbol(TB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 9, 20)) + +declare function accC(x: TC): void; +>accC : Symbol(accC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 15, 35)) +>x : Symbol(x, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 16, 22)) +>TC : Symbol(TC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 10, 20)) + +declare function accL(x: TL): void; +>accL : Symbol(accL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 16, 35)) +>x : Symbol(x, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 17, 22)) +>TL : Symbol(TL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 11, 20)) + +// These should all be OK, every type is identical +accA(fA); accA(fB); accA(fC); +>accA : Symbol(accA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 28)) +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) +>accA : Symbol(accA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 28)) +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) +>accA : Symbol(accA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 12, 28)) +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) + +// ~~ previously an error +accB(fA); accB(fB); accB(fC); +>accB : Symbol(accB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 14, 35)) +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) +>accB : Symbol(accB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 14, 35)) +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) +>accB : Symbol(accB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 14, 35)) +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) + +// OK +accC(fA); accC(fB); accC(fC); +>accC : Symbol(accC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 15, 35)) +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) +>accC : Symbol(accC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 15, 35)) +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) +>accC : Symbol(accC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 15, 35)) +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) + +// ~~ previously an error +accL(fA); accL(fB); accL(fC); +>accL : Symbol(accL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 16, 35)) +>fA : Symbol(fA, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 0, 13)) +>accL : Symbol(accL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 16, 35)) +>fB : Symbol(fB, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 1, 5)) +>accL : Symbol(accL, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 16, 35)) +>fC : Symbol(fC, Decl(nearbyIdenticalGenericLambdasAssignable.ts, 4, 5)) + +// ~~ previously an error diff --git a/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.types b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.types new file mode 100644 index 0000000000000..b2f878d548ab5 --- /dev/null +++ b/tests/baselines/reference/nearbyIdenticalGenericLambdasAssignable.types @@ -0,0 +1,111 @@ +=== tests/cases/compiler/nearbyIdenticalGenericLambdasAssignable.ts === +declare const fA: () => { v: T }; +>fA : () => { v: T; } +>v : T + +const fB = () => { +>fB : () => { v: T; } +>() => { return { v: '' as any as T };} : () => { v: T; } + + return { v: '' as any as T }; +>{ v: '' as any as T } : { v: T; } +>v : T +>'' as any as T : T +>'' as any : any +>'' : "" + +}; +const fC = () => { +>fC : () => { v: T; } +>() => { return {} as any as { v: T };} : () => { v: T; } + + return {} as any as { v: T }; +>{} as any as { v: T } : { v: T; } +>{} as any : any +>{} : {} +>v : T + +}; + +// Hover display is identical on all of these +type TA = typeof fA; +>TA : () => { v: T; } +>fA : () => { v: T; } + +type TB = typeof fB; +>TB : () => { v: T; } +>fB : () => { v: T; } + +type TC = typeof fC; +>TC : () => { v: T; } +>fC : () => { v: T; } + +type TL = () => { v: T }; +>TL : TL +>v : T + +declare function accA(x: TA): void; +>accA : (x: () => { v: T; }) => void +>x : () => { v: T; } + +declare function accB(x: TB): void; +>accB : (x: () => { v: T; }) => void +>x : () => { v: T; } + +declare function accC(x: TC): void; +>accC : (x: () => { v: T; }) => void +>x : () => { v: T; } + +declare function accL(x: TL): void; +>accL : (x: TL) => void +>x : TL + +// These should all be OK, every type is identical +accA(fA); accA(fB); accA(fC); +>accA(fA) : void +>accA : (x: () => { v: T; }) => void +>fA : () => { v: T; } +>accA(fB) : void +>accA : (x: () => { v: T; }) => void +>fB : () => { v: T; } +>accA(fC) : void +>accA : (x: () => { v: T; }) => void +>fC : () => { v: T; } + +// ~~ previously an error +accB(fA); accB(fB); accB(fC); +>accB(fA) : void +>accB : (x: () => { v: T; }) => void +>fA : () => { v: T; } +>accB(fB) : void +>accB : (x: () => { v: T; }) => void +>fB : () => { v: T; } +>accB(fC) : void +>accB : (x: () => { v: T; }) => void +>fC : () => { v: T; } + +// OK +accC(fA); accC(fB); accC(fC); +>accC(fA) : void +>accC : (x: () => { v: T; }) => void +>fA : () => { v: T; } +>accC(fB) : void +>accC : (x: () => { v: T; }) => void +>fB : () => { v: T; } +>accC(fC) : void +>accC : (x: () => { v: T; }) => void +>fC : () => { v: T; } + +// ~~ previously an error +accL(fA); accL(fB); accL(fC); +>accL(fA) : void +>accL : (x: TL) => void +>fA : () => { v: T; } +>accL(fB) : void +>accL : (x: TL) => void +>fB : () => { v: T; } +>accL(fC) : void +>accL : (x: TL) => void +>fC : () => { v: T; } + +// ~~ previously an error diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.errors.txt b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.errors.txt index fcd04b27754ec..db52e0e0454ac 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.errors.txt +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.ts(3,5): error TS2304: Cannot find name 'undefinedVariable'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.ts(3,5): error TS18004: No value exists in scope for the shorthand property 'undefinedVariable'. Either declare one or provide an initializer. ==== tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNoneExistingIdentifier.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr x, // OK undefinedVariable // Error ~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'undefinedVariable'. +!!! error TS18004: No value exists in scope for the shorthand property 'undefinedVariable'. Either declare one or provide an initializer. } \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt index 17c7126ff3310..04a0565174f5f 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt @@ -7,12 +7,12 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(9,8): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(10,10): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(12,1): error TS1005: ':' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,5): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,6): error TS1005: ',' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,5): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,6): error TS1005: ',' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,12): error TS1005: ':' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,5): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,6): error TS1005: ',' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,9): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(20,17): error TS1005: ':' expected. @@ -53,19 +53,19 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr var x = { a.b, ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. a["ss"], ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. ~ !!! error TS1005: ':' expected. a[1], ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt index 43a0927cc29df..6dc19e6ed5387 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt @@ -1,19 +1,19 @@ -tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,11): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,11): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,12): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,14): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,14): error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,15): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,17): error TS2304: Cannot find name 'c'. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,17): error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. ==== tests/cases/compiler/objectLiteralWithSemicolons1.ts (5 errors) ==== var v = { a; b; c } ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. ~ -!!! error TS2304: Cannot find name 'c'. \ No newline at end of file +!!! error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt index 6fc0b5ff13945..88280933a65cc 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt @@ -1,23 +1,23 @@ -tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,3): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,4): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,3): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,3): error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,4): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons2.ts(4,3): error TS2304: Cannot find name 'c'. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(4,3): error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. ==== tests/cases/compiler/objectLiteralWithSemicolons2.ts (5 errors) ==== var v = { a; ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. b; ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. c ~ -!!! error TS2304: Cannot find name 'c'. +!!! error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. } \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt index dd5709b9822e4..14380be93c41b 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,3): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,4): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,3): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,3): error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,4): error TS1005: ',' expected. -tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,3): error TS2304: Cannot find name 'c'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,3): error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,4): error TS1005: ',' expected. @@ -10,17 +10,17 @@ tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,4): error TS1005: ',' exp var v = { a; ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. b; ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. c; ~ -!!! error TS2304: Cannot find name 'c'. +!!! error TS18004: No value exists in scope for the shorthand property 'c'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt index e0ea42bb8c171..544bddafff278 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/objectLiteralWithSemicolons4.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons4.ts(2,3): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/compiler/objectLiteralWithSemicolons4.ts(3,1): error TS1005: ',' expected. @@ -6,7 +6,7 @@ tests/cases/compiler/objectLiteralWithSemicolons4.ts(3,1): error TS1005: ',' exp var v = { a ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. ; ~ !!! error TS1005: ',' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1.errors.txt b/tests/baselines/reference/parameterInitializersForwardReferencing1.errors.txt index 73f4f27d08b48..91d200adbcdbc 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1.errors.txt +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1.errors.txt @@ -1,12 +1,11 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(3,20): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. -tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(8,27): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(13,20): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(21,18): error TS2372: Parameter 'a' cannot be referenced in its initializer. tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(25,22): error TS2372: Parameter 'async' cannot be referenced in its initializer. tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(29,15): error TS2448: Block-scoped variable 'foo' used before its declaration. -==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts (6 errors) ==== +==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts (5 errors) ==== let foo: string = ""; function f1 (bar = foo) { // unexpected compiler error; works at runtime @@ -17,8 +16,6 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1.ts(29 } function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at runtime - ~~~ -!!! error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. var foo: number = 2; return bar(); // returns 1 } diff --git a/tests/baselines/reference/parser512097.errors.txt b/tests/baselines/reference/parser512097.errors.txt index 5a25284ba51ba..7363372c33197 100644 --- a/tests/baselines/reference/parser512097.errors.txt +++ b/tests/baselines/reference/parser512097.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,12): error TS2304: Cannot find name 'aa'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,12): error TS18004: No value exists in scope for the shorthand property 'aa'. Either declare one or provide an initializer. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,14): error TS1005: ',' expected. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts (2 errors) ==== var tt = { aa; } ~~ -!!! error TS2304: Cannot find name 'aa'. +!!! error TS18004: No value exists in scope for the shorthand property 'aa'. Either declare one or provide an initializer. ~ !!! error TS1005: ',' expected. diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt index 8be4448ae52bf..05c6ba6c8d6b0 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(1,11): error TS2304: Cannot find name 'a'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(1,11): error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,1): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,7): error TS1005: ':' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,8): error TS1005: '}' expected. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserEr ==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts (4 errors) ==== var v = { a ~ -!!! error TS2304: Cannot find name 'a'. +!!! error TS18004: No value exists in scope for the shorthand property 'a'. Either declare one or provide an initializer. return; ~~~~~~ !!! error TS1005: ',' expected. diff --git a/tests/baselines/reference/qualify.errors.txt b/tests/baselines/reference/qualify.errors.txt index 932e3711809eb..87d2ad62657cd 100644 --- a/tests/baselines/reference/qualify.errors.txt +++ b/tests/baselines/reference/qualify.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/qualify.ts(47,13): error TS2322: Type 'I4' is not assignabl tests/cases/compiler/qualify.ts(48,13): error TS2322: Type 'I4' is not assignable to type '(k: I3) => void'. Type 'I4' provides no match for the signature '(k: I3): void'. tests/cases/compiler/qualify.ts(49,13): error TS2741: Property 'k' is missing in type 'I4' but required in type '{ k: I3; }'. -tests/cases/compiler/qualify.ts(58,5): error TS2741: Property 'p' is missing in type 'I' but required in type 'I'. +tests/cases/compiler/qualify.ts(58,5): error TS2741: Property 'p' is missing in type 'I' but required in type 'T.I'. ==== tests/cases/compiler/qualify.ts (8 errors) ==== @@ -88,7 +88,7 @@ tests/cases/compiler/qualify.ts(58,5): error TS2741: Property 'p' is missing in var y:I; var x:T.I=y; ~ -!!! error TS2741: Property 'p' is missing in type 'I' but required in type 'I'. +!!! error TS2741: Property 'p' is missing in type 'I' but required in type 'T.I'. !!! related TS2728 tests/cases/compiler/qualify.ts:18:9: 'p' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/recursiveTypeRelations.types b/tests/baselines/reference/recursiveTypeRelations.types index cb0baef7919d6..669ab3879c4fc 100644 --- a/tests/baselines/reference/recursiveTypeRelations.types +++ b/tests/baselines/reference/recursiveTypeRelations.types @@ -72,9 +72,9 @@ export function css(styles: S, ...classNam >Object.keys(arg).reduce((obj: ClassNameObject, key: keyof S) => { const exportedClassName = styles[key]; obj[exportedClassName] = (arg as ClassNameMap)[key]; return obj; }, {}) : any >Object.keys(arg).reduce : { (callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string): string; (callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string, initialValue: string): string; (callbackfn: (previousValue: U, currentValue: string, currentIndex: number, array: string[]) => U, initialValue: U): U; } >Object.keys(arg) : string[] ->Object.keys : (o: {}) => string[] +>Object.keys : (o: object) => string[] >Object : ObjectConstructor ->keys : (o: {}) => string[] +>keys : (o: object) => string[] >arg : ClassNameObjectMap >reduce : { (callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string): string; (callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string, initialValue: string): string; (callbackfn: (previousValue: U, currentValue: string, currentIndex: number, array: string[]) => U, initialValue: U): U; } >(obj: ClassNameObject, key: keyof S) => { const exportedClassName = styles[key]; obj[exportedClassName] = (arg as ClassNameMap)[key]; return obj; } : (obj: any, key: keyof S) => any diff --git a/tests/baselines/reference/restTypeRetainsMappyness.errors.txt b/tests/baselines/reference/restTypeRetainsMappyness.errors.txt new file mode 100644 index 0000000000000..26cc5db846d5e --- /dev/null +++ b/tests/baselines/reference/restTypeRetainsMappyness.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/restTypeRetainsMappyness.ts(7,8): error TS2345: Argument of type 'Foo[number][]' is not assignable to parameter of type 'Foo'. + + +==== tests/cases/compiler/restTypeRetainsMappyness.ts (1 errors) ==== + type Foo = { + [P in keyof T]: T[P] + } + + function test(fn: (...args: Foo) => void) { + const arr: Foo = {} as any + fn(...arr) // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' + ~~~~~~ +!!! error TS2345: Argument of type 'Foo[number][]' is not assignable to parameter of type 'Foo'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/restTypeRetainsMappyness.js b/tests/baselines/reference/restTypeRetainsMappyness.js new file mode 100644 index 0000000000000..8bda2ece38c18 --- /dev/null +++ b/tests/baselines/reference/restTypeRetainsMappyness.js @@ -0,0 +1,16 @@ +//// [restTypeRetainsMappyness.ts] +type Foo = { + [P in keyof T]: T[P] +} + +function test(fn: (...args: Foo) => void) { + const arr: Foo = {} as any + fn(...arr) // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' +} + + +//// [restTypeRetainsMappyness.js] +function test(fn) { + var arr = {}; + fn.apply(void 0, arr); // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' +} diff --git a/tests/baselines/reference/restTypeRetainsMappyness.symbols b/tests/baselines/reference/restTypeRetainsMappyness.symbols new file mode 100644 index 0000000000000..d56b6f4b5aef6 --- /dev/null +++ b/tests/baselines/reference/restTypeRetainsMappyness.symbols @@ -0,0 +1,30 @@ +=== tests/cases/compiler/restTypeRetainsMappyness.ts === +type Foo = { +>Foo : Symbol(Foo, Decl(restTypeRetainsMappyness.ts, 0, 0)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 0, 9)) + + [P in keyof T]: T[P] +>P : Symbol(P, Decl(restTypeRetainsMappyness.ts, 1, 5)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 0, 9)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 0, 9)) +>P : Symbol(P, Decl(restTypeRetainsMappyness.ts, 1, 5)) +} + +function test(fn: (...args: Foo) => void) { +>test : Symbol(test, Decl(restTypeRetainsMappyness.ts, 2, 1)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 4, 14)) +>fn : Symbol(fn, Decl(restTypeRetainsMappyness.ts, 4, 31)) +>args : Symbol(args, Decl(restTypeRetainsMappyness.ts, 4, 36)) +>Foo : Symbol(Foo, Decl(restTypeRetainsMappyness.ts, 0, 0)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 4, 14)) + + const arr: Foo = {} as any +>arr : Symbol(arr, Decl(restTypeRetainsMappyness.ts, 5, 9)) +>Foo : Symbol(Foo, Decl(restTypeRetainsMappyness.ts, 0, 0)) +>T : Symbol(T, Decl(restTypeRetainsMappyness.ts, 4, 14)) + + fn(...arr) // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' +>fn : Symbol(fn, Decl(restTypeRetainsMappyness.ts, 4, 31)) +>arr : Symbol(arr, Decl(restTypeRetainsMappyness.ts, 5, 9)) +} + diff --git a/tests/baselines/reference/restTypeRetainsMappyness.types b/tests/baselines/reference/restTypeRetainsMappyness.types new file mode 100644 index 0000000000000..411962e877252 --- /dev/null +++ b/tests/baselines/reference/restTypeRetainsMappyness.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/restTypeRetainsMappyness.ts === +type Foo = { +>Foo : Foo + + [P in keyof T]: T[P] +} + +function test(fn: (...args: Foo) => void) { +>test : (fn: (...args: Foo) => void) => void +>fn : (...args: Foo) => void +>args : Foo + + const arr: Foo = {} as any +>arr : Foo +>{} as any : any +>{} : {} + + fn(...arr) // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' +>fn(...arr) : void +>fn : (...args: Foo) => void +>...arr : any +>arr : Foo +} + diff --git a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.errors.txt b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.errors.txt index 7d2ebd38c3581..c22071d4b758f 100644 --- a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.errors.txt +++ b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring.errors.txt @@ -13,7 +13,7 @@ tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(85,19): erro Types of property 'x' are incompatible. Type 'number' is not assignable to type 'string'. tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(85,26): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(111,12): error TS2304: Cannot find name 's'. +tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(111,12): error TS18004: No value exists in scope for the shorthand property 's'. Either declare one or provide an initializer. tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(111,14): error TS1312: '=' can only be used in an object literal property inside a destructuring assignment. @@ -160,7 +160,7 @@ tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring.ts(111,14): err (function() { let a = { s = 5 }; ~ -!!! error TS2304: Cannot find name 's'. +!!! error TS18004: No value exists in scope for the shorthand property 's'. Either declare one or provide an initializer. ~ !!! error TS1312: '=' can only be used in an object literal property inside a destructuring assignment. }); diff --git a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring_ES6.errors.txt b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring_ES6.errors.txt index fa821aa51b6b8..48ce3922c475b 100644 --- a/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring_ES6.errors.txt +++ b/tests/baselines/reference/shorthandPropertyAssignmentsInDestructuring_ES6.errors.txt @@ -13,7 +13,7 @@ tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(85,19): Types of property 'x' are incompatible. Type 'number' is not assignable to type 'string'. tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(85,26): error TS2322: Type 'number' is not assignable to type 'string'. -tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(111,12): error TS2304: Cannot find name 's'. +tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(111,12): error TS18004: No value exists in scope for the shorthand property 's'. Either declare one or provide an initializer. tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(111,14): error TS1312: '=' can only be used in an object literal property inside a destructuring assignment. @@ -160,7 +160,7 @@ tests/cases/compiler/shorthandPropertyAssignmentsInDestructuring_ES6.ts(111,14): (function() { let a = { s = 5 }; ~ -!!! error TS2304: Cannot find name 's'. +!!! error TS18004: No value exists in scope for the shorthand property 's'. Either declare one or provide an initializer. ~ !!! error TS1312: '=' can only be used in an object literal property inside a destructuring assignment. }); diff --git a/tests/baselines/reference/shorthandPropertyUndefined.errors.txt b/tests/baselines/reference/shorthandPropertyUndefined.errors.txt new file mode 100644 index 0000000000000..da6f9ad5984bd --- /dev/null +++ b/tests/baselines/reference/shorthandPropertyUndefined.errors.txt @@ -0,0 +1,7 @@ +tests/cases/compiler/shorthandPropertyUndefined.ts(1,11): error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. + + +==== tests/cases/compiler/shorthandPropertyUndefined.ts (1 errors) ==== + var a = { b }; + ~ +!!! error TS18004: No value exists in scope for the shorthand property 'b'. Either declare one or provide an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/shorthandPropertyUndefined.js b/tests/baselines/reference/shorthandPropertyUndefined.js new file mode 100644 index 0000000000000..643b75bb054c2 --- /dev/null +++ b/tests/baselines/reference/shorthandPropertyUndefined.js @@ -0,0 +1,5 @@ +//// [shorthandPropertyUndefined.ts] +var a = { b }; + +//// [shorthandPropertyUndefined.js] +var a = { b: b }; diff --git a/tests/baselines/reference/shorthandPropertyUndefined.symbols b/tests/baselines/reference/shorthandPropertyUndefined.symbols new file mode 100644 index 0000000000000..fd7c0fe4c231a --- /dev/null +++ b/tests/baselines/reference/shorthandPropertyUndefined.symbols @@ -0,0 +1,5 @@ +=== tests/cases/compiler/shorthandPropertyUndefined.ts === +var a = { b }; +>a : Symbol(a, Decl(shorthandPropertyUndefined.ts, 0, 3)) +>b : Symbol(b, Decl(shorthandPropertyUndefined.ts, 0, 9)) + diff --git a/tests/baselines/reference/shorthandPropertyUndefined.types b/tests/baselines/reference/shorthandPropertyUndefined.types new file mode 100644 index 0000000000000..7ed8983dc3cef --- /dev/null +++ b/tests/baselines/reference/shorthandPropertyUndefined.types @@ -0,0 +1,6 @@ +=== tests/cases/compiler/shorthandPropertyUndefined.ts === +var a = { b }; +>a : { b: any; } +>{ b } : { b: any; } +>b : any + diff --git a/tests/baselines/reference/showConfig/Shows tsconfig for single option/allowUmdGlobalAccess/tsconfig.json b/tests/baselines/reference/showConfig/Shows tsconfig for single option/allowUmdGlobalAccess/tsconfig.json new file mode 100644 index 0000000000000..fdd388c331200 --- /dev/null +++ b/tests/baselines/reference/showConfig/Shows tsconfig for single option/allowUmdGlobalAccess/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "allowUmdGlobalAccess": true + } +} diff --git a/tests/baselines/reference/stringLiteralsAssertionsInEqualityComparisons02.errors.txt b/tests/baselines/reference/stringLiteralsAssertionsInEqualityComparisons02.errors.txt index 8cb9e8203e7ad..b98939167aa33 100644 --- a/tests/baselines/reference/stringLiteralsAssertionsInEqualityComparisons02.errors.txt +++ b/tests/baselines/reference/stringLiteralsAssertionsInEqualityComparisons02.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/types/literal/stringLiteralsAssertionsInEqualityComparisons02.ts(3,9): error TS2367: This condition will always return 'false' since the types '"foo"' and '"baz"' have no overlap. -tests/cases/conformance/types/literal/stringLiteralsAssertionsInEqualityComparisons02.ts(5,9): error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsAssertionsInEqualityComparisons02.ts(5,9): error TS2367: This condition will always return 'false' since the types '"foo"' and 'number' have no overlap. tests/cases/conformance/types/literal/stringLiteralsAssertionsInEqualityComparisons02.ts(5,19): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. @@ -12,7 +12,7 @@ tests/cases/conformance/types/literal/stringLiteralsAssertionsInEqualityComparis var b = "foo" !== ("bar" as "foo"); var c = "foo" == ("bar"); ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"foo"' and 'number' have no overlap. ~~~~~~~~~~~~~ !!! error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. var d = "foo" === ("bar" as EnhancedString); \ No newline at end of file diff --git a/tests/baselines/reference/stringLiteralsWithEqualityChecks03.errors.txt b/tests/baselines/reference/stringLiteralsWithEqualityChecks03.errors.txt index cb25251645025..cbefbbac978bd 100644 --- a/tests/baselines/reference/stringLiteralsWithEqualityChecks03.errors.txt +++ b/tests/baselines/reference/stringLiteralsWithEqualityChecks03.errors.txt @@ -1,8 +1,12 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(16,5): error TS2367: This condition will always return 'false' since the types '"foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(19,5): error TS2367: This condition will always return 'false' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(20,5): error TS2367: This condition will always return 'false' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(25,5): error TS2367: This condition will always return 'true' since the types '"foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(28,5): error TS2367: This condition will always return 'true' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(29,5): error TS2367: This condition will always return 'true' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. -==== tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts (2 errors) ==== +==== tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts (6 errors) ==== interface Runnable { isRunning: boolean; } @@ -24,7 +28,11 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(25,5 b = "bar" === x; b = x === "bar"; b = y === "bar"; + ~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. b = "bar" === y; + ~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. b = x !== y; b = "foo" !== y @@ -35,5 +43,9 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks03.ts(25,5 b = "bar" !== x; b = x !== "bar"; b = y !== "bar"; + ~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. b = "bar" !== y; + ~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. \ No newline at end of file diff --git a/tests/baselines/reference/stringLiteralsWithEqualityChecks04.errors.txt b/tests/baselines/reference/stringLiteralsWithEqualityChecks04.errors.txt index 8bdee5e16173c..293abe0b5c565 100644 --- a/tests/baselines/reference/stringLiteralsWithEqualityChecks04.errors.txt +++ b/tests/baselines/reference/stringLiteralsWithEqualityChecks04.errors.txt @@ -1,8 +1,12 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(16,5): error TS2367: This condition will always return 'false' since the types '"foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(19,5): error TS2367: This condition will always return 'false' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(20,5): error TS2367: This condition will always return 'false' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(25,5): error TS2367: This condition will always return 'true' since the types '"foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(28,5): error TS2367: This condition will always return 'true' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. +tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(29,5): error TS2367: This condition will always return 'true' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. -==== tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts (2 errors) ==== +==== tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts (6 errors) ==== interface Runnable { isRunning: boolean; } @@ -24,7 +28,11 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(25,5 b = "bar" == x; b = x == "bar"; b = y == "bar"; + ~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. b = "bar" == y; + ~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. b = x != y; b = "foo" != y @@ -35,5 +43,9 @@ tests/cases/conformance/types/literal/stringLiteralsWithEqualityChecks04.ts(25,5 b = "bar" != x; b = x != "bar"; b = y != "bar"; + ~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types 'Refrigerator | "foo"' and '"bar"' have no overlap. b = "bar" != y; + ~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types '"bar"' and 'Refrigerator | "foo"' have no overlap. \ No newline at end of file diff --git a/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.js b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.js new file mode 100644 index 0000000000000..722483f5f553d --- /dev/null +++ b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.js @@ -0,0 +1,33 @@ +//// [substitutionTypeNoMergeOfAssignableType.ts] +interface Entry { + comment?: string; + } + + interface Entity { + fields: {[key: string]: Entry}; + } + + type Fields = { + [P in keyof E["fields"]]: E["fields"][P] + }; + + type Nodes = { + [P in keyof T]: T[P] extends Entity + ? Fields + : T[P] + }; + + function makeEntityStore>(config: T): Nodes { + return {} as Nodes + } + + const myTest = makeEntityStore({ test: { fields: { id: {} } } }); + myTest.test + + +//// [substitutionTypeNoMergeOfAssignableType.js] +function makeEntityStore(config) { + return {}; +} +var myTest = makeEntityStore({ test: { fields: { id: {} } } }); +myTest.test; diff --git a/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.symbols b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.symbols new file mode 100644 index 0000000000000..4d1641b535516 --- /dev/null +++ b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/substitutionTypeNoMergeOfAssignableType.ts === +interface Entry { +>Entry : Symbol(Entry, Decl(substitutionTypeNoMergeOfAssignableType.ts, 0, 0)) + + comment?: string; +>comment : Symbol(Entry.comment, Decl(substitutionTypeNoMergeOfAssignableType.ts, 0, 17)) + } + + interface Entity { +>Entity : Symbol(Entity, Decl(substitutionTypeNoMergeOfAssignableType.ts, 2, 2)) + + fields: {[key: string]: Entry}; +>fields : Symbol(Entity.fields, Decl(substitutionTypeNoMergeOfAssignableType.ts, 4, 19)) +>key : Symbol(key, Decl(substitutionTypeNoMergeOfAssignableType.ts, 5, 15)) +>Entry : Symbol(Entry, Decl(substitutionTypeNoMergeOfAssignableType.ts, 0, 0)) + } + + type Fields = { +>Fields : Symbol(Fields, Decl(substitutionTypeNoMergeOfAssignableType.ts, 6, 2)) +>E : Symbol(E, Decl(substitutionTypeNoMergeOfAssignableType.ts, 8, 13)) +>Entity : Symbol(Entity, Decl(substitutionTypeNoMergeOfAssignableType.ts, 2, 2)) + + [P in keyof E["fields"]]: E["fields"][P] +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 9, 6)) +>E : Symbol(E, Decl(substitutionTypeNoMergeOfAssignableType.ts, 8, 13)) +>E : Symbol(E, Decl(substitutionTypeNoMergeOfAssignableType.ts, 8, 13)) +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 9, 6)) + + }; + + type Nodes = { +>Nodes : Symbol(Nodes, Decl(substitutionTypeNoMergeOfAssignableType.ts, 10, 3)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 12, 12)) + + [P in keyof T]: T[P] extends Entity +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 13, 6)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 12, 12)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 12, 12)) +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 13, 6)) +>Entity : Symbol(Entity, Decl(substitutionTypeNoMergeOfAssignableType.ts, 2, 2)) + + ? Fields +>Fields : Symbol(Fields, Decl(substitutionTypeNoMergeOfAssignableType.ts, 6, 2)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 12, 12)) +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 13, 6)) + + : T[P] +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 12, 12)) +>P : Symbol(P, Decl(substitutionTypeNoMergeOfAssignableType.ts, 13, 6)) + + }; + + function makeEntityStore>(config: T): Nodes { +>makeEntityStore : Symbol(makeEntityStore, Decl(substitutionTypeNoMergeOfAssignableType.ts, 16, 3)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 18, 26)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Entity : Symbol(Entity, Decl(substitutionTypeNoMergeOfAssignableType.ts, 2, 2)) +>config : Symbol(config, Decl(substitutionTypeNoMergeOfAssignableType.ts, 18, 60)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 18, 26)) +>Nodes : Symbol(Nodes, Decl(substitutionTypeNoMergeOfAssignableType.ts, 10, 3)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 18, 26)) + + return {} as Nodes +>Nodes : Symbol(Nodes, Decl(substitutionTypeNoMergeOfAssignableType.ts, 10, 3)) +>T : Symbol(T, Decl(substitutionTypeNoMergeOfAssignableType.ts, 18, 26)) + } + + const myTest = makeEntityStore({ test: { fields: { id: {} } } }); +>myTest : Symbol(myTest, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 6)) +>makeEntityStore : Symbol(makeEntityStore, Decl(substitutionTypeNoMergeOfAssignableType.ts, 16, 3)) +>test : Symbol(test, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 33)) +>fields : Symbol(fields, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 41)) +>id : Symbol(id, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 51)) + + myTest.test +>myTest.test : Symbol(test, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 33)) +>myTest : Symbol(myTest, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 6)) +>test : Symbol(test, Decl(substitutionTypeNoMergeOfAssignableType.ts, 22, 33)) + diff --git a/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.types b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.types new file mode 100644 index 0000000000000..af1f239850c03 --- /dev/null +++ b/tests/baselines/reference/substitutionTypeNoMergeOfAssignableType.types @@ -0,0 +1,52 @@ +=== tests/cases/compiler/substitutionTypeNoMergeOfAssignableType.ts === +interface Entry { + comment?: string; +>comment : string + } + + interface Entity { + fields: {[key: string]: Entry}; +>fields : { [key: string]: Entry; } +>key : string + } + + type Fields = { +>Fields : Fields + + [P in keyof E["fields"]]: E["fields"][P] + }; + + type Nodes = { +>Nodes : Nodes + + [P in keyof T]: T[P] extends Entity + ? Fields + : T[P] + }; + + function makeEntityStore>(config: T): Nodes { +>makeEntityStore : >(config: T) => Nodes +>config : T + + return {} as Nodes +>{} as Nodes : Nodes +>{} : {} + } + + const myTest = makeEntityStore({ test: { fields: { id: {} } } }); +>myTest : Nodes<{ test: { fields: { id: {}; }; }; }> +>makeEntityStore({ test: { fields: { id: {} } } }) : Nodes<{ test: { fields: { id: {}; }; }; }> +>makeEntityStore : >(config: T) => Nodes +>{ test: { fields: { id: {} } } } : { test: { fields: { id: {}; }; }; } +>test : { fields: { id: {}; }; } +>{ fields: { id: {} } } : { fields: { id: {}; }; } +>fields : { id: {}; } +>{ id: {} } : { id: {}; } +>id : {} +>{} : {} + + myTest.test +>myTest.test : Fields<{ fields: { id: {}; }; }> +>myTest : Nodes<{ test: { fields: { id: {}; }; }; }> +>test : Fields<{ fields: { id: {}; }; }> + diff --git a/tests/baselines/reference/symbolType9.errors.txt b/tests/baselines/reference/symbolType9.errors.txt index 5b6c233367ef2..e697a2619294f 100644 --- a/tests/baselines/reference/symbolType9.errors.txt +++ b/tests/baselines/reference/symbolType9.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/Symbols/symbolType9.ts(3,1): error TS2367: This condition will always return 'false' since the types 'symbol' and 'boolean' have no overlap. -tests/cases/conformance/es6/Symbols/symbolType9.ts(5,1): error TS2367: This condition will always return 'true' since the types 'number' and 'symbol' have no overlap. -tests/cases/conformance/es6/Symbols/symbolType9.ts(7,1): error TS2367: This condition will always return 'false' since the types 'symbol' and 'number' have no overlap. -tests/cases/conformance/es6/Symbols/symbolType9.ts(9,1): error TS2367: This condition will always return 'true' since the types 'boolean' and 'symbol' have no overlap. +tests/cases/conformance/es6/Symbols/symbolType9.ts(3,1): error TS2367: This condition will always return 'false' since the types 'symbol' and 'true' have no overlap. +tests/cases/conformance/es6/Symbols/symbolType9.ts(5,1): error TS2367: This condition will always return 'true' since the types '0' and 'symbol' have no overlap. +tests/cases/conformance/es6/Symbols/symbolType9.ts(7,1): error TS2367: This condition will always return 'false' since the types 'symbol' and '1' have no overlap. +tests/cases/conformance/es6/Symbols/symbolType9.ts(9,1): error TS2367: This condition will always return 'true' since the types 'false' and 'symbol' have no overlap. ==== tests/cases/conformance/es6/Symbols/symbolType9.ts (4 errors) ==== @@ -9,16 +9,16 @@ tests/cases/conformance/es6/Symbols/symbolType9.ts(9,1): error TS2367: This cond s == s; s == true; ~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'symbol' and 'boolean' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types 'symbol' and 'true' have no overlap. s != s; 0 != s; ~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types 'number' and 'symbol' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '0' and 'symbol' have no overlap. s === s; s === 1; ~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types 'symbol' and 'number' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types 'symbol' and '1' have no overlap. s !== s; false !== s; ~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types 'boolean' and 'symbol' have no overlap. \ No newline at end of file +!!! error TS2367: This condition will always return 'true' since the types 'false' and 'symbol' have no overlap. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt index a4ba377af29fd..c5063689b51b4 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt @@ -89,7 +89,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio fn5 `${ (n) => n.toFixed() }`; // will error; 'n' should have type 'string'. ~~~~~~~ !!! error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'? -!!! related TS2728 /.ts/lib.es2015.core.d.ts:466:5: 'fixed' is declared here. +!!! related TS2728 /.ts/lib.es2015.core.d.ts:472:5: 'fixed' is declared here. fn5 `${ (n) => n.substr(0) }`; \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json index 8e4ff5171868d..36311335115d5 100644 --- a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json index 7332496971fba..88f400655955b 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json index ebf7070cfa4d4..5095e9f81c621 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json index 25f9b39967a8d..46e7b4f13cde1 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json index fc1fb8ec631d8..0355dd9d051ba 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json index dcff85de986d4..e62bf4a08818e 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json index 8e4ff5171868d..36311335115d5 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json index 112be7a95f953..3bf9d892a2461 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json index 4c4b740a12284..35c5bfd08ffb3 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json @@ -48,6 +48,7 @@ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js new file mode 100644 index 0000000000000..f7ffde933fd36 --- /dev/null +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js @@ -0,0 +1,94 @@ +//// [/src/bar.ts] +interface RawAction { + (...args: any[]): Promise | void; +} +interface ActionFactory { + (target: T): T; +} +declare function foo(): ActionFactory; +export default foo()(function foobar(): void { +}); + +//// [/src/obj/bar.d.ts] +declare const _default: () => void; +export default _default; + + +//// [/src/obj/bar.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = foo()(function foobar() { +}); + + +//// [/src/obj/index.d.ts] +import { LazyAction } from './bundling'; +export declare const lazyBar: LazyAction<() => void, typeof import("./lazyIndex")>; + + +//// [/src/obj/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "/lib/lib.d.ts": { + "version": "-15964756381", + "signature": "-15964756381" + }, + "/src/bar.ts": { + "version": "747071916", + "signature": "-9232740537" + }, + "/src/bundling.ts": { + "version": "-21659820217", + "signature": "-40032907372" + }, + "/src/global.d.ts": { + "version": "-9780226215", + "signature": "-9780226215" + }, + "/src/lazyindex.ts": { + "version": "-6956449754", + "signature": "-6224542381" + }, + "/src/index.ts": { + "version": "-11602502901", + "signature": "6256067474" + } + }, + "options": { + "target": 1, + "declaration": true, + "outDir": "/src/obj", + "incremental": true, + "configFilePath": "/src/tsconfig.json" + }, + "referencedMap": { + "/src/index.ts": [ + "/src/bundling.ts", + "/src/lazyindex.ts" + ], + "/src/lazyindex.ts": [ + "/src/bar.ts" + ] + }, + "exportedModulesMap": { + "/src/index.ts": [ + "/src/bundling.ts", + "/src/lazyindex.ts" + ], + "/src/lazyindex.ts": [ + "/src/bar.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "/lib/lib.d.ts", + "/src/bar.ts", + "/src/bundling.ts", + "/src/global.d.ts", + "/src/index.ts", + "/src/lazyindex.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-Build/inferred-type-from-transitive-module.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-Build/inferred-type-from-transitive-module.js new file mode 100644 index 0000000000000..e587db59b21c2 --- /dev/null +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-Build/inferred-type-from-transitive-module.js @@ -0,0 +1,132 @@ +//// [/src/obj/bar.d.ts] +declare const _default: (param: string) => void; +export default _default; + + +//// [/src/obj/bar.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = foo()(function foobar(param) { +}); + + +//// [/src/obj/bundling.d.ts] +export declare class LazyModule { + private importCallback; + constructor(importCallback: () => Promise); +} +export declare class LazyAction any, TModule> { + constructor(_lazyModule: LazyModule, _getter: (module: TModule) => TAction); +} + + +//// [/src/obj/bundling.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var LazyModule = /** @class */ (function () { + function LazyModule(importCallback) { + this.importCallback = importCallback; + } + return LazyModule; +}()); +exports.LazyModule = LazyModule; +var LazyAction = /** @class */ (function () { + function LazyAction(_lazyModule, _getter) { + } + return LazyAction; +}()); +exports.LazyAction = LazyAction; + + +//// [/src/obj/index.d.ts] +import { LazyAction } from './bundling'; +export declare const lazyBar: LazyAction<(param: string) => void, typeof import("./lazyIndex")>; + + +//// [/src/obj/index.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var bundling_1 = require("./bundling"); +var lazyModule = new bundling_1.LazyModule(function () { + return Promise.resolve().then(function () { return require('./lazyIndex'); }); +}); +exports.lazyBar = new bundling_1.LazyAction(lazyModule, function (m) { return m.bar; }); + + +//// [/src/obj/lazyIndex.d.ts] +export { default as bar } from './bar'; + + +//// [/src/obj/lazyIndex.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var bar_1 = require("./bar"); +exports.bar = bar_1.default; + + +//// [/src/obj/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "/lib/lib.d.ts": { + "version": "-15964756381", + "signature": "-15964756381" + }, + "/src/bar.ts": { + "version": "5936740878", + "signature": "11191036521" + }, + "/src/bundling.ts": { + "version": "-21659820217", + "signature": "-40032907372" + }, + "/src/global.d.ts": { + "version": "-9780226215", + "signature": "-9780226215" + }, + "/src/lazyindex.ts": { + "version": "-6956449754", + "signature": "-6224542381" + }, + "/src/index.ts": { + "version": "-11602502901", + "signature": "18468008756" + } + }, + "options": { + "target": 1, + "declaration": true, + "outDir": "/src/obj", + "incremental": true, + "configFilePath": "/src/tsconfig.json" + }, + "referencedMap": { + "/src/index.ts": [ + "/src/bundling.ts", + "/src/lazyindex.ts" + ], + "/src/lazyindex.ts": [ + "/src/bar.ts" + ] + }, + "exportedModulesMap": { + "/src/index.ts": [ + "/src/bundling.ts", + "/src/lazyindex.ts" + ], + "/src/lazyindex.ts": [ + "/src/bar.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "/lib/lib.d.ts", + "/src/bar.ts", + "/src/bundling.ts", + "/src/global.d.ts", + "/src/index.ts", + "/src/lazyindex.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/umd9.js b/tests/baselines/reference/umd9.js new file mode 100644 index 0000000000000..99660aebb4cd5 --- /dev/null +++ b/tests/baselines/reference/umd9.js @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/externalModules/umd9.ts] //// + +//// [foo.d.ts] +declare class Thing { + foo(): number; +} +export = Thing; +export as namespace Foo; + +//// [a.ts] +/// +export const x = Foo; // OK in value position because allowUmdGlobalAccess: true + + +//// [a.js] +"use strict"; +exports.__esModule = true; +/// +exports.x = Foo; // OK in value position because allowUmdGlobalAccess: true diff --git a/tests/baselines/reference/umd9.symbols b/tests/baselines/reference/umd9.symbols new file mode 100644 index 0000000000000..013636f5edb5d --- /dev/null +++ b/tests/baselines/reference/umd9.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/externalModules/a.ts === +/// +export const x = Foo; // OK in value position because allowUmdGlobalAccess: true +>x : Symbol(x, Decl(a.ts, 1, 12)) +>Foo : Symbol(Foo, Decl(foo.d.ts, 3, 15)) + +=== tests/cases/conformance/externalModules/foo.d.ts === +declare class Thing { +>Thing : Symbol(Thing, Decl(foo.d.ts, 0, 0)) + + foo(): number; +>foo : Symbol(Thing.foo, Decl(foo.d.ts, 0, 21)) +} +export = Thing; +>Thing : Symbol(Thing, Decl(foo.d.ts, 0, 0)) + +export as namespace Foo; +>Foo : Symbol(Foo, Decl(foo.d.ts, 3, 15)) + diff --git a/tests/baselines/reference/umd9.types b/tests/baselines/reference/umd9.types new file mode 100644 index 0000000000000..e4fc9376efdad --- /dev/null +++ b/tests/baselines/reference/umd9.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/externalModules/a.ts === +/// +export const x = Foo; // OK in value position because allowUmdGlobalAccess: true +>x : typeof Thing +>Foo : typeof Thing + +=== tests/cases/conformance/externalModules/foo.d.ts === +declare class Thing { +>Thing : Thing + + foo(): number; +>foo : () => number +} +export = Thing; +>Thing : Thing + +export as namespace Foo; +>Foo : typeof Thing + diff --git a/tests/baselines/reference/useBeforeDeclaration_destructuring.errors.txt b/tests/baselines/reference/useBeforeDeclaration_destructuring.errors.txt new file mode 100644 index 0000000000000..0ce95e27125b9 --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration_destructuring.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/useBeforeDeclaration_destructuring.ts(1,1): error TS2448: Block-scoped variable 'a' used before its declaration. + + +==== tests/cases/compiler/useBeforeDeclaration_destructuring.ts (1 errors) ==== + a; + ~ +!!! error TS2448: Block-scoped variable 'a' used before its declaration. +!!! related TS2728 tests/cases/compiler/useBeforeDeclaration_destructuring.ts:2:6: 'a' is declared here. + let {a, b = a} = {a: '', b: 1}; + b; + + function test({c, d = c}: Record) {} + \ No newline at end of file diff --git a/tests/baselines/reference/useBeforeDeclaration_destructuring.js b/tests/baselines/reference/useBeforeDeclaration_destructuring.js new file mode 100644 index 0000000000000..4c06ca7733e43 --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration_destructuring.js @@ -0,0 +1,15 @@ +//// [useBeforeDeclaration_destructuring.ts] +a; +let {a, b = a} = {a: '', b: 1}; +b; + +function test({c, d = c}: Record) {} + + +//// [useBeforeDeclaration_destructuring.js] +a; +var _a = { a: '', b: 1 }, a = _a.a, _b = _a.b, b = _b === void 0 ? a : _b; +b; +function test(_a) { + var c = _a.c, _b = _a.d, d = _b === void 0 ? c : _b; +} diff --git a/tests/baselines/reference/useBeforeDeclaration_destructuring.symbols b/tests/baselines/reference/useBeforeDeclaration_destructuring.symbols new file mode 100644 index 0000000000000..ea8458aeecfaf --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration_destructuring.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/useBeforeDeclaration_destructuring.ts === +a; +>a : Symbol(a, Decl(useBeforeDeclaration_destructuring.ts, 1, 5)) + +let {a, b = a} = {a: '', b: 1}; +>a : Symbol(a, Decl(useBeforeDeclaration_destructuring.ts, 1, 5)) +>b : Symbol(b, Decl(useBeforeDeclaration_destructuring.ts, 1, 7)) +>a : Symbol(a, Decl(useBeforeDeclaration_destructuring.ts, 1, 5)) +>a : Symbol(a, Decl(useBeforeDeclaration_destructuring.ts, 1, 18)) +>b : Symbol(b, Decl(useBeforeDeclaration_destructuring.ts, 1, 24)) + +b; +>b : Symbol(b, Decl(useBeforeDeclaration_destructuring.ts, 1, 7)) + +function test({c, d = c}: Record) {} +>test : Symbol(test, Decl(useBeforeDeclaration_destructuring.ts, 2, 2)) +>c : Symbol(c, Decl(useBeforeDeclaration_destructuring.ts, 4, 15)) +>d : Symbol(d, Decl(useBeforeDeclaration_destructuring.ts, 4, 17)) +>c : Symbol(c, Decl(useBeforeDeclaration_destructuring.ts, 4, 15)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) + diff --git a/tests/baselines/reference/useBeforeDeclaration_destructuring.types b/tests/baselines/reference/useBeforeDeclaration_destructuring.types new file mode 100644 index 0000000000000..935d320353243 --- /dev/null +++ b/tests/baselines/reference/useBeforeDeclaration_destructuring.types @@ -0,0 +1,23 @@ +=== tests/cases/compiler/useBeforeDeclaration_destructuring.ts === +a; +>a : any + +let {a, b = a} = {a: '', b: 1}; +>a : any +>b : any +>a : any +>{a: '', b: 1} : { a: string; b?: number; } +>a : string +>'' : "" +>b : number +>1 : 1 + +b; +>b : any + +function test({c, d = c}: Record) {} +>test : ({ c, d }: Record) => void +>c : number +>d : number +>c : number + diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index ce68e2383edc4..8f4b868d5527a 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -8,58 +8,60 @@ node_modules/uglify-js/lib/ast.js(870,14): error TS2339: Property 'push' does no node_modules/uglify-js/lib/ast.js(877,14): error TS2339: Property 'pop' does not exist on type 'TreeWalker'. node_modules/uglify-js/lib/ast.js(932,25): error TS2339: Property 'self' does not exist on type 'TreeWalker'. node_modules/uglify-js/lib/ast.js(933,37): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(174,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(516,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(839,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1094,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1108,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'true | ((node: any) => any)' has no compatible call signatures. -node_modules/uglify-js/lib/compress.js(1172,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1213,112): error TS2454: Variable 'args' is used before being assigned. -node_modules/uglify-js/lib/compress.js(1214,29): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(1223,87): error TS2322: Type 'false' is not assignable to type 'number'. -node_modules/uglify-js/lib/compress.js(1231,29): error TS2322: Type 'false' is not assignable to type 'never'. -node_modules/uglify-js/lib/compress.js(1337,53): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1438,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1548,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1580,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1687,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. +node_modules/uglify-js/lib/compress.js(175,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(532,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(855,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1110,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1124,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'true | ((node: any) => any)' has no compatible call signatures. +node_modules/uglify-js/lib/compress.js(1188,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1229,112): error TS2454: Variable 'args' is used before being assigned. +node_modules/uglify-js/lib/compress.js(1230,29): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(1239,87): error TS2322: Type 'false' is not assignable to type 'number'. +node_modules/uglify-js/lib/compress.js(1247,29): error TS2322: Type 'false' is not assignable to type 'never'. +node_modules/uglify-js/lib/compress.js(1353,53): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1454,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1564,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1596,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1708,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. Type 'number[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 -node_modules/uglify-js/lib/compress.js(2010,59): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(2048,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. +node_modules/uglify-js/lib/compress.js(2031,59): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2069,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. Type 'any[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 -node_modules/uglify-js/lib/compress.js(2196,34): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3291,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3304,33): error TS2322: Type '"f"' is not assignable to type 'boolean'. -node_modules/uglify-js/lib/compress.js(3438,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3493,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3510,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3535,75): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3761,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3782,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3792,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3951,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'defs' must be of type 'Dictionary & { set: (key: any, val: any) => Dictionary & { set: ...; add: (key: any, val: any) => Dictionary & { set: ...; add: ...; get: (key: any) => any; del: (key: any) => Dictionary & { set: ...; ... 8 more ...; toObject: () => any; }; ... 5 more ...; toObject: () => any; }; ... 7 more ...; toObject: () => any;...', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(4003,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. -node_modules/uglify-js/lib/compress.js(4059,45): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4171,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4470,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(4554,37): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4762,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[RegExp, (string | undefined)?]'. +node_modules/uglify-js/lib/compress.js(2217,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2883,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3328,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3341,33): error TS2322: Type '"f"' is not assignable to type 'boolean'. +node_modules/uglify-js/lib/compress.js(3475,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3528,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3545,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(3570,75): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3643,63): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3828,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3849,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(3859,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4018,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'defs' must be of type 'Dictionary & { set: (key: any, val: any) => Dictionary & { set: ...; add: (key: any, val: any) => Dictionary & { set: ...; add: ...; get: (key: any) => any; del: (key: any) => Dictionary & { set: ...; ... 8 more ...; toObject: () => any; }; ... 5 more ...; toObject: () => any; }; ... 7 more ...; toObject: () => any;...', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(4070,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. +node_modules/uglify-js/lib/compress.js(4126,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4238,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4537,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(4621,37): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4829,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[RegExp, (string | undefined)?]'. Property '0' is missing in type 'any[]' but required in type '[RegExp, (string | undefined)?]'. -node_modules/uglify-js/lib/compress.js(4920,45): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4927,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: () => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 24 more ...; parent: (n: any) => any; }'. -node_modules/uglify-js/lib/compress.js(4931,36): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(4936,41): error TS2339: Property 'get' does not exist on type 'string'. -node_modules/uglify-js/lib/compress.js(5423,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. -node_modules/uglify-js/lib/compress.js(5855,25): error TS2367: This condition will always return 'false' since the types 'boolean' and '"f"' have no overlap. -node_modules/uglify-js/lib/compress.js(5882,47): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5956,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6028,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6034,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6467,43): error TS2454: Variable 'property' is used before being assigned. -node_modules/uglify-js/lib/compress.js(6482,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(6485,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. -node_modules/uglify-js/lib/compress.js(6491,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(6519,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4987,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4994,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: () => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 24 more ...; parent: (n: any) => any; }'. +node_modules/uglify-js/lib/compress.js(4998,36): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(5003,41): error TS2339: Property 'get' does not exist on type 'string'. +node_modules/uglify-js/lib/compress.js(5490,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. +node_modules/uglify-js/lib/compress.js(5922,25): error TS2367: This condition will always return 'false' since the types 'boolean' and '"f"' have no overlap. +node_modules/uglify-js/lib/compress.js(5949,47): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6023,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6095,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6101,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6534,43): error TS2454: Variable 'property' is used before being assigned. +node_modules/uglify-js/lib/compress.js(6549,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(6552,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. +node_modules/uglify-js/lib/compress.js(6558,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(6586,34): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/minify.js(170,75): error TS2339: Property 'compress' does not exist on type 'Compressor'. node_modules/uglify-js/lib/mozilla-ast.js(566,33): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(246,25): error TS2554: Expected 0 arguments, but got 2. @@ -67,33 +69,33 @@ node_modules/uglify-js/lib/output.js(475,37): error TS2554: Expected 0 arguments node_modules/uglify-js/lib/output.js(767,38): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(1163,44): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(1445,58): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. -node_modules/uglify-js/lib/parse.js(367,20): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. +node_modules/uglify-js/lib/parse.js(361,20): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. -node_modules/uglify-js/lib/parse.js(449,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. -node_modules/uglify-js/lib/parse.js(460,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. -node_modules/uglify-js/lib/parse.js(511,20): error TS2339: Property 'raw_source' does not exist on type 'RegExp'. -node_modules/uglify-js/lib/parse.js(622,57): error TS2339: Property 'push' does not exist on type 'never'. -node_modules/uglify-js/lib/parse.js(632,32): error TS2345: Argument of type 'never[]' is not assignable to parameter of type 'never'. -node_modules/uglify-js/lib/parse.js(638,40): error TS2339: Property 'length' does not exist on type 'never'. -node_modules/uglify-js/lib/parse.js(739,13): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(775,69): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(775,83): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(819,31): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(825,17): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(829,21): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(834,43): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(853,21): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(872,21): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(987,23): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. -node_modules/uglify-js/lib/parse.js(1101,9): error TS2322: Type 'any[]' is not assignable to type 'never[]'. +node_modules/uglify-js/lib/parse.js(443,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. +node_modules/uglify-js/lib/parse.js(454,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. +node_modules/uglify-js/lib/parse.js(505,20): error TS2339: Property 'raw_source' does not exist on type 'RegExp'. +node_modules/uglify-js/lib/parse.js(616,57): error TS2339: Property 'push' does not exist on type 'never'. +node_modules/uglify-js/lib/parse.js(626,32): error TS2345: Argument of type 'never[]' is not assignable to parameter of type 'never'. +node_modules/uglify-js/lib/parse.js(632,40): error TS2339: Property 'length' does not exist on type 'never'. +node_modules/uglify-js/lib/parse.js(733,13): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(769,69): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(769,83): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(813,31): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(819,17): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(823,21): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(828,43): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(847,21): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(866,21): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(981,23): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. +node_modules/uglify-js/lib/parse.js(1095,9): error TS2322: Type 'any[]' is not assignable to type 'never[]'. Type 'any' is not assignable to type 'never'. -node_modules/uglify-js/lib/parse.js(1158,17): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(1326,32): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1152,17): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1320,32): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1420,20): error TS2531: Object is possibly 'null'. node_modules/uglify-js/lib/parse.js(1426,20): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(1432,20): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(1518,48): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(1544,35): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/parse.js(1589,52): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1512,48): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1538,35): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/parse.js(1583,52): error TS2531: Object is possibly 'null'. node_modules/uglify-js/lib/propmangle.js(69,18): error TS2339: Property 'prototype' does not exist on type 'ObjectConstructor | FunctionConstructor | StringConstructor | BooleanConstructor | NumberConstructor | Math | DateConstructor | RegExpConstructor | ErrorConstructor | ArrayConstructor'. Property 'prototype' does not exist on type 'Math'. node_modules/uglify-js/lib/propmangle.js(70,45): error TS2339: Property 'prototype' does not exist on type 'ObjectConstructor | FunctionConstructor | StringConstructor | BooleanConstructor | NumberConstructor | Math | DateConstructor | RegExpConstructor | ErrorConstructor | ArrayConstructor'. @@ -101,12 +103,12 @@ node_modules/uglify-js/lib/propmangle.js(70,45): error TS2339: Property 'prototy node_modules/uglify-js/lib/propmangle.js(80,29): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/propmangle.js(94,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/propmangle.js(146,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(104,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(159,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(194,47): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(405,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(462,30): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(487,30): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(102,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(157,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(192,47): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(403,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(460,30): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(485,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/sourcemap.js(55,25): error TS2304: Cannot find name 'MOZ_SourceMap'. node_modules/uglify-js/lib/sourcemap.js(61,23): error TS2304: Cannot find name 'MOZ_SourceMap'. node_modules/uglify-js/tools/exit.js(7,32): error TS2339: Property 'bufferSize' does not exist on type 'WriteStream'. diff --git a/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt b/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt index 4b19087eea036..47e8e6ff4f295 100644 --- a/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt +++ b/tests/baselines/reference/wrappedAndRecursiveConstraints4.errors.txt @@ -1,5 +1,4 @@ -tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursiveConstraints4.ts(13,25): error TS2322: Type '(x: number) => void' is not assignable to type '(pos: number) => string'. - Type 'void' is not assignable to type 'string'. +tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursiveConstraints4.ts(13,12): error TS2345: Argument of type '{ length: number; charAt: (x: number) => void; }' is not assignable to parameter of type 'string'. ==== tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursiveConstraints4.ts (1 errors) ==== @@ -16,6 +15,5 @@ tests/cases/conformance/types/typeParameters/typeArgumentLists/wrappedAndRecursi var c = new C({ length: 2 }); var r = c.foo(''); var r2 = r({ length: 3, charAt: (x: number) => { '' } }); // error - ~~~~~~ -!!! error TS2322: Type '(x: number) => void' is not assignable to type '(pos: number) => string'. -!!! error TS2322: Type 'void' is not assignable to type 'string'. \ No newline at end of file + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2345: Argument of type '{ length: number; charAt: (x: number) => void; }' is not assignable to parameter of type 'string'. \ No newline at end of file diff --git a/tests/cases/compiler/assignmentIndexedToPrimitives.ts b/tests/cases/compiler/assignmentIndexedToPrimitives.ts new file mode 100644 index 0000000000000..1a0fd5c604d82 --- /dev/null +++ b/tests/cases/compiler/assignmentIndexedToPrimitives.ts @@ -0,0 +1,15 @@ +const n1: number = [0]; +const n2: number = ["0"]; +const n3: number = [0, "1"]; +const n4: 0 = [0]; + +const s1: string = [0]; +const s2: string = ["0"]; +const s3: string = [0, "1"]; +const s4: "01" = ["0", "1"]; + +const no1: number = { 0: 1 }; + +const so1: string = { 0: 1 }; +const so2: string = { "0": 1 }; +const so3: string = { 0: "1" }; diff --git a/tests/cases/compiler/capturedParametersInInitializers1.ts b/tests/cases/compiler/capturedParametersInInitializers1.ts index b4150f6b62318..be989e92f8bcf 100644 --- a/tests/cases/compiler/capturedParametersInInitializers1.ts +++ b/tests/cases/compiler/capturedParametersInInitializers1.ts @@ -1,3 +1,4 @@ +// @target: es6 // ok - usage is deferred function foo1(y = class {c = x}, x = 1) { new y().c; @@ -12,4 +13,28 @@ function foo2(y = function(x: typeof z) {}, z = 1) { let a; function foo3(y = { x: a }, z = 1) { -} \ No newline at end of file +} + +// error - used before declaration +function foo4(y = {z}, z = 1) { +} + +// error - used before declaration, IIFEs are inlined +function foo5(y = (() => z)(), z = 1) { +} + +// ok - IIFE inside another function +function foo6(y = () => (() => z)(), z = 1) { +} + +// ok - used inside immediately invoked generator function +function foo7(y = (function*() {yield z})(), z = 1) { +} + +// ok - used inside immediately invoked async function +function foo8(y = (async () => z)(), z = 1) { +} + +// error - used as computed name of method +function foo9(y = {[z]() { return z; }}, z = 1) { +} diff --git a/tests/cases/compiler/capturedParametersInInitializers2.ts b/tests/cases/compiler/capturedParametersInInitializers2.ts index 718c2db713184..852d91d374d70 100644 --- a/tests/cases/compiler/capturedParametersInInitializers2.ts +++ b/tests/cases/compiler/capturedParametersInInitializers2.ts @@ -1,4 +1,14 @@ -function foo(y = class {static c = x}, x = 1) { +// @target: es5 +function foo( + y = class { + static c = x; + get [x]() {return x;} + constructor() { x; } + [z]() { return z; } + }, + x = 1, + z = 2 +) { y.c } function foo2(y = class {[x] = x}, x = 1) { diff --git a/tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts b/tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts new file mode 100644 index 0000000000000..eb92c64c3bfa2 --- /dev/null +++ b/tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts @@ -0,0 +1,6 @@ +// Test for #26758 + +function foo(t: T) { + t === "a"; // Should be allowed + t === "x"; // Should be error +} diff --git a/tests/cases/compiler/errorWithSameNameType.ts b/tests/cases/compiler/errorWithSameNameType.ts new file mode 100644 index 0000000000000..662ae638753bb --- /dev/null +++ b/tests/cases/compiler/errorWithSameNameType.ts @@ -0,0 +1,22 @@ +// @filename: a.ts +export interface F { + foo1: number +} + +// @filename: b.ts +export interface F { + foo2: number +} + +// @filename: c.ts +import * as A from './a' +import * as B from './b' + +let a: A.F +let b: B.F + +if (a === b) { + +} + +a = b diff --git a/tests/cases/compiler/exportAssignmentWithoutAllowSyntheticDefaultImportsError.ts b/tests/cases/compiler/exportAssignmentWithoutAllowSyntheticDefaultImportsError.ts new file mode 100644 index 0000000000000..8513a6bdb675d --- /dev/null +++ b/tests/cases/compiler/exportAssignmentWithoutAllowSyntheticDefaultImportsError.ts @@ -0,0 +1,8 @@ +// @module: es2015 + +// @Filename: /bar.ts +export = bar; +function bar() {} + +// @Filename: /foo.ts +import bar from './bar'; \ No newline at end of file diff --git a/tests/cases/compiler/importTypeGenericArrowTypeParenthesized.ts b/tests/cases/compiler/importTypeGenericArrowTypeParenthesized.ts new file mode 100644 index 0000000000000..d8a212b1e8674 --- /dev/null +++ b/tests/cases/compiler/importTypeGenericArrowTypeParenthesized.ts @@ -0,0 +1,18 @@ +// @declaration: true +// @filename: module.d.ts +declare module "module" { + export interface Modifier { } + + export function fn(x: T): Modifier; +} +// @filename: index.ts +import { fn } from "module"; + +export const fail1 = fn((x: T): T => x); +export const fail2 = fn(function(x: T): T { + return x; +}); + +export const works1 = fn((x: number) => x); +type MakeItWork = (x: T) => T; +export const works2 = fn(x => x); diff --git a/tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts b/tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts new file mode 100644 index 0000000000000..725870c5da61e --- /dev/null +++ b/tests/cases/compiler/importTypeWithUnparenthesizedGenericFunctionParsed.ts @@ -0,0 +1 @@ +export declare const fail1: import("module").Modifier<(x: T) => T>; // shouldn't be a parse error \ No newline at end of file diff --git a/tests/cases/compiler/indexerConstraints2.ts b/tests/cases/compiler/indexerConstraints2.ts index 38b4ddec41a3d..caa7ca719f333 100644 --- a/tests/cases/compiler/indexerConstraints2.ts +++ b/tests/cases/compiler/indexerConstraints2.ts @@ -72,4 +72,9 @@ interface R { interface S { [u: "foo" | "bar"]: A; -} \ No newline at end of file +} + +type Key = string; +interface T { + [key: Key] +} diff --git a/tests/cases/compiler/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx b/tests/cases/compiler/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx new file mode 100644 index 0000000000000..ae53669cad5e2 --- /dev/null +++ b/tests/cases/compiler/jsxChildrenSingleChildConfusableWithMultipleChildrenNoError.tsx @@ -0,0 +1,26 @@ +// @skipLibCheck: true +// @jsx: react +/// + +import * as React from 'react' + +type Tab = [string, React.ReactNode] // [tabName, tabContent] + +interface Props { + children: Tab[] +} + +function TabLayout(props: Props) { + return
+} + +export class App extends React.Component<{}> { + render() { + return + {[ + ['Users',
], + ['Products',
] + ]} + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/nearbyIdenticalGenericLambdasAssignable.ts b/tests/cases/compiler/nearbyIdenticalGenericLambdasAssignable.ts new file mode 100644 index 0000000000000..bad3cfb332722 --- /dev/null +++ b/tests/cases/compiler/nearbyIdenticalGenericLambdasAssignable.ts @@ -0,0 +1,28 @@ +declare const fA: () => { v: T }; +const fB = () => { + return { v: '' as any as T }; +}; +const fC = () => { + return {} as any as { v: T }; +}; + +// Hover display is identical on all of these +type TA = typeof fA; +type TB = typeof fB; +type TC = typeof fC; +type TL = () => { v: T }; + +declare function accA(x: TA): void; +declare function accB(x: TB): void; +declare function accC(x: TC): void; +declare function accL(x: TL): void; + +// These should all be OK, every type is identical +accA(fA); accA(fB); accA(fC); +// ~~ previously an error +accB(fA); accB(fB); accB(fC); +// OK +accC(fA); accC(fB); accC(fC); +// ~~ previously an error +accL(fA); accL(fB); accL(fC); +// ~~ previously an error \ No newline at end of file diff --git a/tests/cases/compiler/restTypeRetainsMappyness.ts b/tests/cases/compiler/restTypeRetainsMappyness.ts new file mode 100644 index 0000000000000..d0d4fff669cd8 --- /dev/null +++ b/tests/cases/compiler/restTypeRetainsMappyness.ts @@ -0,0 +1,8 @@ +type Foo = { + [P in keyof T]: T[P] +} + +function test(fn: (...args: Foo) => void) { + const arr: Foo = {} as any + fn(...arr) // Error: Argument of type 'any[]' is not assignable to parameter of type 'Foo' +} diff --git a/tests/cases/compiler/shorthandPropertyUndefined.ts b/tests/cases/compiler/shorthandPropertyUndefined.ts new file mode 100644 index 0000000000000..0b9ac3fcbeff9 --- /dev/null +++ b/tests/cases/compiler/shorthandPropertyUndefined.ts @@ -0,0 +1 @@ +var a = { b }; \ No newline at end of file diff --git a/tests/cases/compiler/substitutionTypeNoMergeOfAssignableType.ts b/tests/cases/compiler/substitutionTypeNoMergeOfAssignableType.ts new file mode 100644 index 0000000000000..b919557d65520 --- /dev/null +++ b/tests/cases/compiler/substitutionTypeNoMergeOfAssignableType.ts @@ -0,0 +1,25 @@ +interface Entry { + comment?: string; + } + + interface Entity { + fields: {[key: string]: Entry}; + } + + type Fields = { + [P in keyof E["fields"]]: E["fields"][P] + }; + + type Nodes = { + [P in keyof T]: T[P] extends Entity + ? Fields + : T[P] + }; + + function makeEntityStore>(config: T): Nodes { + return {} as Nodes + } + + const myTest = makeEntityStore({ test: { fields: { id: {} } } }); + myTest.test + \ No newline at end of file diff --git a/tests/cases/compiler/useBeforeDeclaration_destructuring.ts b/tests/cases/compiler/useBeforeDeclaration_destructuring.ts new file mode 100644 index 0000000000000..9ef9c896f0388 --- /dev/null +++ b/tests/cases/compiler/useBeforeDeclaration_destructuring.ts @@ -0,0 +1,5 @@ +a; +let {a, b = a} = {a: '', b: 1}; +b; + +function test({c, d = c}: Record) {} diff --git a/tests/cases/conformance/declarationEmit/exportDefaultNamespace.ts b/tests/cases/conformance/declarationEmit/exportDefaultNamespace.ts new file mode 100644 index 0000000000000..4724bda727ca3 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/exportDefaultNamespace.ts @@ -0,0 +1,7 @@ +// @declaration: true + +export default function someFunc() { + return 'hello!'; +} + +someFunc.someProp = 'yo'; diff --git a/tests/cases/conformance/externalModules/umd9.ts b/tests/cases/conformance/externalModules/umd9.ts new file mode 100644 index 0000000000000..459227e9454c5 --- /dev/null +++ b/tests/cases/conformance/externalModules/umd9.ts @@ -0,0 +1,14 @@ +// @module: commonjs +// @noImplicitReferences: true +// @allowUmdGlobalAccess: true + +// @filename: foo.d.ts +declare class Thing { + foo(): number; +} +export = Thing; +export as namespace Foo; + +// @filename: a.ts +/// +export const x = Foo; // OK in value position because allowUmdGlobalAccess: true diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts deleted file mode 100644 index af8707a9f81c5..0000000000000 --- a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes.ts +++ /dev/null @@ -1,44 +0,0 @@ -/// - -// @Filename: /dir/node_modules/plus/index.js -////module.exports = function plus(x, y) { return x + y; }; - -// @Filename: /dir/a.ts -////import plus = require("plus"); -////plus; - -// @Filename: /dir/tsconfig.json -////{ -//// "compilerOptions": { -//// "paths": { -//// "nota": ["valid_pathmapping"], -//// dontCrash: 37, -//// "*": ["abc123"], -//// } -//// } -////} - -goTo.file("/dir/a.ts"); -verify.codeFix({ - description: "Generate types for 'plus'", - newFileContent: { - "/dir/tsconfig.json": -`{ - "compilerOptions": { - "baseUrl": ".", - "paths": { - "*": ["types/*"], - "nota": ["valid_pathmapping"], - dontCrash: 37, - "*": ["abc123"], - } - } -}`, - }, - commands: [{ - type: "generate types", - file: "/dir/a.ts", - fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", - outputFileName: "/dir/types/plus.d.ts", - }], -}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts deleted file mode 100644 index 183ca3324a473..0000000000000 --- a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_all.ts +++ /dev/null @@ -1,47 +0,0 @@ -/// - -// @Filename: /dir/node_modules/plus/index.js -////module.exports = function plus(x, y) { return x + y; }; - -// @Filename: /dir/node_modules/times/index.js -////module.exports = function times(x, y) { return x * y; }; - -// @Filename: /dir/a.ts -////import plus = require("plus"); -////import times = require("times"); -////plus; - -// @Filename: /dir/tsconfig.json -////{ -//// "compilerOptions": {} -////} - -goTo.file("/dir/a.ts"); -verify.codeFixAll({ - fixAllDescription: "Generate types for all packages without types", - fixId: "generateTypes", - newFileContent: { - "/dir/tsconfig.json": -// TODO: GH#26618 -`{ - "compilerOptions": { - "baseUrl": ".", - "paths": { "*": ["types/*"] }, -} -}`, - }, - commands: [ - { - type: "generate types", - file: "/dir/a.ts", - fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", - outputFileName: "/dir/types/plus.d.ts", - }, - { - type: "generate types", - file: "/dir/a.ts", - fileToGenerateTypesFor: "/dir/node_modules/times/index.js", - outputFileName: "/dir/types/times.d.ts", - }, - ], -}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts deleted file mode 100644 index 99a2207814391..0000000000000 --- a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_noExistingCompilerOptions.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// - -// @Filename: /dir/node_modules/plus/index.js -////module.exports = function plus(x, y) { return x * y; }; - -// @Filename: /dir/a.ts -////import plus = require("plus"); -////plus; - -// @Filename: /dir/tsconfig.json -////{} - -goTo.file("/dir/a.ts"); -verify.codeFix({ - description: "Generate types for 'plus'", - newFileContent: { - "/dir/tsconfig.json": -`{ - "compilerOptions": { "baseUrl": ".", "paths": { "*": ["types/*"] } }, -}`, - }, - commands: [{ - type: "generate types", - file: "/dir/a.ts", - fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", - outputFileName: "/dir/types/plus.d.ts", - }], -}); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts deleted file mode 100644 index a4e6450e93351..0000000000000 --- a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_notForNonexistentPackage.ts +++ /dev/null @@ -1,13 +0,0 @@ -/// - -// @Filename: /a.ts -////import plus = require("plus"); -////plus; - -// @Filename: /tsconfig.json -////{ -//// "compilerOptions": {} -////} - -goTo.file("/a.ts"); -verify.codeFixAvailable([]); diff --git a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts b/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts deleted file mode 100644 index 5c095f84ba752..0000000000000 --- a/tests/cases/fourslash/codeFixCannotFindModule_generateTypes_typesDirectoryExists.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -// @Filename: /dir/node_modules/plus/index.js -////module.exports = function plus(x, y) { return x * y; }; - -// @Filename: /dir/a.ts -////import plus = require("plus"); -////plus; - -// @Filename: /dir/tsconfig.json -////{ -//// "compilerOptions": { -//// "baseUrl": "base", -//// "paths": { -//// "*": ["myTypes/*"], -//// }, -//// }, -////} - -goTo.file("/dir/a.ts"); -verify.codeFix({ - description: "Generate types for 'plus'", - newFileContent: {}, // no change - commands: [{ - type: "generate types", - file: "/dir/a.ts", - fileToGenerateTypesFor: "/dir/node_modules/plus/index.js", - outputFileName: "/dir/base/myTypes/plus.d.ts", - }], -}); diff --git a/tests/cases/fourslash/codeFixClassImplementInterfaceWithNegativeNumber.ts b/tests/cases/fourslash/codeFixClassImplementInterfaceWithNegativeNumber.ts new file mode 100644 index 0000000000000..0fbce596d8741 --- /dev/null +++ b/tests/cases/fourslash/codeFixClassImplementInterfaceWithNegativeNumber.ts @@ -0,0 +1,9 @@ + + +/// + +//// interface X { value: -1 | 0 | 1; } +//// class Y implements X { } + +// https://github.com/Microsoft/TypeScript/issues/30431 +verify.codeFixAvailable([{ description: "Implement interface 'X'" }]); diff --git a/tests/cases/fourslash/codeFixInferFromFunctionUsage.ts b/tests/cases/fourslash/codeFixInferFromFunctionUsage.ts new file mode 100644 index 0000000000000..27a039878ba36 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromFunctionUsage.ts @@ -0,0 +1,9 @@ +/// + +// @noImplicitAny: true +////function wrap( [| arr |] ) { +//// arr.sort(function (a: number, b: number) { return a < b ? -1 : 1 }) +//// } + +// https://github.com/Microsoft/TypeScript/issues/29330 +verify.rangeAfterCodeFix("arr: { sort: (arg0: (a: number, b: number) => 1 | -1) => void; }"); diff --git a/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts b/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts index 42e48ecd38deb..86388a7a8d3f6 100644 --- a/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts +++ b/tests/cases/fourslash/formattingSpaceBeforeFunctionParen.ts @@ -5,9 +5,11 @@ /////*3*/var bar = function foo() { }; /////*4*/var foo = { bar() { } }; /////*5*/function tmpl () { } +/////*6*/var f = function*() { }; +/////*7*/function* g () { } -format.setOption("InsertSpaceBeforeFunctionParenthesis", true); - +format.setOption("insertSpaceBeforeFunctionParenthesis", true); +format.setOption("insertSpaceAfterFunctionKeywordForAnonymousFunctions", false); format.document(); goTo.marker('1'); @@ -20,3 +22,7 @@ goTo.marker('4'); verify.currentLineContentIs('var foo = { bar () { } };'); goTo.marker('5'); verify.currentLineContentIs('function tmpl () { }'); +goTo.marker('6'); +verify.currentLineContentIs('var f = function*() { };'); +goTo.marker('7'); +verify.currentLineContentIs('function* g () { }'); diff --git a/tests/cases/fourslash/generateTypes.ts b/tests/cases/fourslash/generateTypes.ts deleted file mode 100644 index 3a26e9829b298..0000000000000 --- a/tests/cases/fourslash/generateTypes.ts +++ /dev/null @@ -1,157 +0,0 @@ -/// - -////dummy text - -verify.generateTypes( -{ - value: 0, - global: true, - output: "declare const example: number;\n", -}, -{ - value: { x: 0, f() {} }, - global: true, - output: -`declare namespace example { - function f(): void; - const x: number; -} -`, -}, -{ - value: { "*": 10, "default": true, "with": 10, " ": 3 }, - global: true, - output: -`declare const example: { - " ": number; - "*": number; - default: boolean; - with: number; -}; -`, -}, -{ - value: { "*": 10, f() {} }, - global: true, - output: -`declare namespace example { - function f(): void; -} -`, -}, - -{ - value: 0, - output: -`export = example; -declare const example: number; -`, -}, -{ - value: (x, y) => x + y, - output: -`export = example; -declare function example(x: any, y: any): void; -`, -}, -{ - // non-arrow functions have different toString(), so important to test - value: function(x, y) { - return x * y; - function inner() { - arguments; // Should not affect type inference - } - }, - output: -`export = example; -declare function example(x: any, y: any): any; -`, -}, -{ - value: function(x) { arguments; }, - output: -`export = example; -declare function example(x: any, ...args: any[]): void; -`, -}, - -{ - value: ({ default() {} }), - output: -`export default function _default(): void; -`, -}, - -{ - value: ({ default: class {} }), - output: -`export default class _default { -} -`, -}, - -{ - value: new Date(), - output: -`export = example; -declare const example: Date; -`, -}, - -{ - value: [0], - output: -`export = example; -declare const example: number[]; -`, -}, -{ - value: [() => 0, () => ""], - output: -`export = example; -declare const example: Function[]; -`, -}, -{ - value: (() => { - const a = []; - a.push(a); - return a; - })(), - output: -`export = example; -declare const example: any[]; -`, -}, -{ - value: (() => { - const o = { - default: 0, - a: 0, - b: "", - self: null, - fn: x => x, - ns1: { x: 0, default: 0 }, - ns2: { fn: x => x, default: 0 }, - }; - o.self = o; - return o; - })(), - output: -`export const a: number; -export const b: string; -export default _default; -export const _default: number; -export function fn(x: any): void; -export const ns1: { - default: number; - x: number; -}; -export namespace ns2 { - function fn(x: any): void; -} -// Circular reference from example -export const self: any; -`, -}, -); diff --git a/tests/cases/fourslash/generateTypes_baselines.ts b/tests/cases/fourslash/generateTypes_baselines.ts deleted file mode 100644 index 9508f83d31f40..0000000000000 --- a/tests/cases/fourslash/generateTypes_baselines.ts +++ /dev/null @@ -1,35 +0,0 @@ -/// - -////dummy text - -verify.generateTypes( - // would like to test against the real "global" but that may vary between node versions. - { - value: { - Array: ignore(Array, ["values", "flat", "flatMap"]), - Boolean, - Date, - Math, - Number, - RegExp, - String: ignore(String, ["padStart", "padEnd", "trimStart", "trimEnd"]), - Symbol: ignore(Symbol, ["asyncIterator", "description"]), - }, - outputBaseline: "global", - }, - { value: require("lodash"), outputBaseline: "lodash" }, -); - -// Ignore properties only present in newer versions of node. -function ignore(Cls: Function, ignored: ReadonlyArray): Function { - class Copy {} - for (const name of Object.getOwnPropertyNames(Cls)) { - if (ignored.includes(name) || name === "arguments" || name === "caller" || name === "name" || name === "length" || name === "prototype") continue; - Copy[name] = Cls[name]; - } - for (const name of Object.getOwnPropertyNames(Cls.prototype)) { - if (ignored.includes(name)) continue; - Copy.prototype[name] = Cls.prototype[name]; - } - return Copy; -} diff --git a/tests/cases/fourslash/generateTypes_classes.ts b/tests/cases/fourslash/generateTypes_classes.ts deleted file mode 100644 index 9168346874377..0000000000000 --- a/tests/cases/fourslash/generateTypes_classes.ts +++ /dev/null @@ -1,149 +0,0 @@ -/// - -////dummy text - -verify.generateTypes( -{ - value: class {}, - output: -`export = example; -declare class example { -} -`, -}, - -{ - value: class { - constructor(x) { - (this as any).x = x; - // Code inside this function should be ignored - function f(this: any) { - this.y = 0; - } - // Same for this class - class Other { constructor() { (this as any).z = 0; } } - } - }, - output: -`export = example; -declare class example { - constructor(x: any); - x: any; -} -`, -}, -{ - value: { x: 0, export: 0 }, - output: `export const x: number; -`, -}, -{ - value: (() => { - class Super { - superField = 0; // TODO: climb to prototype.constructor and get instance fields? - superMethod() {} - static superStaticMethod() {} - } - class C extends Super { - constructor() { - super(); - (this as any)._privateField = 0; - (this as any).field = 0; - } - - _privateMethod() {} - method(_p) { - (this as any).otherField = 0; // TODO: include this in output? - } - - static _privateStatic() {} - static staticMethod(_s: any) {} - static staticMethodWithNoNamespaceMembers(_p: any) {} - - static _privateStaticField = 0; - static staticField = 0; - static innerClass = class {}; - } - (C.prototype as any).prototypeNonFunction = 0; // ignored - (C.staticMethod as any).staticMethodProperty = 0; - (C.staticMethod as any)._staticFieldPrivateMember = 0; - (C.prototype.method as any).methodMember = 0; // ignored - // Non-identifier names should be ignored. - (C as any)["&"] = function() {}; - (C.prototype as any)["&"] = function() {}; - return C; - })(), - output: -`export = example; -declare class example { - static staticField: number; - static staticMethodWithNoNamespaceMembers(_p: any): void; - static superStaticMethod(): void; - field: any; - method(_p: any): void; - superMethod(): void; -} -declare namespace example { - class innerClass { - } - function staticMethod(_s: any): void; - namespace staticMethod { - const staticMethodProperty: number; - } -} -`, -}, - -{ - value: (() => { - function F() { this.x = 0; } - (F as any).staticMethod = function() {} - F.prototype.method = function() { } - return F; - })(), - output: -`export = example; -declare class example { - static staticMethod(): void; - x: any; - method(): void; -} -`, -}, - -{ - // No duplicate instance members - value: (() => { - class C { - constructor() { - (this as any).x = 0; - (this as any).x = 1; - (this as any).m = 0; - } - m() {} - } - return C; - })(), - output: -`export = example; -declare class example { - x: any; - m(): void; -} -`, -}, - -{ - // nontrivial prototype marks something as an instance - value: (() => { - const obj = Object.create({}); - obj.m = function() { this.x = 0; } - return { obj }; - })(), - output: -`export const obj: { - m: Function; -}; -`, -}, -); diff --git a/tests/cases/fourslash/generatorDeclarationFormatting.ts b/tests/cases/fourslash/generatorDeclarationFormatting.ts index 007380fd0dedf..4b7ae4157aea5 100644 --- a/tests/cases/fourslash/generatorDeclarationFormatting.ts +++ b/tests/cases/fourslash/generatorDeclarationFormatting.ts @@ -7,4 +7,4 @@ format.document(); goTo.marker('1'); verify.currentLineContentIs("function* g() { }"); goTo.marker('2'); -verify.currentLineContentIs("var v = function* () { };"); \ No newline at end of file +verify.currentLineContentIs("var v = function*() { };"); \ No newline at end of file diff --git a/tests/projects/inferredTypeFromTransitiveModule/bar.ts b/tests/projects/inferredTypeFromTransitiveModule/bar.ts new file mode 100644 index 0000000000000..84efa817b01df --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/bar.ts @@ -0,0 +1,9 @@ +interface RawAction { + (...args: any[]): Promise | void; +} +interface ActionFactory { + (target: T): T; +} +declare function foo(): ActionFactory; +export default foo()(function foobar(param: string): void { +}); \ No newline at end of file diff --git a/tests/projects/inferredTypeFromTransitiveModule/bundling.ts b/tests/projects/inferredTypeFromTransitiveModule/bundling.ts new file mode 100644 index 0000000000000..dc7fd0d1864e0 --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/bundling.ts @@ -0,0 +1,11 @@ +export class LazyModule { + constructor(private importCallback: () => Promise) {} +} + +export class LazyAction< + TAction extends (...args: any[]) => any, + TModule +> { + constructor(_lazyModule: LazyModule, _getter: (module: TModule) => TAction) { + } +} diff --git a/tests/projects/inferredTypeFromTransitiveModule/global.d.ts b/tests/projects/inferredTypeFromTransitiveModule/global.d.ts new file mode 100644 index 0000000000000..0386ed66f7071 --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/global.d.ts @@ -0,0 +1,6 @@ +interface PromiseConstructor { + new (): Promise; +} +declare var Promise: PromiseConstructor; +interface Promise { +} \ No newline at end of file diff --git a/tests/projects/inferredTypeFromTransitiveModule/index.ts b/tests/projects/inferredTypeFromTransitiveModule/index.ts new file mode 100644 index 0000000000000..f5adaa5eb2a32 --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/index.ts @@ -0,0 +1,5 @@ +import { LazyAction, LazyModule } from './bundling'; +const lazyModule = new LazyModule(() => + import('./lazyIndex') +); +export const lazyBar = new LazyAction(lazyModule, m => m.bar); \ No newline at end of file diff --git a/tests/projects/inferredTypeFromTransitiveModule/lazyIndex.ts b/tests/projects/inferredTypeFromTransitiveModule/lazyIndex.ts new file mode 100644 index 0000000000000..1b1a7743ed76d --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/lazyIndex.ts @@ -0,0 +1 @@ +export { default as bar } from './bar'; diff --git a/tests/projects/inferredTypeFromTransitiveModule/tsconfig.json b/tests/projects/inferredTypeFromTransitiveModule/tsconfig.json new file mode 100644 index 0000000000000..f29cb38d3fb2c --- /dev/null +++ b/tests/projects/inferredTypeFromTransitiveModule/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "es5", + "declaration": true, + "outDir": "obj", + "incremental": true + } +} \ No newline at end of file diff --git a/tslint.json b/tslint.json index 5952c770c5e7e..5b75ed1a55b74 100644 --- a/tslint.json +++ b/tslint.json @@ -1,6 +1,11 @@ { "extends": "tslint:latest", "rulesDirectory": "built/local/tslint/rules", + "linterOptions": { + "exclude": [ + "tests/**/*" + ] + }, "rules": { "no-unnecessary-type-assertion": true,