diff --git a/.eslintrc.json b/.eslintrc.json index affed4dbc0108..486f0cc29f11c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -34,6 +34,7 @@ ], "@typescript-eslint/consistent-type-definitions": ["error", "interface"], + "@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as" }], "no-duplicate-imports": "off", "@typescript-eslint/no-duplicate-imports": "error", diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 0eaa4fb427461..8cb8045ef425e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -20,11 +20,6 @@ jobs: # a pull request then we can checkout the head. fetch-depth: 2 - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 diff --git a/.github/workflows/sync-wiki.yml b/.github/workflows/sync-wiki.yml new file mode 100644 index 0000000000000..a10335070b049 --- /dev/null +++ b/.github/workflows/sync-wiki.yml @@ -0,0 +1,21 @@ +name: Sync Two Wiki Repos + +on: [gollum] + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Get repo name + run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV + - name: Checkout ${{ env.BASENAME }}-wiki + uses: actions/checkout@v2 + with: + repository: "${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki" + token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} + fetch-depth: 0 + - name: Run sync + run: ./.github/workflows/sync + env: + PUSHER: typescript-bot + AUTH: ${{ secrets.TS_BOT_GITHUB_TOKEN }} diff --git a/package-lock.json b/package-lock.json index df19d4464e882..f73012feb9115 100644 --- a/package-lock.json +++ b/package-lock.json @@ -314,9 +314,9 @@ } }, "@octokit/graphql": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.1.tgz", - "integrity": "sha512-2lYlvf4YTDgZCTXTW4+OX+9WTLFtEUc6hGm4qM1nlZjzxj+arizM4aHWzBVBCxY9glh7GIs0WEuiSgbVzv8cmA==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz", + "integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==", "dev": true, "requires": { "@octokit/request": "^5.3.0", @@ -325,9 +325,9 @@ } }, "@octokit/openapi-types": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.0.0.tgz", - "integrity": "sha512-gV/8DJhAL/04zjTI95a7FhQwS6jlEE0W/7xeYAzuArD0KVAVWDLP2f3vi98hs3HLTczxXdRK/mF0tRoQPpolEw==", + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.2.1.tgz", + "integrity": "sha512-IHQJpLciwzwDvciLxiFj3IEV5VYn7lSVcj5cu0jbTwMfK4IG6/g8SPrVp3Le1VRzIiYSRcBzm1dA7vgWelYP3Q==", "dev": true }, "@octokit/plugin-paginate-rest": { @@ -401,12 +401,12 @@ } }, "@octokit/types": { - "version": "6.14.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.14.2.tgz", - "integrity": "sha512-wiQtW9ZSy4OvgQ09iQOdyXYNN60GqjCL/UdMsepDr1Gr0QzpW6irIKbH3REuAHXAhxkEk9/F2a3Gcs1P6kW5jA==", + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.0.tgz", + "integrity": "sha512-EktqSNq8EKXE82a7Vw33ozOEhFXIRik+rZHJTHAgVZRm/p2K5r5ecn5fVpRkLCm3CAVFwchRvt3yvtmfbt2LCQ==", "dev": true, "requires": { - "@octokit/openapi-types": "^7.0.0" + "@octokit/openapi-types": "^7.2.0" } }, "@types/browserify": { @@ -583,9 +583,9 @@ "dev": true }, "@types/node": { - "version": "15.3.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-15.3.0.tgz", - "integrity": "sha512-8/bnjSZD86ZfpBsDlCIkNXIvm+h6wi9g7IqL+kmFkQ+Wvu3JrasgLElfiPgoo8V8vVfnEi0QVS12gbl94h9YsQ==", + "version": "15.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.0.tgz", + "integrity": "sha512-gCYSfQpy+LYhOFTKAeE8BkyGqaxmlFxe+n4DKM6DR0wzw/HISUE/hAmkC/KT8Sw5PCJblqg062b3z9gucv3k0A==", "dev": true }, "@types/node-fetch": { @@ -1052,12 +1052,6 @@ "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", "dev": true }, - "array-filter": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-filter/-/array-filter-1.0.0.tgz", - "integrity": "sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=", - "dev": true - }, "array-includes": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz", @@ -1141,6 +1135,111 @@ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, + "array.prototype.filter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array.prototype.filter/-/array.prototype.filter-1.0.0.tgz", + "integrity": "sha512-TfO1gz+tLm+Bswq0FBOXPqAchtCr2Rn48T8dLJoRFl8NoEosjZmzptmuo1X8aZBzZcqsR1W8U761tjACJtngTQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0", + "es-array-method-boxes-properly": "^1.0.0", + "is-string": "^1.0.5" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", + "object-inspect": "^1.9.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + } + }, + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, + "is-negative-zero": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", + "dev": true + }, + "is-regex": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", + "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.2" + } + }, + "object-inspect": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", + "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + } + } + }, "array.prototype.flat": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz", @@ -1268,12 +1367,12 @@ "dev": true }, "available-typed-arrays": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.2.tgz", - "integrity": "sha512-XWX3OX8Onv97LMk/ftVyBibpGwY5a8SmuxZPzeOxqmuEqUCOM9ZE+uIaD1VNJ5QnvU2UQusvmKbuM1FR8QWGfQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.3.tgz", + "integrity": "sha512-CuPhFULixV/d89POo1UG4GqGbR7dmrefY2ZdmsYakeR4gOSJXoF7tfeaiqMHGOMrlTiJoeEs87fpLsBYmE2BMw==", "dev": true, "requires": { - "array-filter": "^1.0.0" + "array.prototype.filter": "^1.0.0" } }, "azure-devops-node-api": { @@ -2674,6 +2773,12 @@ } } }, + "es-array-method-boxes-properly": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz", + "integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==", + "dev": true + }, "es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", @@ -7960,9 +8065,9 @@ "dev": true }, "uglify-js": { - "version": "3.13.6", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.6.tgz", - "integrity": "sha512-rRprLwl8RVaS+Qvx3Wh5hPfPBn9++G6xkGlUupya0s5aDmNjI7z3lnRLB3u7sN4OmbB0pWgzhM9BEJyiWAwtAA==", + "version": "3.13.7", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.7.tgz", + "integrity": "sha512-1Psi2MmnZJbnEsgJJIlfnd7tFlJfitusmR7zDI8lXlFI0ACD4/Rm/xdrU8bh6zF0i74aiVoBtkRiFulkrmh3AA==", "dev": true, "optional": true }, diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index 4714b44bb298d..23026ca50f32e 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -47,7 +47,7 @@ class DeclarationsWalker { } if (s.name === "Array" || s.name === "ReadOnlyArray") { // we should process type argument instead - return this.processType((type).typeArguments[0]); + return this.processType((type as any).typeArguments[0]); } else { const declarations = s.getDeclarations(); @@ -84,12 +84,12 @@ class DeclarationsWalker { case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.Parameter: case ts.SyntaxKind.IndexSignature: - if (((node.parent).type) === node) { + if (((node.parent as ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration).type) === node) { this.processTypeOfNode(node); } break; case ts.SyntaxKind.InterfaceDeclaration: - const heritageClauses = (node.parent).heritageClauses; + const heritageClauses = (node.parent as ts.InterfaceDeclaration).heritageClauses; if (heritageClauses) { if (heritageClauses[0].token !== ts.SyntaxKind.ExtendsKeyword) { throw new Error(`Unexpected kind of heritage clause: ${ts.SyntaxKind[heritageClauses[0].kind]}`); @@ -106,7 +106,7 @@ class DeclarationsWalker { private processTypeOfNode(node: ts.Node): void { if (node.kind === ts.SyntaxKind.UnionType) { - for (const t of (node).types) { + for (const t of (node as ts.UnionTypeNode).types) { this.processTypeOfNode(t); } } @@ -120,7 +120,7 @@ class DeclarationsWalker { } function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptServicesDts: string) { - const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [], stripInternal: true }; + const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [] as string[], stripInternal: true }; /** * 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 4e850f4eea9ea..02432a247949b 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -100,7 +100,7 @@ namespace ts { case SyntaxKind.Identifier: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should // be considered the same as type alias - if ((node).isInJSDocNamespace) { + if ((node as Identifier).isInJSDocNamespace) { return ModuleInstanceState.NonInstantiated; } } @@ -327,14 +327,14 @@ namespace ts { // unless it is a well known Symbol. function getDeclarationName(node: Declaration): __String | undefined { if (node.kind === SyntaxKind.ExportAssignment) { - return (node).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default; + return (node as ExportAssignment).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default; } const name = getNameOfDeclaration(node); if (name) { if (isAmbientModule(node)) { const moduleName = getTextOfIdentifierOrLiteral(name as Identifier | StringLiteral); - return (isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`) as __String; + return (isGlobalScopeAugmentation(node as ModuleDeclaration) ? "__global" : `"${moduleName}"`) as __String; } if (name.kind === SyntaxKind.ComputedPropertyName) { const nameExpression = name.expression; @@ -392,7 +392,7 @@ namespace ts { // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType, "Impossible parameter parent kind", () => `parent is: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[node.parent.kind] : node.parent.kind}, expected JSDocFunctionType`); - const functionType = node.parent; + const functionType = node.parent as JSDocFunctionType; const index = functionType.parameters.indexOf(node as ParameterDeclaration); return "arg" + index as __String; } @@ -499,7 +499,7 @@ namespace ts { // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals)) { + (node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals)) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; multipleDefaultExports = true; @@ -656,13 +656,13 @@ namespace ts { const saveActiveLabelList = activeLabelList; const saveHasExplicitReturn = hasExplicitReturn; const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !hasSyntacticModifier(node, ModifierFlags.Async) && - !(node).asteriskToken && !!getImmediatelyInvokedFunctionExpression(node); + !(node as FunctionLikeDeclaration).asteriskToken && !!getImmediatelyInvokedFunctionExpression(node); // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { currentFlow = initFlowNode({ flags: FlowFlags.Start }); if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { - currentFlow.node = node; + currentFlow.node = node as FunctionExpression | ArrowFunction | MethodDeclaration; } } // We create a return control flow graph for IIFEs and constructors. For constructors @@ -676,10 +676,10 @@ namespace ts { bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~NodeFlags.ReachabilityAndEmitFlags; - if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((node).body)) { + if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((node as FunctionLikeDeclaration).body)) { node.flags |= NodeFlags.HasImplicitReturn; if (hasExplicitReturn) node.flags |= NodeFlags.HasExplicitReturn; - (node).endFlowNode = currentFlow; + (node as FunctionLikeDeclaration).endFlowNode = currentFlow; } if (node.kind === SyntaxKind.SourceFile) { node.flags |= emitFlags; @@ -690,7 +690,7 @@ namespace ts { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); if (node.kind === SyntaxKind.Constructor || (isInJSFile(node) && (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression))) { - (node).returnFlowNode = currentFlow; + (node as FunctionLikeDeclaration).returnFlowNode = currentFlow; } } if (!isIIFE) { @@ -750,52 +750,52 @@ namespace ts { } switch (node.kind) { case SyntaxKind.WhileStatement: - bindWhileStatement(node); + bindWhileStatement(node as WhileStatement); break; case SyntaxKind.DoStatement: - bindDoStatement(node); + bindDoStatement(node as DoStatement); break; case SyntaxKind.ForStatement: - bindForStatement(node); + bindForStatement(node as ForStatement); break; case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - bindForInOrForOfStatement(node); + bindForInOrForOfStatement(node as ForInOrOfStatement); break; case SyntaxKind.IfStatement: - bindIfStatement(node); + bindIfStatement(node as IfStatement); break; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: - bindReturnOrThrow(node); + bindReturnOrThrow(node as ReturnStatement | ThrowStatement); break; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: - bindBreakOrContinueStatement(node); + bindBreakOrContinueStatement(node as BreakOrContinueStatement); break; case SyntaxKind.TryStatement: - bindTryStatement(node); + bindTryStatement(node as TryStatement); break; case SyntaxKind.SwitchStatement: - bindSwitchStatement(node); + bindSwitchStatement(node as SwitchStatement); break; case SyntaxKind.CaseBlock: - bindCaseBlock(node); + bindCaseBlock(node as CaseBlock); break; case SyntaxKind.CaseClause: - bindCaseClause(node); + bindCaseClause(node as CaseClause); break; case SyntaxKind.ExpressionStatement: - bindExpressionStatement(node); + bindExpressionStatement(node as ExpressionStatement); break; case SyntaxKind.LabeledStatement: - bindLabeledStatement(node); + bindLabeledStatement(node as LabeledStatement); break; case SyntaxKind.PrefixUnaryExpression: - bindPrefixUnaryExpressionFlow(node); + bindPrefixUnaryExpressionFlow(node as PrefixUnaryExpression); break; case SyntaxKind.PostfixUnaryExpression: - bindPostfixUnaryExpressionFlow(node); + bindPostfixUnaryExpressionFlow(node as PostfixUnaryExpression); break; case SyntaxKind.BinaryExpression: if (isDestructuringAssignment(node)) { @@ -805,26 +805,26 @@ namespace ts { bindDestructuringAssignmentFlow(node); return; } - bindBinaryExpressionFlow(node); + bindBinaryExpressionFlow(node as BinaryExpression); break; case SyntaxKind.DeleteExpression: - bindDeleteExpressionFlow(node); + bindDeleteExpressionFlow(node as DeleteExpression); break; case SyntaxKind.ConditionalExpression: - bindConditionalExpressionFlow(node); + bindConditionalExpressionFlow(node as ConditionalExpression); break; case SyntaxKind.VariableDeclaration: - bindVariableDeclarationFlow(node); + bindVariableDeclarationFlow(node as VariableDeclaration); break; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - bindAccessExpressionFlow(node); + bindAccessExpressionFlow(node as AccessExpression); break; case SyntaxKind.CallExpression: - bindCallExpressionFlow(node); + bindCallExpressionFlow(node as CallExpression); break; case SyntaxKind.NonNullExpression: - bindNonNullExpressionFlow(node); + bindNonNullExpressionFlow(node as NonNullExpression); break; case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: @@ -842,7 +842,7 @@ namespace ts { bindEachFunctionsFirst((node as Block).statements); break; case SyntaxKind.BindingElement: - bindBindingElementFlow(node); + bindBindingElementFlow(node as BindingElement); break; case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.ArrayLiteralExpression: @@ -869,16 +869,16 @@ namespace ts { case SyntaxKind.ElementAccessExpression: return containsNarrowableReference(expr); case SyntaxKind.CallExpression: - return hasNarrowableArgument(expr); + return hasNarrowableArgument(expr as CallExpression); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return isNarrowingExpression((expr).expression); + return isNarrowingExpression((expr as ParenthesizedExpression | NonNullExpression).expression); case SyntaxKind.BinaryExpression: - return isNarrowingBinaryExpression(expr); + return isNarrowingBinaryExpression(expr as BinaryExpression); case SyntaxKind.PrefixUnaryExpression: - return (expr).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr).operand); + return (expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr as PrefixUnaryExpression).operand); case SyntaxKind.TypeOfExpression: - return isNarrowingExpression((expr).expression); + return isNarrowingExpression((expr as TypeOfExpression).expression); } return false; } @@ -904,7 +904,7 @@ namespace ts { } } if (expr.expression.kind === SyntaxKind.PropertyAccessExpression && - containsNarrowableReference((expr.expression).expression)) { + containsNarrowableReference((expr.expression as PropertyAccessExpression).expression)) { return true; } return false; @@ -944,13 +944,13 @@ namespace ts { function isNarrowableOperand(expr: Expression): boolean { switch (expr.kind) { case SyntaxKind.ParenthesizedExpression: - return isNarrowableOperand((expr).expression); + return isNarrowableOperand((expr as ParenthesizedExpression).expression); case SyntaxKind.BinaryExpression: - switch ((expr).operatorToken.kind) { + switch ((expr as BinaryExpression).operatorToken.kind) { case SyntaxKind.EqualsToken: - return isNarrowableOperand((expr).left); + return isNarrowableOperand((expr as BinaryExpression).left); case SyntaxKind.CommaToken: - return isNarrowableOperand((expr).right); + return isNarrowableOperand((expr as BinaryExpression).right); } } return containsNarrowableReference(expr); @@ -1035,10 +1035,10 @@ namespace ts { case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: - return (parent).expression === node; + return (parent as IfStatement | WhileStatement | DoStatement).expression === node; case SyntaxKind.ForStatement: case SyntaxKind.ConditionalExpression: - return (parent).condition === node; + return (parent as ForStatement | ConditionalExpression).condition === node; } return false; } @@ -1046,16 +1046,16 @@ namespace ts { function isLogicalExpression(node: Node) { while (true) { if (node.kind === SyntaxKind.ParenthesizedExpression) { - node = (node).expression; + node = (node as ParenthesizedExpression).expression; } - else if (node.kind === SyntaxKind.PrefixUnaryExpression && (node).operator === SyntaxKind.ExclamationToken) { - node = (node).operand; + else if (node.kind === SyntaxKind.PrefixUnaryExpression && (node as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) { + node = (node as PrefixUnaryExpression).operand; } else { return node.kind === SyntaxKind.BinaryExpression && ( - (node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken || - (node).operatorToken.kind === SyntaxKind.BarBarToken || - (node).operatorToken.kind === SyntaxKind.QuestionQuestionToken); + (node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken || + (node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken || + (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken); } } } @@ -1370,7 +1370,7 @@ namespace ts { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. if (node.kind === SyntaxKind.CallExpression) { - const call = node; + const call = node as CallExpression; if (call.expression.kind !== SyntaxKind.SuperKeyword && isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } @@ -1397,8 +1397,8 @@ namespace ts { } function bindDestructuringTargetFlow(node: Expression) { - if (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.EqualsToken) { - bindAssignmentTargetFlow((node).left); + if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + bindAssignmentTargetFlow((node as BinaryExpression).left); } else { bindAssignmentTargetFlow(node); @@ -1410,9 +1410,9 @@ namespace ts { currentFlow = createFlowMutation(FlowFlags.Assignment, currentFlow, node); } else if (node.kind === SyntaxKind.ArrayLiteralExpression) { - for (const e of (node).elements) { + for (const e of (node as ArrayLiteralExpression).elements) { if (e.kind === SyntaxKind.SpreadElement) { - bindAssignmentTargetFlow((e).expression); + bindAssignmentTargetFlow((e as SpreadElement).expression); } else { bindDestructuringTargetFlow(e); @@ -1420,7 +1420,7 @@ namespace ts { } } else if (node.kind === SyntaxKind.ObjectLiteralExpression) { - for (const p of (node).properties) { + for (const p of (node as ObjectLiteralExpression).properties) { if (p.kind === SyntaxKind.PropertyAssignment) { bindDestructuringTargetFlow(p.initializer); } @@ -1579,7 +1579,7 @@ namespace ts { if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) { - const elementAccess = node.left; + const elementAccess = node.left as ElementAccessExpression; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node); } @@ -1784,7 +1784,7 @@ namespace ts { } } if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { - const propertyAccess = node.expression; + const propertyAccess = node.expression as PropertyAccessExpression; if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node); } @@ -1839,7 +1839,7 @@ namespace ts { case SyntaxKind.ModuleBlock: return ContainerFlags.IsControlFlowContainer; case SyntaxKind.PropertyDeclaration: - return (node).initializer ? ContainerFlags.IsControlFlowContainer : 0; + return (node as PropertyDeclaration).initializer ? ContainerFlags.IsControlFlowContainer : 0; case SyntaxKind.CatchClause: case SyntaxKind.ForStatement: @@ -2099,7 +2099,7 @@ namespace ts { declareModuleMember(node, symbolFlags, symbolExcludes); break; case SyntaxKind.SourceFile: - if (isExternalOrCommonJsModule(container)) { + if (isExternalOrCommonJsModule(container as SourceFile)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; } @@ -2249,7 +2249,7 @@ namespace ts { if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) { // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); + checkStrictModeEvalOrArguments(node, node.left as Identifier); } } @@ -2277,7 +2277,7 @@ namespace ts { function checkStrictModeEvalOrArguments(contextNode: Node, name: Node | undefined) { if (name && name.kind === SyntaxKind.Identifier) { - const identifier = name; + const identifier = name as Identifier; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -2350,7 +2350,7 @@ namespace ts { // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); + checkStrictModeEvalOrArguments(node, node.operand as Identifier); } } @@ -2358,7 +2358,7 @@ namespace ts { // Grammar checking if (inStrictMode) { if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { - checkStrictModeEvalOrArguments(node, node.operand); + checkStrictModeEvalOrArguments(node, node.operand as Identifier); } } } @@ -2479,7 +2479,7 @@ namespace ts { return; } - if (isUseStrictPrologueDirective(statement)) { + if (isUseStrictPrologueDirective(statement as ExpressionStatement)) { inStrictMode = true; return; } @@ -2503,7 +2503,7 @@ namespace ts { // for typedef type names with namespaces, bind the new jsdoc type symbol here // because it requires all containing namespaces to be in effect, namely the // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if ((node).isInJSDocNamespace) { + if ((node as Identifier).isInJSDocNamespace) { let parentNode = node.parent; while (parentNode && !isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; @@ -2516,9 +2516,9 @@ namespace ts { if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) { node.flowNode = currentFlow; } - return checkContextualIdentifier(node); + return checkContextualIdentifier(node as Identifier); case SyntaxKind.QualifiedName: - if (currentFlow && parent.kind === SyntaxKind.TypeQuery) { + if (currentFlow && isPartOfTypeQuery(node)) { node.flowNode = currentFlow; } break; @@ -2580,21 +2580,21 @@ namespace ts { default: Debug.fail("Unknown binary expression special property assignment kind"); } - return checkStrictModeBinaryExpression(node); + return checkStrictModeBinaryExpression(node as BinaryExpression); case SyntaxKind.CatchClause: - return checkStrictModeCatchClause(node); + return checkStrictModeCatchClause(node as CatchClause); case SyntaxKind.DeleteExpression: - return checkStrictModeDeleteExpression(node); + return checkStrictModeDeleteExpression(node as DeleteExpression); case SyntaxKind.NumericLiteral: - return checkStrictModeNumericLiteral(node); + return checkStrictModeNumericLiteral(node as NumericLiteral); case SyntaxKind.PostfixUnaryExpression: - return checkStrictModePostfixUnaryExpression(node); + return checkStrictModePostfixUnaryExpression(node as PostfixUnaryExpression); case SyntaxKind.PrefixUnaryExpression: - return checkStrictModePrefixUnaryExpression(node); + return checkStrictModePrefixUnaryExpression(node as PrefixUnaryExpression); case SyntaxKind.WithStatement: - return checkStrictModeWithStatement(node); + return checkStrictModeWithStatement(node as WithStatement); case SyntaxKind.LabeledStatement: - return checkStrictModeLabeledStatement(node); + return checkStrictModeLabeledStatement(node as LabeledStatement); case SyntaxKind.ThisType: seenThisKeyword = true; return; @@ -2603,46 +2603,46 @@ namespace ts { case SyntaxKind.TypeParameter: return bindTypeParameter(node as TypeParameterDeclaration); case SyntaxKind.Parameter: - return bindParameter(node); + return bindParameter(node as ParameterDeclaration); case SyntaxKind.VariableDeclaration: - return bindVariableDeclarationOrBindingElement(node); + return bindVariableDeclarationOrBindingElement(node as VariableDeclaration); case SyntaxKind.BindingElement: node.flowNode = currentFlow; - return bindVariableDeclarationOrBindingElement(node); + return bindVariableDeclarationOrBindingElement(node as BindingElement); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: return bindPropertyWorker(node as PropertyDeclaration | PropertySignature); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Property, SymbolFlags.PropertyExcludes); case SyntaxKind.EnumMember: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Signature, SymbolFlags.None); + return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Signature, SymbolFlags.None); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Method | ((node as MethodDeclaration).questionToken ? SymbolFlags.Optional : SymbolFlags.None), isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); case SyntaxKind.FunctionDeclaration: - return bindFunctionDeclaration(node); + return bindFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.Constructor: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); + return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); case SyntaxKind.GetAccessor: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); case SyntaxKind.SetAccessor: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.JSDocFunctionType: case SyntaxKind.JSDocSignature: case SyntaxKind.ConstructorType: - return bindFunctionOrConstructorType(node); + return bindFunctionOrConstructorType(node as SignatureDeclaration | JSDocSignature); case SyntaxKind.TypeLiteral: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.MappedType: @@ -2650,10 +2650,10 @@ namespace ts { case SyntaxKind.JSDocClassTag: return bindJSDocClassTag(node as JSDocClassTag); case SyntaxKind.ObjectLiteralExpression: - return bindObjectLiteralExpression(node); + return bindObjectLiteralExpression(node as ObjectLiteralExpression); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return bindFunctionExpression(node); + return bindFunctionExpression(node as FunctionExpression); case SyntaxKind.CallExpression: const assignmentKind = getAssignmentDeclarationKind(node as CallExpression); @@ -2670,7 +2670,7 @@ namespace ts { return Debug.fail("Unknown call expression assignment declaration kind"); } if (isInJSFile(node)) { - bindCallExpression(node); + bindCallExpression(node as CallExpression); } break; @@ -2679,37 +2679,37 @@ namespace ts { case SyntaxKind.ClassDeclaration: // All classes are automatically in strict mode in ES6. inStrictMode = true; - return bindClassLikeDeclaration(node); + return bindClassLikeDeclaration(node as ClassLikeDeclaration); case SyntaxKind.InterfaceDeclaration: - return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); + return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); case SyntaxKind.TypeAliasDeclaration: - return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: - return bindEnumDeclaration(node); + return bindEnumDeclaration(node as EnumDeclaration); case SyntaxKind.ModuleDeclaration: - return bindModuleDeclaration(node); + return bindModuleDeclaration(node as ModuleDeclaration); // Jsx-attributes case SyntaxKind.JsxAttributes: - return bindJsxAttributes(node); + return bindJsxAttributes(node as JsxAttributes); case SyntaxKind.JsxAttribute: - return bindJsxAttribute(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + return bindJsxAttribute(node as JsxAttribute, SymbolFlags.Property, SymbolFlags.PropertyExcludes); // Imports and exports case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes); case SyntaxKind.NamespaceExportDeclaration: - return bindNamespaceExportDeclaration(node); + return bindNamespaceExportDeclaration(node as NamespaceExportDeclaration); case SyntaxKind.ImportClause: - return bindImportClause(node); + return bindImportClause(node as ImportClause); case SyntaxKind.ExportDeclaration: - return bindExportDeclaration(node); + return bindExportDeclaration(node as ExportDeclaration); case SyntaxKind.ExportAssignment: - return bindExportAssignment(node); + return bindExportAssignment(node as ExportAssignment); case SyntaxKind.SourceFile: - updateStrictModeStatementList((node).statements); + updateStrictModeStatementList((node as SourceFile).statements); return bindSourceFileIfExternalModule(); case SyntaxKind.Block: if (!isFunctionLike(node.parent)) { @@ -2717,7 +2717,7 @@ namespace ts { } // falls through case SyntaxKind.ModuleBlock: - return updateStrictModeStatementList((node).statements); + return updateStrictModeStatementList((node as Block | ModuleBlock).statements); case SyntaxKind.JSDocParameterTag: if (node.parent.kind === SyntaxKind.JSDocSignature) { @@ -2745,7 +2745,7 @@ namespace ts { } function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral) { - return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, InternalSymbolName.Type); + return bindAnonymousDeclaration(node as Declaration, SymbolFlags.TypeLiteral, InternalSymbolName.Type); } function bindSourceFileIfExternalModule() { @@ -3432,7 +3432,7 @@ namespace ts { // report error on class declarations node.kind === SyntaxKind.ClassDeclaration || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node as ModuleDeclaration)); if (reportError) { currentFlow = reportedUnreachableFlow; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fad22675cbe4a..e74b547e6826a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -180,15 +180,6 @@ namespace ts { IsForSignatureHelp = 1 << 4, // Call resolution for purposes of signature help } - const enum AccessFlags { - None = 0, - NoIndexSignatures = 1 << 0, - Writing = 1 << 1, - CacheSymbol = 1 << 2, - NoTupleBoundsCheck = 1 << 3, - ExpressionPosition = 1 << 4, - } - const enum SignatureCheckMode { BivariantCallback = 1 << 0, StrictCallback = 1 << 1, @@ -781,7 +772,7 @@ namespace ts { const numberOrBigIntType = getUnionType([numberType, bigintType]); const templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]) as UnionType; - const restrictiveMapper: TypeMapper = makeFunctionTypeMapper(t => t.flags & TypeFlags.TypeParameter ? getRestrictiveTypeParameter(t) : t); + const restrictiveMapper: TypeMapper = makeFunctionTypeMapper(t => t.flags & TypeFlags.TypeParameter ? getRestrictiveTypeParameter(t as TypeParameter) : t); const permissiveMapper: TypeMapper = makeFunctionTypeMapper(t => t.flags & TypeFlags.TypeParameter ? wildcardType : t); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -792,7 +783,7 @@ namespace ts { emptyTypeLiteralSymbol.members = createSymbolTable(); const emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined) as ObjectType as GenericType; emptyGenericType.instantiations = new Map(); const anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -1152,7 +1143,7 @@ namespace ts { function createSymbol(flags: SymbolFlags, name: __String, checkFlags?: CheckFlags) { symbolCount++; - const symbol = (new Symbol(flags | SymbolFlags.Transient, name)); + const symbol = (new Symbol(flags | SymbolFlags.Transient, name) as TransientSymbol); symbol.checkFlags = checkFlags || 0; return symbol; } @@ -1326,7 +1317,7 @@ namespace ts { } function mergeModuleAugmentation(moduleName: StringLiteral | Identifier): void { - const moduleAugmentation = moduleName.parent; + const moduleAugmentation = moduleName.parent as ModuleDeclaration; if (moduleAugmentation.symbol.declarations?.[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations @@ -1402,18 +1393,18 @@ namespace ts { } function getSymbolLinks(symbol: Symbol): SymbolLinks { - if (symbol.flags & SymbolFlags.Transient) return symbol; + if (symbol.flags & SymbolFlags.Transient) return symbol as TransientSymbol; const id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = new (SymbolLinks)()); + return symbolLinks[id] || (symbolLinks[id] = new (SymbolLinks as any)()); } function getNodeLinks(node: Node): NodeLinks { const nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = new (NodeLinks)()); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = new (NodeLinks as any)()); } function isGlobalSourceFile(node: Node) { - return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); + return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node as SourceFile); } function getSymbol(symbols: SymbolTable, name: __String, meaning: SymbolFlags): Symbol | undefined { @@ -1578,7 +1569,7 @@ namespace ts { const initializerOfProperty = current.parent && current.parent.kind === SyntaxKind.PropertyDeclaration && - (current.parent).initializer === current; + (current.parent as PropertyDeclaration).initializer === current; if (initializerOfProperty) { if (hasSyntacticModifier(current.parent, ModifierFlags.Static)) { @@ -1640,7 +1631,7 @@ namespace ts { function useOuterVariableScopeInParameter(result: Symbol, location: Node, lastLocation: Node) { const target = getEmitScriptTarget(compilerOptions); - const functionLocation = location; + const functionLocation = location as FunctionLikeDeclaration; if (isParameter(lastLocation) && functionLocation.body && result.valueDeclaration @@ -1744,7 +1735,7 @@ namespace ts { if (location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; - if (isFunctionLike(location) && lastLocation && lastLocation !== (location).body) { + if (isFunctionLike(location) && lastLocation && lastLocation !== (location as FunctionLikeDeclaration).body) { // symbol lookup restrictions for function-like declarations // - Type parameters of a function are in scope in the entire function declaration, including the parameter // list and return type. However, local types are only in scope in the function body. @@ -1754,7 +1745,7 @@ namespace ts { if (meaning & result.flags & SymbolFlags.Type && lastLocation.kind !== SyntaxKind.JSDocComment) { useResult = result.flags & SymbolFlags.TypeParameter // type parameters are visible in parameter list, return type and type parameter list - ? lastLocation === (location).type || + ? lastLocation === (location as FunctionLikeDeclaration).type || lastLocation.kind === SyntaxKind.Parameter || lastLocation.kind === SyntaxKind.TypeParameter // local types not visible outside the function body @@ -1773,7 +1764,7 @@ namespace ts { useResult = lastLocation.kind === SyntaxKind.Parameter || ( - lastLocation === (location).type && + lastLocation === (location as FunctionLikeDeclaration).type && !!findAncestor(result.valueDeclaration, isParameter) ); } @@ -1782,7 +1773,7 @@ namespace ts { else if (location.kind === SyntaxKind.ConditionalType) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. - useResult = lastLocation === (location).trueType; + useResult = lastLocation === (location as ConditionalTypeNode).trueType; } if (useResult) { @@ -1796,7 +1787,7 @@ namespace ts { withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location)) break; + if (!isExternalOrCommonJsModule(location as SourceFile)) break; isInExternalModule = true; // falls through case SyntaxKind.ModuleDeclaration: @@ -1886,7 +1877,7 @@ namespace ts { break loop; } if (location.kind === SyntaxKind.ClassExpression && meaning & SymbolFlags.Class) { - const className = (location).name; + const className = (location as ClassExpression).name; if (className && name === className.escapedText) { result = location.symbol; break loop; @@ -1895,7 +1886,7 @@ namespace ts { break; case SyntaxKind.ExpressionWithTypeArguments: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === (location).expression && (location.parent).token === SyntaxKind.ExtendsKeyword) { + if (lastLocation === (location as ExpressionWithTypeArguments).expression && (location.parent as HeritageClause).token === SyntaxKind.ExtendsKeyword) { const container = location.parent.parent; if (isClassLike(container) && (result = lookup(getSymbolOfNode(container).members!, name, meaning & SymbolFlags.Type))) { if (nameNotFoundMessage) { @@ -1947,7 +1938,7 @@ namespace ts { } if (meaning & SymbolFlags.Function) { - const functionName = (location).name; + const functionName = (location as FunctionExpression).name; if (functionName && name === functionName.escapedText) { result = location.symbol; break loop; @@ -2012,9 +2003,9 @@ namespace ts { break; case SyntaxKind.InferType: if (meaning & SymbolFlags.TypeParameter) { - const parameterName = (location).typeParameter.name; + const parameterName = (location as InferTypeNode).typeParameter.name; if (parameterName && name === parameterName.escapedText) { - result = (location).typeParameter.symbol; + result = (location as InferTypeNode).typeParameter.symbol; break loop; } } @@ -2104,7 +2095,7 @@ namespace ts { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. - const propertyName = (propertyWithInvalidInitializer).name; + const propertyName = (propertyWithInvalidInitializer as PropertyDeclaration).name; error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyName), diagnosticName(nameArg!)); return undefined; @@ -2148,7 +2139,7 @@ namespace ts { } // And it cannot refer to any declarations which come after it else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation)); + error(errorLocation, Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), declarationNameToString(errorLocation as Identifier)); } } if (result && errorLocation && meaning & SymbolFlags.Value && result.flags & SymbolFlags.Alias) { @@ -2252,7 +2243,7 @@ namespace ts { // No static member is present. // Check if we're in an instance method and look for a relevant instance member. if (location === container && !hasSyntacticModifier(location, ModifierFlags.Static)) { - const instanceType = (getDeclaredTypeOfSymbol(classSymbol)).thisType!; // TODO: GH#18217 + const instanceType = (getDeclaredTypeOfSymbol(classSymbol) as InterfaceType).thisType!; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -2284,8 +2275,8 @@ namespace ts { case SyntaxKind.PropertyAccessExpression: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; case SyntaxKind.ExpressionWithTypeArguments: - if (isEntityNameExpression((node).expression)) { - return (node).expression; + if (isEntityNameExpression((node as ExpressionWithTypeArguments).expression)) { + return (node as ExpressionWithTypeArguments).expression as EntityNameExpression; } // falls through default: @@ -2496,12 +2487,12 @@ namespace ts { function isAliasSymbolDeclaration(node: Node): boolean { return node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration - || node.kind === SyntaxKind.ImportClause && !!(node).name + || node.kind === SyntaxKind.ImportClause && !!(node as ImportClause).name || node.kind === SyntaxKind.NamespaceImport || node.kind === SyntaxKind.NamespaceExport || node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier - || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) + || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node as ExportAssignment) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) @@ -2727,7 +2718,7 @@ namespace ts { function getPropertyOfVariable(symbol: Symbol, name: __String): Symbol | undefined { if (symbol.flags & SymbolFlags.Variable) { - const typeAnnotation = (symbol.valueDeclaration).type; + const typeAnnotation = (symbol.valueDeclaration as VariableDeclaration).type; if (typeAnnotation) { return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } @@ -2923,19 +2914,19 @@ namespace ts { case SyntaxKind.ImportClause: return getTargetOfImportClause(node as ImportClause, dontRecursivelyResolve); case SyntaxKind.NamespaceImport: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + return getTargetOfNamespaceImport(node as NamespaceImport, dontRecursivelyResolve); case SyntaxKind.NamespaceExport: - return getTargetOfNamespaceExport(node, dontRecursivelyResolve); + return getTargetOfNamespaceExport(node as NamespaceExport, dontRecursivelyResolve); case SyntaxKind.ImportSpecifier: case SyntaxKind.BindingElement: return getTargetOfImportSpecifier(node as ImportSpecifier | BindingElement, dontRecursivelyResolve); case SyntaxKind.ExportSpecifier: - return getTargetOfExportSpecifier(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node as ExportSpecifier, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve); case SyntaxKind.ExportAssignment: case SyntaxKind.BinaryExpression: - return getTargetOfExportAssignment((node), dontRecursivelyResolve); + return getTargetOfExportAssignment((node as ExportAssignment | BinaryExpression), dontRecursivelyResolve); case SyntaxKind.NamespaceExportDeclaration: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + return getTargetOfNamespaceExportDeclaration(node as NamespaceExportDeclaration, dontRecursivelyResolve); case SyntaxKind.ShorthandPropertyAssignment: return resolveEntityName((node as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*ignoreErrors*/ true, dontRecursivelyResolve); case SyntaxKind.PropertyAssignment: @@ -3082,7 +3073,7 @@ namespace ts { const target = resolveSymbol(symbol); if (target === unknownSymbol || target.flags & SymbolFlags.Value) { // import foo = - checkExpressionCached(node.moduleReference); + checkExpressionCached(node.moduleReference as Expression); } } } @@ -3106,7 +3097,7 @@ namespace ts { // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if (entityName.kind === SyntaxKind.Identifier && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; + entityName = entityName.parent as QualifiedName; } // Check for case 1 and 3 in the above example if (entityName.kind === SyntaxKind.Identifier || entityName.parent.kind === SyntaxKind.QualifiedName) { @@ -3815,8 +3806,8 @@ namespace ts { function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration | undefined { const members = node.members; for (const member of members) { - if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { - return member; + if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member as ConstructorDeclaration).body)) { + return member as ConstructorDeclaration; } } } @@ -3836,21 +3827,21 @@ namespace ts { } function createIntrinsicType(kind: TypeFlags, intrinsicName: string, objectFlags: ObjectFlags = 0): IntrinsicType { - const type = createType(kind); + const type = createType(kind) as IntrinsicType; type.intrinsicName = intrinsicName; type.objectFlags = objectFlags; return type; } function createBooleanType(trueFalseTypes: readonly Type[]): IntrinsicType & UnionType { - const type = getUnionType(trueFalseTypes); + const type = getUnionType(trueFalseTypes) as IntrinsicType & UnionType; type.flags |= TypeFlags.Boolean; type.intrinsicName = "boolean"; return type; } function createObjectType(objectFlags: ObjectFlags, symbol?: Symbol): ObjectType { - const type = createType(TypeFlags.Object); + const type = createType(TypeFlags.Object) as ObjectType; type.objectFlags = objectFlags; type.symbol = symbol!; type.members = undefined; @@ -3867,7 +3858,7 @@ namespace ts { } function createTypeParameter(symbol?: Symbol) { - const type = createType(TypeFlags.TypeParameter); + const type = createType(TypeFlags.TypeParameter) as TypeParameter; if (symbol) type.symbol = symbol; return type; } @@ -3901,7 +3892,7 @@ namespace ts { } function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { - const resolved = type; + const resolved = type as ResolvedType; resolved.members = members; resolved.properties = emptyArray; resolved.callSignatures = callSignatures; @@ -3946,7 +3937,7 @@ namespace ts { } switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location)) { + if (!isExternalOrCommonJsModule(location as SourceFile)) { break; } // falls through @@ -4275,11 +4266,11 @@ namespace ts { } function hasExternalModuleSymbol(declaration: Node) { - return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); + return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration as SourceFile)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration: Node) { - return isModuleWithStringLiteralName(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); + return isModuleWithStringLiteralName(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration as SourceFile)); } function hasVisibleDeclarations(symbol: Symbol, shouldComputeAliasToMakeVisible: boolean): SymbolVisibilityResult | undefined { @@ -4622,21 +4613,21 @@ namespace ts { return symbolToTypeNode(type.symbol, context, SymbolFlags.Type); } if (type.flags & TypeFlags.StringLiteral) { - context.approximateLength += ((type).value.length + 2); - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral((type).value, !!(context.flags & NodeBuilderFlags.UseSingleQuotesForStringLiteralType)), EmitFlags.NoAsciiEscaping)); + context.approximateLength += ((type as StringLiteralType).value.length + 2); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral((type as StringLiteralType).value, !!(context.flags & NodeBuilderFlags.UseSingleQuotesForStringLiteralType)), EmitFlags.NoAsciiEscaping)); } if (type.flags & TypeFlags.NumberLiteral) { - const value = (type).value; + const value = (type as NumberLiteralType).value; context.approximateLength += ("" + value).length; return factory.createLiteralTypeNode(value < 0 ? factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(-value)) : factory.createNumericLiteral(value)); } if (type.flags & TypeFlags.BigIntLiteral) { - context.approximateLength += (pseudoBigIntToString((type).value).length) + 1; - return factory.createLiteralTypeNode((factory.createBigIntLiteral((type).value))); + context.approximateLength += (pseudoBigIntToString((type as BigIntLiteralType).value).length) + 1; + return factory.createLiteralTypeNode((factory.createBigIntLiteral((type as BigIntLiteralType).value))); } if (type.flags & TypeFlags.BooleanLiteral) { - context.approximateLength += (type).intrinsicName.length; - return factory.createLiteralTypeNode((type).intrinsicName === "true" ? factory.createTrue() : factory.createFalse()); + context.approximateLength += (type as IntrinsicType).intrinsicName.length; + return factory.createLiteralTypeNode((type as IntrinsicType).intrinsicName === "true" ? factory.createTrue() : factory.createFalse()); } if (type.flags & TypeFlags.UniqueESSymbol) { if (!(context.flags & NodeBuilderFlags.AllowUniqueESSymbolType)) { @@ -4698,7 +4689,7 @@ namespace ts { if (objectFlags & ObjectFlags.Reference) { Debug.assert(!!(type.flags & TypeFlags.Object)); - return (type).node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type); + return (type as TypeReference).node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type as TypeReference); } if (type.flags & TypeFlags.TypeParameter || objectFlags & ObjectFlags.ClassOrInterface) { if (type.flags & TypeFlags.TypeParameter && contains(context.inferTypeParameters, type)) { @@ -4717,11 +4708,11 @@ namespace ts { ? symbolToTypeNode(type.symbol, context, SymbolFlags.Type) : factory.createTypeReferenceNode(factory.createIdentifier("?"), /*typeArguments*/ undefined); } - if (type.flags & TypeFlags.Union && (type).origin) { - type = (type).origin!; + if (type.flags & TypeFlags.Union && (type as UnionType).origin) { + type = (type as UnionType).origin!; } if (type.flags & (TypeFlags.Union | TypeFlags.Intersection)) { - const types = type.flags & TypeFlags.Union ? formatUnionTypes((type).types) : (type).types; + const types = type.flags & TypeFlags.Union ? formatUnionTypes((type as UnionType).types) : (type as IntersectionType).types; if (length(types) === 1) { return typeToTypeNodeHelper(types[0], context); } @@ -4739,17 +4730,17 @@ namespace ts { if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) { Debug.assert(!!(type.flags & TypeFlags.Object)); // The type is an object literal type. - return createAnonymousTypeNode(type); + return createAnonymousTypeNode(type as ObjectType); } if (type.flags & TypeFlags.Index) { - const indexedType = (type).type; + const indexedType = (type as IndexType).type; context.approximateLength += 6; const indexTypeNode = typeToTypeNodeHelper(indexedType, context); return factory.createTypeOperatorNode(SyntaxKind.KeyOfKeyword, indexTypeNode); } if (type.flags & TypeFlags.TemplateLiteral) { - const texts = (type).texts; - const types = (type).types; + const texts = (type as TemplateLiteralType).texts; + const types = (type as TemplateLiteralType).types; const templateHead = factory.createTemplateHead(texts[0]); const templateSpans = factory.createNodeArray( map(types, (t, i) => factory.createTemplateLiteralTypeSpan( @@ -4759,28 +4750,28 @@ namespace ts { return factory.createTemplateLiteralType(templateHead, templateSpans); } if (type.flags & TypeFlags.StringMapping) { - const typeNode = typeToTypeNodeHelper((type).type, context); - return symbolToTypeNode((type).symbol, context, SymbolFlags.Type, [typeNode]); + const typeNode = typeToTypeNodeHelper((type as StringMappingType).type, context); + return symbolToTypeNode((type as StringMappingType).symbol, context, SymbolFlags.Type, [typeNode]); } if (type.flags & TypeFlags.IndexedAccess) { - const objectTypeNode = typeToTypeNodeHelper((type).objectType, context); - const indexTypeNode = typeToTypeNodeHelper((type).indexType, context); + const objectTypeNode = typeToTypeNodeHelper((type as IndexedAccessType).objectType, context); + const indexTypeNode = typeToTypeNodeHelper((type as IndexedAccessType).indexType, context); context.approximateLength += 2; return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & TypeFlags.Conditional) { - const checkTypeNode = typeToTypeNodeHelper((type).checkType, context); + const checkTypeNode = typeToTypeNodeHelper((type as ConditionalType).checkType, context); const saveInferTypeParameters = context.inferTypeParameters; - context.inferTypeParameters = (type).root.inferTypeParameters; - const extendsTypeNode = typeToTypeNodeHelper((type).extendsType, context); + context.inferTypeParameters = (type as ConditionalType).root.inferTypeParameters; + const extendsTypeNode = typeToTypeNodeHelper((type as ConditionalType).extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type)); - const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type)); + const trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type as ConditionalType)); + const falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type as ConditionalType)); context.approximateLength += 15; return factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & TypeFlags.Substitution) { - return typeToTypeNodeHelper((type).baseType, context); + return typeToTypeNodeHelper((type as SubstitutionType).baseType, context); } return Debug.fail("Should be unreachable."); @@ -4802,8 +4793,8 @@ namespace ts { function createMappedTypeNodeFromType(type: MappedType) { Debug.assert(!!(type.flags & TypeFlags.Object)); - const readonlyToken = type.declaration.readonlyToken ? factory.createToken(type.declaration.readonlyToken.kind) : undefined; - const questionToken = type.declaration.questionToken ? factory.createToken(type.declaration.questionToken.kind) : undefined; + const readonlyToken = type.declaration.readonlyToken ? factory.createToken(type.declaration.readonlyToken.kind) as ReadonlyKeyword | PlusToken | MinusToken : undefined; + const questionToken = type.declaration.questionToken ? factory.createToken(type.declaration.questionToken.kind) as QuestionToken | PlusToken | MinusToken : undefined; let appropriateConstraintTypeNode: TypeNode; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } @@ -4875,7 +4866,7 @@ namespace ts { function visitAndTransformType(type: Type, transform: (type: Type) => T) { const typeId = type.id; const isConstructorObject = getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; - const id = getObjectFlags(type) & ObjectFlags.Reference && (type).node ? "N" + getNodeId((type).node!) : + const id = getObjectFlags(type) & ObjectFlags.Reference && (type as TypeReference).node ? "N" + getNodeId((type as TypeReference).node!) : type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) : undefined; // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead @@ -4948,14 +4939,14 @@ namespace ts { if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; - const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context) as FunctionTypeNode; return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { const signature = resolved.constructSignatures[0]; - const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context); + const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType, context) as ConstructorTypeNode; return signatureNode; } } @@ -5032,12 +5023,12 @@ namespace ts { } } const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode(tupleConstituentNodes), EmitFlags.SingleLine); - return (type.target).readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode; + return (type.target as TupleType).readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode; } } if (context.encounteredError || (context.flags & NodeBuilderFlags.AllowEmptyTuple)) { const tupleTypeNode = setEmitFlags(factory.createTupleTypeNode([]), EmitFlags.SingleLine); - return (type.target).readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode; + return (type.target as TupleType).readonly ? factory.createTypeOperatorNode(SyntaxKind.ReadonlyKeyword, tupleTypeNode) : tupleTypeNode; } context.encounteredError = true; return undefined!; // TODO: GH#18217 @@ -5158,11 +5149,11 @@ namespace ts { } const typeElements: TypeElement[] = []; for (const signature of resolvedType.callSignatures) { - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature, context) as CallSignatureDeclaration); } for (const signature of resolvedType.constructSignatures) { if (signature.flags & SignatureFlags.Abstract) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature, context) as ConstructSignatureDeclaration); } if (resolvedType.stringIndexInfo) { let indexSignature: IndexSignatureDeclaration; @@ -5263,7 +5254,7 @@ namespace ts { if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { const signatures = getSignaturesOfType(filterType(propertyType, t => !(t.flags & TypeFlags.Undefined)), SignatureKind.Call); for (const signature of signatures) { - const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context, { name: propertyName, questionToken: optionalToken }); + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature, context, { name: propertyName, questionToken: optionalToken }) as MethodSignature; typeElements.push(preserveCommentsOn(methodDeclaration)); } } @@ -5540,7 +5531,7 @@ namespace ts { return parameterNode; function cloneBindingName(node: BindingName): BindingName { - return elideInitializerAndSetEmitFlags(node); + return elideInitializerAndSetEmitFlags(node) as BindingName; function elideInitializerAndSetEmitFlags(node: Node): Node { if (context.tracker.trackSymbol && isComputedPropertyName(node) && isLateBindableName(node)) { trackComputedName(node.expression, context.enclosingDeclaration, context); @@ -6018,7 +6009,7 @@ namespace ts { const nameType = getSymbolLinks(symbol).nameType; if (nameType) { if (nameType.flags & TypeFlags.StringOrNumberLiteral) { - const name = "" + (nameType).value; + const name = "" + (nameType as StringLiteralType | NumberLiteralType).value; if (!isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { return factory.createStringLiteral(name, !!singleQuote); } @@ -6028,7 +6019,7 @@ namespace ts { return createPropertyNameNodeForIdentifierOrLiteral(name); } if (nameType.flags & TypeFlags.UniqueESSymbol) { - return factory.createComputedPropertyName(symbolToExpression((nameType).symbol, context, SymbolFlags.Value)); + return factory.createComputedPropertyName(symbolToExpression((nameType as UniqueESSymbolType).symbol, context, SymbolFlags.Value)); } } } @@ -7761,10 +7752,10 @@ namespace ts { flags |= t.flags; if (!(t.flags & TypeFlags.Nullable)) { if (t.flags & (TypeFlags.BooleanLiteral | TypeFlags.EnumLiteral)) { - const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t); + const baseType = t.flags & TypeFlags.BooleanLiteral ? booleanType : getBaseTypeOfEnumLiteralType(t as LiteralType); if (baseType.flags & TypeFlags.Union) { - const count = (baseType).types.length; - if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType((baseType).types[count - 1])) { + const count = (baseType as UnionType).types.length; + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType((baseType as UnionType).types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -7835,7 +7826,7 @@ namespace ts { const nameType = getSymbolLinks(symbol).nameType; if (nameType) { if (nameType.flags & TypeFlags.StringOrNumberLiteral) { - const name = "" + (nameType).value; + const name = "" + (nameType as StringLiteralType | NumberLiteralType).value; if (!isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { return `"${escapeString(name, CharacterCodes.doubleQuote)}"`; } @@ -7845,7 +7836,7 @@ namespace ts { return name; } if (nameType.flags & TypeFlags.UniqueESSymbol) { - return `[${getNameOfSymbolAsWritten((nameType).symbol, context)}]`; + return `[${getNameOfSymbolAsWritten((nameType as UniqueESSymbolType).symbol, context)}]`; } } } @@ -7890,7 +7881,7 @@ namespace ts { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((declaration.parent).name); + return declarationNameToString((declaration.parent as VariableDeclaration).name); } switch (declaration.kind) { case SyntaxKind.ClassExpression: @@ -8017,7 +8008,7 @@ namespace ts { exportSymbol = resolveName(node, node.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { - exportSymbol = getTargetOfExportSpecifier(node.parent, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + exportSymbol = getTargetOfExportSpecifier(node.parent as ExportSpecifier, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } let result: Node[] | undefined; let visited: Set | undefined; @@ -8041,7 +8032,7 @@ namespace ts { if (isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible - const internalModuleReference = declaration.moduleReference; + const internalModuleReference = declaration.moduleReference as Identifier | QualifiedName; const firstIdentifier = getFirstIdentifier(internalModuleReference); const importSymbol = resolveName(declaration, firstIdentifier.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, undefined, undefined, /*isUse*/ false); @@ -8097,17 +8088,17 @@ namespace ts { function hasType(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): boolean { switch (propertyName) { case TypeSystemPropertyName.Type: - return !!getSymbolLinks(target).type; + return !!getSymbolLinks(target as Symbol).type; case TypeSystemPropertyName.EnumTagType: return !!(getNodeLinks(target as JSDocEnumTag).resolvedEnumType); case TypeSystemPropertyName.DeclaredType: - return !!getSymbolLinks(target).declaredType; + return !!getSymbolLinks(target as Symbol).declaredType; case TypeSystemPropertyName.ResolvedBaseConstructorType: - return !!(target).resolvedBaseConstructorType; + return !!(target as InterfaceType).resolvedBaseConstructorType; case TypeSystemPropertyName.ResolvedReturnType: - return !!(target).resolvedReturnType; + return !!(target as Signature).resolvedReturnType; case TypeSystemPropertyName.ImmediateBaseConstraint: - return !!(target).immediateBaseConstraint; + return !!(target as Type).immediateBaseConstraint; case TypeSystemPropertyName.ResolvedTypeArguments: return !!(target as TypeReference).resolvedTypeArguments; case TypeSystemPropertyName.ResolvedBaseTypes: @@ -8147,8 +8138,8 @@ namespace ts { // Every class automatically contains a static property member named 'prototype', // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. // It is an error to explicitly declare a static property member with the name 'prototype'. - const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)!); - return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, _ => anyType)) : classType; + const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)!) as InterfaceType; + return classType.typeParameters ? createTypeReference(classType as GenericType, map(classType.typeParameters, _ => anyType)) : classType; } // Return the type of the given property in the given type, or undefined if no such property exists @@ -8254,30 +8245,30 @@ namespace ts { switch (ancestor.kind) { case SyntaxKind.BindingElement: case SyntaxKind.PropertyAssignment: - return getSyntheticElementAccess(ancestor); + return getSyntheticElementAccess(ancestor as BindingElement | PropertyAssignment); case SyntaxKind.ArrayLiteralExpression: - return getSyntheticElementAccess(node.parent); + return getSyntheticElementAccess(node.parent as Expression); case SyntaxKind.VariableDeclaration: - return (ancestor).initializer; + return (ancestor as VariableDeclaration).initializer; case SyntaxKind.BinaryExpression: - return (ancestor).right; + return (ancestor as BinaryExpression).right; } } function getDestructuringPropertyName(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression) { const parent = node.parent; if (node.kind === SyntaxKind.BindingElement && parent.kind === SyntaxKind.ObjectBindingPattern) { - return getLiteralPropertyNameText((node).propertyName || (node).name); + return getLiteralPropertyNameText((node as BindingElement).propertyName || (node as BindingElement).name as Identifier); } if (node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) { - return getLiteralPropertyNameText((node).name); + return getLiteralPropertyNameText((node as PropertyAssignment | ShorthandPropertyAssignment).name); } - return "" + (>(parent).elements).indexOf(node); + return "" + ((parent as BindingPattern | ArrayLiteralExpression).elements as NodeArray).indexOf(node); } function getLiteralPropertyNameText(name: PropertyName) { const type = getLiteralTypeFromPropertyName(name); - return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + (type).value : undefined; + return type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral) ? "" + (type as StringLiteralType | NumberLiteralType).value : undefined; } /** Return the inferred type for a binding element */ @@ -8315,9 +8306,9 @@ namespace ts { } else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - const name = declaration.propertyName || declaration.name; + const name = declaration.propertyName || declaration.name as Identifier; const indexType = getLiteralTypeFromPropertyName(name); - const declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, AccessFlags.ExpressionPosition); + const declaredType = getIndexedAccessType(parentType, indexType, AccessFlags.ExpressionPosition, name); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -8332,13 +8323,13 @@ namespace ts { // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. type = everyType(parentType, isTupleType) ? - mapType(parentType, t => sliceTupleType(t, index)) : + mapType(parentType, t => sliceTupleType(t as TupleTypeReference, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getLiteralType(index); - const accessFlags = hasDefaultValue(declaration) ? AccessFlags.NoTupleBoundsCheck : 0; - const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | AccessFlags.ExpressionPosition) || errorType; + const accessFlags = AccessFlags.ExpressionPosition | (hasDefaultValue(declaration) ? AccessFlags.NoTupleBoundsCheck : 0); + const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -8366,12 +8357,12 @@ namespace ts { function isNullOrUndefined(node: Expression) { const expr = skipParentheses(node); - return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; + return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr as Identifier) === undefinedSymbol; } function isEmptyArrayLiteral(node: Expression) { const expr = skipParentheses(node); - return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr).elements.length === 0; + return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr as ArrayLiteralExpression).elements.length === 0; } function addOptionality(type: Type, optional = true): Type { @@ -8397,7 +8388,7 @@ namespace ts { } if (isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); + return getTypeForBindingElement(declaration as BindingElement); } const isOptional = includeOptionality && ( @@ -8428,7 +8419,7 @@ namespace ts { } if (isParameter(declaration)) { - const func = declaration.parent; + const func = declaration.parent as FunctionLikeDeclaration; // For a parameter of a set accessor, use the type of the get accessor if one is present if (func.kind === SyntaxKind.SetAccessor && hasBindableName(func)) { const getter = getDeclarationOfKind(getSymbolOfNode(declaration.parent), SyntaxKind.GetAccessor); @@ -8508,7 +8499,7 @@ namespace ts { links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, declaration => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== SyntaxKind.ElementAccessExpression || isStringOrNumericLiteralLike((declaration.left).argumentExpression)) && + (declaration.left.kind !== SyntaxKind.ElementAccessExpression || isStringOrNumericLiteralLike((declaration.left as ElementAccessExpression).argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration)); } return links.isConstructorDeclaredProperty; @@ -8849,7 +8840,7 @@ namespace ts { let stringIndexInfo: IndexInfo | undefined; let objectFlags = ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectOrArrayLiteral; forEach(pattern.elements, e => { - const name = e.propertyName || e.name; + const name = e.propertyName || e.name as Identifier; if (e.dotDotDotToken) { stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); return; @@ -8888,7 +8879,7 @@ namespace ts { const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); const minLength = findLastIndex(elements, e => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1; const elementFlags = map(elements, (e, i) => e === restElement ? ElementFlags.Rest : i >= minLength ? ElementFlags.Optional : ElementFlags.Required); - let result = createTupleType(elementTypes, elementFlags); + let result = createTupleType(elementTypes, elementFlags) as TypeReference; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; @@ -9038,7 +9029,7 @@ namespace ts { } let type: Type; if (declaration.kind === SyntaxKind.ExportAssignment) { - type = widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration).expression), declaration); + type = widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration as ExportAssignment).expression), declaration); } else if ( isBinaryExpression(declaration) || @@ -9323,7 +9314,7 @@ namespace ts { } function reportCircularityError(symbol: Symbol) { - const declaration = symbol.valueDeclaration; + const declaration = symbol.valueDeclaration as VariableLikeDeclaration; // Check if variable has type annotation that circularly references the variable itself if (getEffectiveTypeAnnotationNode(declaration)) { error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, @@ -9331,7 +9322,7 @@ namespace ts { return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== SyntaxKind.Parameter || (declaration).initializer)) { + if (noImplicitAny && (declaration.kind !== SyntaxKind.Parameter || (declaration as HasInitializer).initializer)) { error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } @@ -9397,11 +9388,11 @@ namespace ts { return type !== undefined && target !== undefined && (getObjectFlags(type) & ObjectFlags.Reference) !== 0 - && (type).target === target; + && (type as TypeReference).target === target; } function getTargetType(type: Type): Type { - return getObjectFlags(type) & ObjectFlags.Reference ? (type).target : type; + return getObjectFlags(type) & ObjectFlags.Reference ? (type as TypeReference).target : type; } // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. @@ -9409,11 +9400,11 @@ namespace ts { return check(type); function check(type: Type): boolean { if (getObjectFlags(type) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference)) { - const target = getTargetType(type); + const target = getTargetType(type) as InterfaceType; return target === checkBase || some(getBaseTypes(target), check); } else if (type.flags & TypeFlags.Intersection) { - return some((type).types, check); + return some((type as IntersectionType).types, check); } return false; } @@ -9469,12 +9460,12 @@ namespace ts { case SyntaxKind.ConditionalType: { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); if (node.kind === SyntaxKind.MappedType) { - return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode((node).typeParameter))); + return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode((node as MappedTypeNode).typeParameter))); } else if (node.kind === SyntaxKind.ConditionalType) { - return concatenate(outerTypeParameters, getInferTypeParameters(node)); + return concatenate(outerTypeParameters, getInferTypeParameters(node as ConditionalTypeNode)); } - const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); + const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node as DeclarationWithTypeParameters)); const thisType = includeThisTypes && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.InterfaceDeclaration || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node as ClassLikeDeclaration | InterfaceDeclaration)).thisType; @@ -9516,7 +9507,7 @@ namespace ts { node.kind === SyntaxKind.ClassExpression || isJSConstructor(node) || isTypeAlias(node)) { - const declaration = node; + const declaration = node as InterfaceDeclaration | TypeAliasDeclaration | JSDocTypedefTag | JSDocCallbackTag; result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration)); } } @@ -9581,7 +9572,7 @@ namespace ts { */ function getBaseConstructorTypeOfClass(type: InterfaceType): Type { if (!type.resolvedBaseConstructorType) { - const decl = type.symbol.valueDeclaration; + const decl = type.symbol.valueDeclaration as ClassLikeDeclaration; const extended = getEffectiveBaseTypeNode(decl); const baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { @@ -9598,7 +9589,7 @@ namespace ts { if (baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. - resolveStructuredTypeMembers(baseConstructorType); + resolveStructuredTypeMembers(baseConstructorType as ObjectType); } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); @@ -9636,7 +9627,7 @@ namespace ts { const implementsType = getTypeFromTypeNode(node); if (implementsType !== errorType) { if (resolvedImplementsTypes === emptyArray) { - resolvedImplementsTypes = [implementsType]; + resolvedImplementsTypes = [implementsType as ObjectType]; } else { resolvedImplementsTypes.push(implementsType); @@ -9656,7 +9647,7 @@ namespace ts { if (!type.baseTypesResolved) { if (pushTypeResolution(type, TypeSystemPropertyName.ResolvedBaseTypes)) { if (type.objectFlags & ObjectFlags.Tuple) { - type.resolvedBaseTypes = [getTupleBaseType(type)]; + type.resolvedBaseTypes = [getTupleBaseType(type as TupleType)]; } else if (type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { if (type.symbol.flags & SymbolFlags.Class) { @@ -9746,10 +9737,10 @@ namespace ts { function areAllOuterTypeParametersApplied(type: Type): boolean { // TODO: GH#18217 Shouldn't this take an InterfaceType? // An unapplied type parameter has its symbol still the same as the matching argument symbol. // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. - const outerTypeParameters = (type).outerTypeParameters; + const outerTypeParameters = (type as InterfaceType).outerTypeParameters; if (outerTypeParameters) { const last = outerTypeParameters.length - 1; - const typeArguments = getTypeArguments(type); + const typeArguments = getTypeArguments(type as TypeReference); return outerTypeParameters[last].symbol !== typeArguments[last].symbol; } return true; @@ -9766,21 +9757,21 @@ namespace ts { // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. return !!(type.flags & (TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.Any) && !isGenericMappedType(type) || - type.flags & TypeFlags.Intersection && every((type).types, isValidBaseType)); + type.flags & TypeFlags.Intersection && every((type as IntersectionType).types, isValidBaseType)); } function resolveBaseTypesOfInterface(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; if (type.symbol.declarations) { for (const declaration of type.symbol.declarations) { - if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { - for (const node of getInterfaceBaseTypeNodes(declaration)!) { + if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration)) { + for (const node of getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration)!) { const baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; + type.resolvedBaseTypes = [baseType as ObjectType]; } else { type.resolvedBaseTypes.push(baseType); @@ -9816,7 +9807,7 @@ namespace ts { if (declaration.flags & NodeFlags.ContainsThis) { return false; } - const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); + const baseTypeNodes = getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration); if (baseTypeNodes) { for (const node of baseTypeNodes) { if (isEntityNameExpression(node.expression)) { @@ -9843,7 +9834,7 @@ namespace ts { symbol = links = merged; } - const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol); + const type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol) as InterfaceType; const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type @@ -9856,16 +9847,16 @@ namespace ts { type.typeParameters = concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - (type).instantiations = new Map(); - (type).instantiations.set(getTypeListId(type.typeParameters), type); - (type).target = type; - (type).resolvedTypeArguments = type.typeParameters; + (type as GenericType).instantiations = new Map(); + (type as GenericType).instantiations.set(getTypeListId(type.typeParameters), type as GenericType); + (type as GenericType).target = type as GenericType; + (type as GenericType).resolvedTypeArguments = type.typeParameters; type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; type.thisType.constraint = type; } } - return links.declaredType; + return links.declaredType as InterfaceType; } function getDeclaredTypeOfTypeAlias(symbol: Symbol): Type { @@ -9906,7 +9897,7 @@ namespace ts { return true; } else if (expr.kind === SyntaxKind.BinaryExpression) { - return isStringConcatExpression((expr).left) && isStringConcatExpression((expr).right); + return isStringConcatExpression((expr as BinaryExpression).left) && isStringConcatExpression((expr as BinaryExpression).right); } return false; } @@ -9922,10 +9913,10 @@ namespace ts { case SyntaxKind.NoSubstitutionTemplateLiteral: return true; case SyntaxKind.PrefixUnaryExpression: - return (expr).operator === SyntaxKind.MinusToken && - (expr).operand.kind === SyntaxKind.NumericLiteral; + return (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && + (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.NumericLiteral; case SyntaxKind.Identifier: - return nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports!.get((expr).escapedText); + return nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports!.get((expr as Identifier).escapedText); case SyntaxKind.BinaryExpression: return isStringConcatExpression(expr); default: @@ -9942,7 +9933,7 @@ namespace ts { if (symbol.declarations) { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration).members) { + for (const member of (declaration as EnumDeclaration).members) { if (member.initializer && isStringLiteralLike(member.initializer)) { return links.enumKind = EnumKind.Literal; } @@ -9971,7 +9962,7 @@ namespace ts { if (symbol.declarations) { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration).members) { + for (const member of (declaration as EnumDeclaration).members) { const value = getEnumMemberValue(member); const memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; @@ -10062,7 +10053,7 @@ namespace ts { case SyntaxKind.LiteralType: return true; case SyntaxKind.ArrayType: - return isThislessType((node).elementType); + return isThislessType((node as ArrayTypeNode).elementType); case SyntaxKind.TypeReference: return !(node as TypeReferenceNode).typeArguments || (node as TypeReferenceNode).typeArguments!.every(isThislessType); } @@ -10111,13 +10102,13 @@ namespace ts { switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - return isThislessVariableLikeDeclaration(declaration); + return isThislessVariableLikeDeclaration(declaration as VariableLikeDeclaration); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return isThislessFunctionLikeDeclaration(declaration); + return isThislessFunctionLikeDeclaration(declaration as FunctionLikeDeclaration | AccessorDeclaration); } } } @@ -10147,20 +10138,20 @@ namespace ts { } function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { - if (!(type).declaredProperties) { + if (!(type as InterfaceTypeWithDeclaredMembers).declaredProperties) { const symbol = type.symbol; const members = getMembersOfSymbol(symbol); - (type).declaredProperties = getNamedMembers(members); + (type as InterfaceTypeWithDeclaredMembers).declaredProperties = getNamedMembers(members); // Start with signatures at empty array in case of recursive types - (type).declaredCallSignatures = emptyArray; - (type).declaredConstructSignatures = emptyArray; + (type as InterfaceTypeWithDeclaredMembers).declaredCallSignatures = emptyArray; + (type as InterfaceTypeWithDeclaredMembers).declaredConstructSignatures = emptyArray; - (type).declaredCallSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.Call)); - (type).declaredConstructSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.New)); - (type).declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String); - (type).declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number); + (type as InterfaceTypeWithDeclaredMembers).declaredCallSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.Call)); + (type as InterfaceTypeWithDeclaredMembers).declaredConstructSignatures = getSignaturesOfSymbol(members.get(InternalSymbolName.New)); + (type as InterfaceTypeWithDeclaredMembers).declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String); + (type as InterfaceTypeWithDeclaredMembers).declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number); } - return type; + return type as InterfaceTypeWithDeclaredMembers; } /** @@ -10220,10 +10211,10 @@ namespace ts { */ function getPropertyNameFromType(type: StringLiteralType | NumberLiteralType | UniqueESSymbolType): __String { if (type.flags & TypeFlags.UniqueESSymbol) { - return (type).escapedName; + return (type as UniqueESSymbolType).escapedName; } if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { - return escapeLeadingUnderscores("" + (type).value); + return escapeLeadingUnderscores("" + (type as StringLiteralType | NumberLiteralType).value); } return Debug.fail(); } @@ -10405,16 +10396,16 @@ namespace ts { function getTypeWithThisArgument(type: Type, thisArgument?: Type, needApparentType?: boolean): Type { if (getObjectFlags(type) & ObjectFlags.Reference) { - const target = (type).target; - const typeArguments = getTypeArguments(type); + const target = (type as TypeReference).target; + const typeArguments = getTypeArguments(type as TypeReference); if (length(target.typeParameters) === length(typeArguments)) { const ref = createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType!])); return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & TypeFlags.Intersection) { - const types = sameMap((type).types, t => getTypeWithThisArgument(t, thisArgument, needApparentType)); - return types !== (type).types ? getIntersectionType(types) : type; + const types = sameMap((type as IntersectionType).types, t => getTypeWithThisArgument(t, thisArgument, needApparentType)); + return types !== (type as IntersectionType).types ? getIntersectionType(types) : type; } return needApparentType ? getApparentType(type) : type; } @@ -11053,24 +11044,24 @@ namespace ts { // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). function getLowerBoundOfKeyType(type: Type): Type { if (type.flags & TypeFlags.Index) { - const t = getApparentType((type).type); + const t = getApparentType((type as IndexType).type); return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t); } if (type.flags & TypeFlags.Conditional) { - if ((type).root.isDistributive) { - const checkType = (type).checkType; + if ((type as ConditionalType).root.isDistributive) { + const checkType = (type as ConditionalType).checkType; const constraint = getLowerBoundOfKeyType(checkType); if (constraint !== checkType) { - return getConditionalTypeInstantiation(type, prependTypeMapping((type).root.checkType, constraint, (type).mapper)); + return getConditionalTypeInstantiation(type as ConditionalType, prependTypeMapping((type as ConditionalType).root.checkType, constraint, (type as ConditionalType).mapper)); } } return type; } if (type.flags & TypeFlags.Union) { - return mapType(type, getLowerBoundOfKeyType); + return mapType(type as UnionType, getLowerBoundOfKeyType); } if (type.flags & TypeFlags.Intersection) { - return getIntersectionType(sameMap((type).types, getLowerBoundOfKeyType)); + return getIntersectionType(sameMap((type as UnionType).types, getLowerBoundOfKeyType)); } return type; } @@ -11090,8 +11081,8 @@ namespace ts { // and T as the template type. const typeParameter = getTypeParameterFromMappedType(type); const constraintType = getConstraintTypeFromMappedType(type); - const nameType = getNameTypeFromMappedType(type.target || type); - const templateType = getTemplateTypeFromMappedType(type.target || type); + const nameType = getNameTypeFromMappedType(type.target as MappedType || type); + const templateType = getTemplateTypeFromMappedType(type.target as MappedType || type); const modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' const templateModifiers = getMappedTypeModifiers(type); const include = keyofStringsOnly ? TypeFlags.StringLiteral : TypeFlags.StringOrNumberLiteralOrUnique; @@ -11138,8 +11129,8 @@ namespace ts { !(templateModifiers & MappedTypeModifiers.ExcludeReadonly) && modifiersProp && isReadonlySymbol(modifiersProp)); const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & SymbolFlags.Optional; const lateFlag: CheckFlags = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0; - const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName, - lateFlag | CheckFlags.Mapped | (isReadonly ? CheckFlags.Readonly : 0) | (stripOptional ? CheckFlags.StripOptional : 0)); + const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName, + lateFlag | CheckFlags.Mapped | (isReadonly ? CheckFlags.Readonly : 0) | (stripOptional ? CheckFlags.StripOptional : 0)) as MappedSymbol; prop.mappedType = type; prop.nameType = propNameType; prop.keyType = keyType; @@ -11171,7 +11162,7 @@ namespace ts { mappedType.containsError = true; return errorType; } - const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType); + const templateType = getTemplateTypeFromMappedType(mappedType.target as MappedType || mappedType); const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.keyType); const propType = instantiateType(templateType, mapper); // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the @@ -11219,7 +11210,7 @@ namespace ts { function isMappedTypeWithKeyofConstraintDeclaration(type: MappedType) { const constraintDeclaration = getConstraintDeclarationForMappedType(type)!; // TODO: GH#18217 return constraintDeclaration.kind === SyntaxKind.TypeOperator && - (constraintDeclaration).operator === SyntaxKind.KeyOfKeyword; + (constraintDeclaration as TypeOperatorNode).operator === SyntaxKind.KeyOfKeyword; } function getModifiersTypeFromMappedType(type: MappedType) { @@ -11228,16 +11219,16 @@ namespace ts { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode((getConstraintDeclarationForMappedType(type)).type), type.mapper); + type.modifiersType = instantiateType(getTypeFromTypeNode((getConstraintDeclarationForMappedType(type) as TypeOperatorNode).type), type.mapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', // the modifiers type is T. Otherwise, the modifiers type is unknown. - const declaredType = getTypeFromMappedTypeNode(type.declaration); + const declaredType = getTypeFromMappedTypeNode(type.declaration) as MappedType; const constraint = getConstraintTypeFromMappedType(declaredType); - const extendedConstraint = constraint && constraint.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & TypeFlags.Index ? instantiateType((extendedConstraint).type, type.mapper) : unknownType; + const extendedConstraint = constraint && constraint.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(constraint as TypeParameter) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & TypeFlags.Index ? instantiateType((extendedConstraint as IndexType).type, type.mapper) : unknownType; } } return type.modifiersType; @@ -11261,46 +11252,46 @@ namespace ts { } function isPartialMappedType(type: Type) { - return !!(getObjectFlags(type) & ObjectFlags.Mapped && getMappedTypeModifiers(type) & MappedTypeModifiers.IncludeOptional); + return !!(getObjectFlags(type) & ObjectFlags.Mapped && getMappedTypeModifiers(type as MappedType) & MappedTypeModifiers.IncludeOptional); } function isGenericMappedType(type: Type): type is MappedType { - return !!(getObjectFlags(type) & ObjectFlags.Mapped) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(getObjectFlags(type) & ObjectFlags.Mapped) && isGenericIndexType(getConstraintTypeFromMappedType(type as MappedType)); } function resolveStructuredTypeMembers(type: StructuredType): ResolvedType { - if (!(type).members) { + if (!(type as ResolvedType).members) { if (type.flags & TypeFlags.Object) { - if ((type).objectFlags & ObjectFlags.Reference) { - resolveTypeReferenceMembers(type); + if ((type as ObjectType).objectFlags & ObjectFlags.Reference) { + resolveTypeReferenceMembers(type as TypeReference); } - else if ((type).objectFlags & ObjectFlags.ClassOrInterface) { - resolveClassOrInterfaceMembers(type); + else if ((type as ObjectType).objectFlags & ObjectFlags.ClassOrInterface) { + resolveClassOrInterfaceMembers(type as InterfaceType); } - else if ((type).objectFlags & ObjectFlags.ReverseMapped) { + else if ((type as ReverseMappedType).objectFlags & ObjectFlags.ReverseMapped) { resolveReverseMappedTypeMembers(type as ReverseMappedType); } - else if ((type).objectFlags & ObjectFlags.Anonymous) { - resolveAnonymousTypeMembers(type); + else if ((type as ObjectType).objectFlags & ObjectFlags.Anonymous) { + resolveAnonymousTypeMembers(type as AnonymousType); } - else if ((type).objectFlags & ObjectFlags.Mapped) { - resolveMappedTypeMembers(type); + else if ((type as MappedType).objectFlags & ObjectFlags.Mapped) { + resolveMappedTypeMembers(type as MappedType); } } else if (type.flags & TypeFlags.Union) { - resolveUnionTypeMembers(type); + resolveUnionTypeMembers(type as UnionType); } else if (type.flags & TypeFlags.Intersection) { - resolveIntersectionTypeMembers(type); + resolveIntersectionTypeMembers(type as IntersectionType); } } - return type; + return type as ResolvedType; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type: Type): Symbol[] { if (type.flags & TypeFlags.Object) { - return resolveStructuredTypeMembers(type).properties; + return resolveStructuredTypeMembers(type as ObjectType).properties; } return emptyArray; } @@ -11310,7 +11301,7 @@ namespace ts { */ function getPropertyOfObjectType(type: Type, name: __String): Symbol | undefined { if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); const symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; @@ -11344,7 +11335,7 @@ namespace ts { function getPropertiesOfType(type: Type): Symbol[] { type = getReducedApparentType(type); return type.flags & TypeFlags.UnionOrIntersection ? - getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfUnionOrIntersectionType(type as UnionType) : getPropertiesOfObjectType(type); } @@ -11378,9 +11369,9 @@ namespace ts { } function getConstraintOfType(type: InstantiableType | UnionOrIntersectionType): Type | undefined { - return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type) : - type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type) : - type.flags & TypeFlags.Conditional ? getConstraintOfConditionalType(type) : + return type.flags & TypeFlags.TypeParameter ? getConstraintOfTypeParameter(type as TypeParameter) : + type.flags & TypeFlags.IndexedAccess ? getConstraintOfIndexedAccess(type as IndexedAccessType) : + type.flags & TypeFlags.Conditional ? getConstraintOfConditionalType(type as ConditionalType) : getBaseConstraintOfType(type); } @@ -11400,14 +11391,14 @@ namespace ts { function getConstraintFromIndexedAccess(type: IndexedAccessType) { const indexConstraint = getSimplifiedTypeOrConstraint(type.indexType); if (indexConstraint && indexConstraint !== type.indexType) { - const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.noUncheckedIndexedAccessCandidate); + const indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags); if (indexedAccess) { return indexedAccess; } } const objectConstraint = getSimplifiedTypeOrConstraint(type.objectType); if (objectConstraint && objectConstraint !== type.objectType) { - return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.noUncheckedIndexedAccessCandidate); + return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.accessFlags); } return undefined; } @@ -11499,7 +11490,7 @@ namespace ts { function getBaseConstraintOfType(type: Type): Type | undefined { if (type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral | TypeFlags.StringMapping)) { - const constraint = getResolvedBaseConstraint(type); + const constraint = getResolvedBaseConstraint(type as InstantiableType | UnionOrIntersectionType); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } return type.flags & TypeFlags.Index ? keyofConstraintType : undefined; @@ -11548,7 +11539,7 @@ namespace ts { } if (!popTypeResolution()) { if (t.flags & TypeFlags.TypeParameter) { - const errorNode = getConstraintDeclaration(t); + const errorNode = getConstraintDeclaration(t as TypeParameter); if (errorNode) { const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) { @@ -11570,13 +11561,13 @@ namespace ts { function computeBaseConstraint(t: Type): Type | undefined { if (t.flags & TypeFlags.TypeParameter) { - const constraint = getConstraintFromTypeParameter(t); + const constraint = getConstraintFromTypeParameter(t as TypeParameter); return (t as TypeParameter).isThisType || !constraint ? constraint : getBaseConstraint(constraint); } if (t.flags & TypeFlags.UnionOrIntersection) { - const types = (t).types; + const types = (t as UnionOrIntersectionType).types; const baseTypes: Type[] = []; let different = false; for (const type of types) { @@ -11602,26 +11593,26 @@ namespace ts { return keyofConstraintType; } if (t.flags & TypeFlags.TemplateLiteral) { - const types = (t).types; + const types = (t as TemplateLiteralType).types; const constraints = mapDefined(types, getBaseConstraint); - return constraints.length === types.length ? getTemplateLiteralType((t).texts, constraints) : stringType; + return constraints.length === types.length ? getTemplateLiteralType((t as TemplateLiteralType).texts, constraints) : stringType; } if (t.flags & TypeFlags.StringMapping) { - const constraint = getBaseConstraint((t).type); - return constraint ? getStringMappingType((t).symbol, constraint) : stringType; + const constraint = getBaseConstraint((t as StringMappingType).type); + return constraint ? getStringMappingType((t as StringMappingType).symbol, constraint) : stringType; } if (t.flags & TypeFlags.IndexedAccess) { - const baseObjectType = getBaseConstraint((t).objectType); - const baseIndexType = getBaseConstraint((t).indexType); - const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, (t).noUncheckedIndexedAccessCandidate); + const baseObjectType = getBaseConstraint((t as IndexedAccessType).objectType); + const baseIndexType = getBaseConstraint((t as IndexedAccessType).indexType); + const baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, (t as IndexedAccessType).accessFlags); return baseIndexedAccess && getBaseConstraint(baseIndexedAccess); } if (t.flags & TypeFlags.Conditional) { - const constraint = getConstraintFromConditionalType(t); + const constraint = getConstraintFromConditionalType(t as ConditionalType); return constraint && getBaseConstraint(constraint); } if (t.flags & TypeFlags.Substitution) { - return getBaseConstraint((t).substitute); + return getBaseConstraint((t as SubstitutionType).substitute); } return t; } @@ -11700,8 +11691,8 @@ namespace ts { */ function getApparentType(type: Type): Type { const t = type.flags & TypeFlags.Instantiable ? getBaseConstraintOfType(type) || unknownType : type; - return getObjectFlags(t) & ObjectFlags.Mapped ? getApparentTypeOfMappedType(t) : - t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t) : + return getObjectFlags(t) & ObjectFlags.Mapped ? getApparentTypeOfMappedType(t as MappedType) : + t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t as IntersectionType) : t.flags & TypeFlags.StringLike ? globalStringType : t.flags & TypeFlags.NumberLike ? globalNumberType : t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2020) : @@ -11903,15 +11894,15 @@ namespace ts { * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type: Type): Type { - if (type.flags & TypeFlags.Union && (type).objectFlags & ObjectFlags.ContainsIntersections) { - return (type).resolvedReducedType || ((type).resolvedReducedType = getReducedUnionType(type)); + if (type.flags & TypeFlags.Union && (type as UnionType).objectFlags & ObjectFlags.ContainsIntersections) { + return (type as UnionType).resolvedReducedType || ((type as UnionType).resolvedReducedType = getReducedUnionType(type as UnionType)); } else if (type.flags & TypeFlags.Intersection) { - if (!((type).objectFlags & ObjectFlags.IsNeverIntersectionComputed)) { - (type).objectFlags |= ObjectFlags.IsNeverIntersectionComputed | - (some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? ObjectFlags.IsNeverIntersection : 0); + if (!((type as IntersectionType).objectFlags & ObjectFlags.IsNeverIntersectionComputed)) { + (type as IntersectionType).objectFlags |= ObjectFlags.IsNeverIntersectionComputed | + (some(getPropertiesOfUnionOrIntersectionType(type as IntersectionType), isNeverReducedProperty) ? ObjectFlags.IsNeverIntersection : 0); } - return (type).objectFlags & ObjectFlags.IsNeverIntersection ? neverType : type; + return (type as IntersectionType).objectFlags & ObjectFlags.IsNeverIntersection ? neverType : type; } return type; } @@ -11923,7 +11914,7 @@ namespace ts { } const reduced = getUnionType(reducedTypes); if (reduced.flags & TypeFlags.Union) { - (reduced).resolvedReducedType = reduced; + (reduced as UnionType).resolvedReducedType = reduced; } return reduced; } @@ -11947,12 +11938,12 @@ namespace ts { function elaborateNeverIntersection(errorInfo: DiagnosticMessageChain | undefined, type: Type) { if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsNeverIntersection) { - const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + const neverProp = find(getPropertiesOfUnionOrIntersectionType(type as IntersectionType), isDiscriminantWithNeverType); if (neverProp) { return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(neverProp)); } - const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + const privateProp = find(getPropertiesOfUnionOrIntersectionType(type as IntersectionType), isConflictingPrivateProperty); if (privateProp) { return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(privateProp)); @@ -11972,7 +11963,7 @@ namespace ts { function getPropertyOfType(type: Type, name: __String, skipObjectFunctionPropertyAugment?: boolean): Symbol | undefined { type = getReducedApparentType(type); if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); const symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { return symbol; @@ -11991,14 +11982,14 @@ namespace ts { return getPropertyOfObjectType(globalObjectType, name); } if (type.flags & TypeFlags.UnionOrIntersection) { - return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment); + return getPropertyOfUnionOrIntersectionType(type as UnionOrIntersectionType, name, skipObjectFunctionPropertyAugment); } return undefined; } function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): readonly Signature[] { if (type.flags & TypeFlags.StructuredType) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures; } return emptyArray; @@ -12014,7 +12005,7 @@ namespace ts { function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo | undefined { if (type.flags & TypeFlags.StructuredType) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); return kind === IndexKind.String ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } @@ -12250,7 +12241,7 @@ namespace ts { } const classType = declaration.kind === SyntaxKind.Constructor ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) + getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent as ClassDeclaration).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { @@ -12320,18 +12311,18 @@ namespace ts { if (!node) return false; switch (node.kind) { case SyntaxKind.Identifier: - return (node).escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return (node as Identifier).escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node as Identifier) === argumentsSymbol; case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name!.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name!); + return (node as NamedDeclaration).name!.kind === SyntaxKind.ComputedPropertyName + && traverse((node as NamedDeclaration).name!); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - return traverse((node).expression); + return traverse((node as PropertyAccessExpression | ElementAccessExpression).expression); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse); @@ -12425,7 +12416,7 @@ namespace ts { let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, UnionReduction.Subtype), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration!) || - (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); + (nodeIsMissing((signature.declaration as FunctionLikeDeclaration).body) ? anyType : getReturnTypeFromBody(signature.declaration as FunctionLikeDeclaration)); if (signature.flags & SignatureFlags.IsInnerCallChain) { type = addOptionalTypeMarker(type); } @@ -12439,7 +12430,7 @@ namespace ts { error(typeNode, Diagnostics.Return_type_annotation_circularly_references_itself); } else if (noImplicitAny) { - const declaration = signature.declaration; + const declaration = signature.declaration as Declaration; const name = getNameOfDeclaration(declaration); if (name) { error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); @@ -12458,7 +12449,7 @@ namespace ts { function getReturnTypeFromAnnotation(declaration: SignatureDeclaration | JSDocSignature) { if (declaration.kind === SyntaxKind.Constructor) { - return getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)); + return getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent as ClassDeclaration).symbol)); } if (isJSDocConstructSignature(declaration)) { return getTypeFromTypeNode((declaration.parameters[0] as ParameterDeclaration).type!); // TODO: GH#18217 @@ -12659,10 +12650,10 @@ namespace ts { // present, we form an intersection of the inferred constraint types. const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent); if (grandParent.kind === SyntaxKind.TypeReference) { - const typeReference = grandParent; + const typeReference = grandParent as TypeReferenceNode; const typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { - const index = typeReference.typeArguments!.indexOf(childTypeParameter); + const index = typeReference.typeArguments!.indexOf(childTypeParameter as TypeNode); if (index < typeParameters.length) { const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); if (declaredConstraint) { @@ -12683,9 +12674,9 @@ namespace ts { } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === SyntaxKind.Parameter && (grandParent).dotDotDotToken || + else if (grandParent.kind === SyntaxKind.Parameter && (grandParent as ParameterDeclaration).dotDotDotToken || grandParent.kind === SyntaxKind.RestType || - grandParent.kind === SyntaxKind.NamedTupleMember && (grandParent).dotDotDotToken) { + grandParent.kind === SyntaxKind.NamedTupleMember && (grandParent as NamedTupleMember).dotDotDotToken) { inferences = append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' @@ -12795,7 +12786,7 @@ namespace ts { const id = getTypeListId(typeArguments); let type = target.instantiations.get(id); if (!type) { - type = createObjectType(ObjectFlags.Reference, target.symbol); + type = createObjectType(ObjectFlags.Reference, target.symbol) as TypeReference; target.instantiations.set(id, type); type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; @@ -12805,7 +12796,7 @@ namespace ts { } function cloneTypeReference(source: TypeReference): TypeReference { - const type = createType(source.flags); + const type = createType(source.flags) as TypeReference; type.symbol = source.symbol; type.objectFlags = source.objectFlags; type.target = source.target; @@ -12819,7 +12810,7 @@ namespace ts { const localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; } - const type = createObjectType(ObjectFlags.Reference, target.symbol); + const type = createObjectType(ObjectFlags.Reference, target.symbol) as DeferredTypeReference; type.target = target; type.node = node; type.mapper = mapper; @@ -12862,7 +12853,7 @@ namespace ts { * Get type from type-reference that reference to class or interface */ function getTypeFromClassOrInterfaceReference(node: NodeWithTypeArguments, symbol: Symbol): Type { - const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)) as InterfaceType; const typeParameters = type.localTypeParameters; if (typeParameters) { const numTypeArguments = length(node.typeArguments); @@ -12886,14 +12877,14 @@ namespace ts { return errorType; } } - if (node.kind === SyntaxKind.TypeReference && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) { - return createDeferredTypeReference(type, node, /*mapper*/ undefined); + if (node.kind === SyntaxKind.TypeReference && isDeferredTypeReferenceNode(node as TypeReferenceNode, length(node.typeArguments) !== typeParameters.length)) { + return createDeferredTypeReference(type as GenericType, node as TypeReferenceNode, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs)); - return createTypeReference(type, typeArguments); + return createTypeReference(type as GenericType, typeArguments); } return checkNoTypeArguments(node, symbol) ? type : errorType; } @@ -13037,7 +13028,7 @@ namespace ts { if (cached) { return cached; } - const result = createType(TypeFlags.Substitution); + const result = createType(TypeFlags.Substitution) as SubstitutionType; result.baseType = baseType; result.substitute = substitute; substitutionTypes.set(id, result); @@ -13045,11 +13036,11 @@ namespace ts { } function isUnaryTupleTypeNode(node: TypeNode) { - return node.kind === SyntaxKind.TupleType && (node).elements.length === 1; + return node.kind === SyntaxKind.TupleType && (node as TupleTypeNode).elements.length === 1; } function getImpliedConstraint(type: Type, checkNode: TypeNode, extendsNode: TypeNode): Type | undefined { - return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, (checkNode).elements[0], (extendsNode).elements[0]) : + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, (checkNode as TupleTypeNode).elements[0], (extendsNode as TupleTypeNode).elements[0]) : getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) : undefined; } @@ -13066,8 +13057,8 @@ namespace ts { } // Always substitute on type parameters, regardless of variance, since even // in contravariant positions, they may rely on substituted constraints to be valid - if ((covariant || type.flags & TypeFlags.TypeVariable) && parent.kind === SyntaxKind.ConditionalType && node === (parent).trueType) { - const constraint = getImpliedConstraint(type, (parent).checkType, (parent).extendsType); + if ((covariant || type.flags & TypeFlags.TypeVariable) && parent.kind === SyntaxKind.ConditionalType && node === (parent as ConditionalTypeNode).trueType) { + const constraint = getImpliedConstraint(type, (parent as ConditionalTypeNode).checkType, (parent as ConditionalTypeNode).extendsType); if (constraint) { constraints = append(constraints, constraint); } @@ -13083,7 +13074,7 @@ namespace ts { function checkNoTypeArguments(node: NodeWithTypeArguments, symbol?: Symbol) { if (node.typeArguments) { - error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : (node).typeName ? declarationNameToString((node).typeName) : anon); + error(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : (node as TypeReferenceNode).typeName ? declarationNameToString((node as TypeReferenceNode).typeName) : anon); return false; } return true; @@ -13216,11 +13207,11 @@ namespace ts { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } - if (length((type).typeParameters) !== arity) { + if (length((type as InterfaceType).typeParameters) !== arity) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbolName(symbol), arity); return arity ? emptyGenericType : emptyObjectType; } - return type; + return type as ObjectType; } function getGlobalValueSymbol(name: __String, reportErrors: boolean): Symbol | undefined { @@ -13325,7 +13316,7 @@ namespace ts { function getGlobalTypeOrUndefined(name: __String, arity = 0): ObjectType | undefined { const symbol = getGlobalSymbol(name, SymbolFlags.Type, /*diagnostic*/ undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); + return symbol && getTypeOfGlobalSymbol(symbol, arity) as GenericType; } function getGlobalExtractSymbol(): Symbol { @@ -13426,11 +13417,11 @@ namespace ts { function mayResolveTypeAlias(node: Node): boolean { switch (node.kind) { case SyntaxKind.TypeReference: - return isJSDocTypeReference(node) || !!(resolveTypeReferenceName((node).typeName, SymbolFlags.Type).flags & SymbolFlags.TypeAlias); + return isJSDocTypeReference(node) || !!(resolveTypeReferenceName((node as TypeReferenceNode).typeName, SymbolFlags.Type).flags & SymbolFlags.TypeAlias); case SyntaxKind.TypeQuery: return true; case SyntaxKind.TypeOperator: - return (node).operator !== SyntaxKind.UniqueKeyword && mayResolveTypeAlias((node).type); + return (node as TypeOperatorNode).operator !== SyntaxKind.UniqueKeyword && mayResolveTypeAlias((node as TypeOperatorNode).type); case SyntaxKind.ParenthesizedType: case SyntaxKind.OptionalType: case SyntaxKind.NamedTupleMember: @@ -13438,17 +13429,17 @@ namespace ts { case SyntaxKind.JSDocNullableType: case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocTypeExpression: - return mayResolveTypeAlias((node).type); + return mayResolveTypeAlias((node as ParenthesizedTypeNode | OptionalTypeNode | JSDocTypeReferencingNode | NamedTupleMember).type); case SyntaxKind.RestType: - return (node).type.kind !== SyntaxKind.ArrayType || mayResolveTypeAlias(((node).type).elementType); + return (node as RestTypeNode).type.kind !== SyntaxKind.ArrayType || mayResolveTypeAlias(((node as RestTypeNode).type as ArrayTypeNode).elementType); case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: - return some((node).types, mayResolveTypeAlias); + return some((node as UnionOrIntersectionTypeNode).types, mayResolveTypeAlias); case SyntaxKind.IndexedAccessType: - return mayResolveTypeAlias((node).objectType) || mayResolveTypeAlias((node).indexType); + return mayResolveTypeAlias((node as IndexedAccessTypeNode).objectType) || mayResolveTypeAlias((node as IndexedAccessTypeNode).indexType); case SyntaxKind.ConditionalType: - return mayResolveTypeAlias((node).checkType) || mayResolveTypeAlias((node).extendsType) || - mayResolveTypeAlias((node).trueType) || mayResolveTypeAlias((node).falseType); + return mayResolveTypeAlias((node as ConditionalTypeNode).checkType) || mayResolveTypeAlias((node as ConditionalTypeNode).extendsType) || + mayResolveTypeAlias((node as ConditionalTypeNode).trueType) || mayResolveTypeAlias((node as ConditionalTypeNode).falseType); } return false; } @@ -13537,13 +13528,13 @@ namespace ts { lengthSymbol.type = getUnionType(literalTypes); } properties.push(lengthSymbol); - const type = createObjectType(ObjectFlags.Tuple | ObjectFlags.Reference); + const type = createObjectType(ObjectFlags.Tuple | ObjectFlags.Reference) as TupleType & InterfaceTypeWithDeclaredMembers; type.typeParameters = typeParameters; type.outerTypeParameters = undefined; type.localTypeParameters = typeParameters; type.instantiations = new Map(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; + type.instantiations.set(getTypeListId(type.typeParameters), type as GenericType); + type.target = type as GenericType; type.resolvedTypeArguments = type.typeParameters; type.thisType = createTypeParameter(); type.thisType.isThisType = true; @@ -13708,7 +13699,7 @@ namespace ts { function addTypeToUnion(typeSet: Type[], includes: TypeFlags, type: Type) { const flags = type.flags; if (flags & TypeFlags.Union) { - return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? TypeFlags.Union : 0), (type).types); + return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? TypeFlags.Union : 0), (type as UnionType).types); } // We ignore 'never' types in unions if (!(flags & TypeFlags.Never)) { @@ -13747,7 +13738,7 @@ namespace ts { // We assume that redundant primitive types have already been removed from the types array and that there // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty // object types, and if none of those are present we can exclude primitive types from the subtype check. - const hasEmptyObject = hasObjectTypes && some(types, t => !!(t.flags & TypeFlags.Object) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t))); + const hasEmptyObject = hasObjectTypes && some(types, t => !!(t.flags & TypeFlags.Object) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t as ObjectType))); const len = types.length; let i = len; let count = 0; @@ -13810,7 +13801,7 @@ namespace ts { flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || reduceVoidUndefined && flags & TypeFlags.Undefined && includes & TypeFlags.Void || - isFreshLiteralType(t) && containsType(types, (t).regularType); + isFreshLiteralType(t) && containsType(types, (t as LiteralType).regularType); if (remove) { orderedRemoveItemAt(types, i); } @@ -13832,25 +13823,25 @@ namespace ts { } function isNamedUnionType(type: Type) { - return !!(type.flags & TypeFlags.Union && (type.aliasSymbol || (type).origin)); + return !!(type.flags & TypeFlags.Union && (type.aliasSymbol || (type as UnionType).origin)); } function addNamedUnions(namedUnions: Type[], types: readonly Type[]) { for (const t of types) { if (t.flags & TypeFlags.Union) { - const origin = (t).origin; + const origin = (t as UnionType).origin; if (t.aliasSymbol || origin && !(origin.flags & TypeFlags.Union)) { pushIfUnique(namedUnions, t); } else if (origin && origin.flags & TypeFlags.Union) { - addNamedUnions(namedUnions, (origin).types); + addNamedUnions(namedUnions, (origin as UnionType).types); } } } } function createOriginUnionOrIntersectionType(flags: TypeFlags, types: Type[]) { - const result = createOriginType(flags); + const result = createOriginType(flags) as UnionOrIntersectionType; result.types = types; return result; } @@ -13898,7 +13889,7 @@ namespace ts { addNamedUnions(namedUnions, types); const reducedTypes: Type[] = []; for (const t of typeSet) { - if (!some(namedUnions, union => containsType((union).types, t))) { + if (!some(namedUnions, union => containsType((union as UnionType).types, t))) { reducedTypes.push(t); } } @@ -13907,7 +13898,7 @@ namespace ts { } // We create a denormalized origin type only when the union was created from one or more named unions // (unions with alias symbols or origins) and when there is no overlap between those named unions. - const namedTypesCount = reduceLeft(namedUnions, (sum, union) => sum + (union).types.length, 0); + const namedTypesCount = reduceLeft(namedUnions, (sum, union) => sum + (union as UnionType).types.length, 0); if (namedTypesCount + reducedTypes.length === typeSet.length) { for (const t of namedUnions) { insertType(reducedTypes, t); @@ -13958,7 +13949,7 @@ namespace ts { } function createUnionType(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[], origin?: Type) { - const result = createType(TypeFlags.Union); + const result = createType(TypeFlags.Union) as UnionType; result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); result.types = types; result.origin = origin; @@ -13976,9 +13967,9 @@ namespace ts { return types[0]; } const typeKey = !origin ? getTypeListId(types) : - origin.flags & TypeFlags.Union ? `|${getTypeListId((origin).types)}` : - origin.flags & TypeFlags.Intersection ? `&${getTypeListId((origin).types)}` : - `#${(origin).type.id}|${getTypeListId(types)}`; // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + origin.flags & TypeFlags.Union ? `|${getTypeListId((origin as UnionType).types)}` : + origin.flags & TypeFlags.Intersection ? `&${getTypeListId((origin as IntersectionType).types)}` : + `#${(origin as IndexType).type.id}|${getTypeListId(types)}`; // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); let type = unionTypes.get(id); if (!type) { @@ -14002,7 +13993,7 @@ namespace ts { function addTypeToIntersection(typeSet: ESMap, includes: TypeFlags, type: Type) { const flags = type.flags; if (flags & TypeFlags.Intersection) { - return addTypesToIntersection(typeSet, includes, (type).types); + return addTypesToIntersection(typeSet, includes, (type as IntersectionType).types); } if (isEmptyAnonymousObjectType(type)) { if (!(includes & TypeFlags.IncludesEmptyObject)) { @@ -14120,7 +14111,7 @@ namespace ts { while (i < types.length) { const t = types[i]; if (getObjectFlags(t) & ObjectFlags.PrimitiveUnion) { - (unionTypes || (unionTypes = [types[index]])).push(t); + (unionTypes || (unionTypes = [types[index] as UnionType])).push(t as UnionType); orderedRemoveItemAt(types, i); } else { @@ -14151,7 +14142,7 @@ namespace ts { } function createIntersectionType(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]) { - const result = createType(TypeFlags.Intersection); + const result = createType(TypeFlags.Intersection) as IntersectionType; result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); result.types = types; result.aliasSymbol = aliasSymbol; @@ -14255,7 +14246,7 @@ namespace ts { } function getCrossProductUnionSize(types: readonly Type[]) { - return reduceLeft(types, (n, t) => t.flags & TypeFlags.Union ? n * (t).types.length : t.flags & TypeFlags.Never ? 0 : n, 1); + return reduceLeft(types, (n, t) => t.flags & TypeFlags.Union ? n * (t as UnionType).types.length : t.flags & TypeFlags.Never ? 0 : n, 1); } function checkCrossProductUnion(types: readonly Type[]) { @@ -14276,7 +14267,7 @@ namespace ts { let n = i; for (let j = types.length - 1; j >= 0; j--) { if (types[j].flags & TypeFlags.Union) { - const sourceTypes = (types[j]).types; + const sourceTypes = (types[j] as UnionType).types; const length = sourceTypes.length; constituents[j] = sourceTypes[n % length]; n = Math.floor(n / length); @@ -14299,14 +14290,14 @@ namespace ts { } function createIndexType(type: InstantiableType | UnionOrIntersectionType, stringsOnly: boolean) { - const result = createType(TypeFlags.Index); + const result = createType(TypeFlags.Index) as IndexType; result.type = type; result.stringsOnly = stringsOnly; return result; } function createOriginIndexType(type: InstantiableType | UnionOrIntersectionType) { - const result = createOriginType(TypeFlags.Index); + const result = createOriginType(TypeFlags.Index) as IndexType; result.type = type; return result; } @@ -14333,16 +14324,22 @@ namespace ts { } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes - // that N distributes over union types, i.e. that N is equivalent to N | N | N. That presumption may not - // be true when N is a non-distributive conditional type or an instantiable type with a non-distributive conditional type as - // a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is. - function maybeNonDistributiveNameType(type: Type | undefined): boolean { - return !!(type && ( - type.flags & TypeFlags.Conditional && (!(type).root.isDistributive || maybeNonDistributiveNameType((type).checkType)) || - type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) && some((type).types, maybeNonDistributiveNameType) || - type.flags & (TypeFlags.Index | TypeFlags.StringMapping) && maybeNonDistributiveNameType((type).type) || - type.flags & TypeFlags.IndexedAccess && maybeNonDistributiveNameType((type).indexType) || - type.flags & TypeFlags.Substitution && maybeNonDistributiveNameType((type).substitute))); + // that N distributes over union types, i.e. that N is equivalent to N | N | N. Specifically, we only + // want to perform the reduction when the name type of a mapped type is distributive with respect to the type variable + // introduced by the 'in' clause of the mapped type. Note that non-generic types are considered to be distributive because + // they're the same type regardless of what's being distributed over. + function hasDistributiveNameType(mappedType: MappedType) { + const typeVariable = getTypeParameterFromMappedType(mappedType); + return isDistributive(getNameTypeFromMappedType(mappedType) || typeVariable); + function isDistributive(type: Type): boolean { + return type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Primitive | TypeFlags.Never | TypeFlags.TypeParameter | TypeFlags.Object | TypeFlags.NonPrimitive) ? true : + type.flags & TypeFlags.Conditional ? (type as ConditionalType).root.isDistributive && (type as ConditionalType).checkType === typeVariable : + type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) ? every((type as UnionOrIntersectionType | TemplateLiteralType).types, isDistributive) : + type.flags & TypeFlags.IndexedAccess ? isDistributive((type as IndexedAccessType).objectType) && isDistributive((type as IndexedAccessType).indexType) : + type.flags & TypeFlags.Substitution ? isDistributive((type as SubstitutionType).substitute) : + type.flags & TypeFlags.StringMapping ? isDistributive((type as StringMappingType).type) : + false; + } } function getLiteralTypeFromPropertyName(name: PropertyName) { @@ -14393,10 +14390,10 @@ namespace ts { function getIndexType(type: Type, stringsOnly = keyofStringsOnly, noIndexSignatures?: boolean): Type { const includeOrigin = stringsOnly === keyofStringsOnly && !noIndexSignatures; type = getReducedType(type); - return type.flags & TypeFlags.Union ? getIntersectionType(map((type).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : - type.flags & TypeFlags.Intersection ? getUnionType(map((type).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : - type.flags & TypeFlags.InstantiableNonPrimitive || isGenericTupleType(type) || isGenericMappedType(type) && maybeNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) : - getObjectFlags(type) & ObjectFlags.Mapped ? getIndexTypeForMappedType(type, noIndexSignatures) : + return type.flags & TypeFlags.Union ? getIntersectionType(map((type as UnionType).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : + type.flags & TypeFlags.Intersection ? getUnionType(map((type as IntersectionType).types, t => getIndexType(t, stringsOnly, noIndexSignatures))) : + type.flags & TypeFlags.InstantiableNonPrimitive || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) ? getIndexTypeForGenericType(type as InstantiableType | UnionOrIntersectionType, stringsOnly) : + getObjectFlags(type) & ObjectFlags.Mapped ? getIndexTypeForMappedType(type as MappedType, noIndexSignatures) : type === wildcardType ? wildcardType : type.flags & TypeFlags.Unknown ? neverType : type.flags & (TypeFlags.Any | TypeFlags.Never) ? keyofConstraintType : @@ -14489,8 +14486,8 @@ namespace ts { text += texts[i + 1]; } else if (t.flags & TypeFlags.TemplateLiteral) { - text += (t).texts[0]; - if (!addSpans((t).texts, (t).types)) return false; + text += (t as TemplateLiteralType).texts[0]; + if (!addSpans((t as TemplateLiteralType).texts, (t as TemplateLiteralType).types)) return false; text += texts[i + 1]; } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { @@ -14507,15 +14504,15 @@ namespace ts { } function getTemplateStringForType(type: Type) { - return type.flags & TypeFlags.StringLiteral ? (type).value : - type.flags & TypeFlags.NumberLiteral ? "" + (type).value : - type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString((type).value) : - type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? (type).intrinsicName : + return type.flags & TypeFlags.StringLiteral ? (type as StringLiteralType).value : + type.flags & TypeFlags.NumberLiteral ? "" + (type as NumberLiteralType).value : + type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString((type as BigIntLiteralType).value) : + type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? (type as IntrinsicType).intrinsicName : undefined; } function createTemplateLiteralType(texts: readonly string[], types: readonly Type[]) { - const type = createType(TypeFlags.TemplateLiteral); + const type = createType(TypeFlags.TemplateLiteral) as TemplateLiteralType; type.texts = texts; type.types = types; return type; @@ -14524,7 +14521,7 @@ namespace ts { function getStringMappingType(symbol: Symbol, type: Type): Type { return type.flags & (TypeFlags.Union | TypeFlags.Never) ? mapType(type, t => getStringMappingType(symbol, t)) : isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : - type.flags & TypeFlags.StringLiteral ? getLiteralType(applyStringMapping(symbol, (type).value)) : + type.flags & TypeFlags.StringLiteral ? getLiteralType(applyStringMapping(symbol, (type as StringLiteralType).value)) : type; } @@ -14548,19 +14545,19 @@ namespace ts { } function createStringMappingType(symbol: Symbol, type: Type) { - const result = createType(TypeFlags.StringMapping); + const result = createType(TypeFlags.StringMapping) as StringMappingType; result.symbol = symbol; result.type = type; return result; } - function createIndexedAccessType(objectType: Type, indexType: Type, aliasSymbol: Symbol | undefined, aliasTypeArguments: readonly Type[] | undefined, shouldIncludeUndefined: boolean) { - const type = createType(TypeFlags.IndexedAccess); + function createIndexedAccessType(objectType: Type, indexType: Type, accessFlags: AccessFlags, aliasSymbol: Symbol | undefined, aliasTypeArguments: readonly Type[] | undefined) { + const type = createType(TypeFlags.IndexedAccess) as IndexedAccessType; type.objectType = objectType; type.indexType = indexType; + type.accessFlags = accessFlags; type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; - type.noUncheckedIndexedAccessCandidate = shouldIncludeUndefined; return type; } @@ -14613,14 +14610,17 @@ namespace ts { return true; } - function getPropertyTypeForIndexType(originalObjectType: Type, objectType: Type, indexType: Type, fullIndexType: Type, suppressNoImplicitAnyError: boolean, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, accessFlags: AccessFlags, noUncheckedIndexedAccessCandidate?: boolean, reportDeprecated?: boolean) { + function getPropertyTypeForIndexType(originalObjectType: Type, objectType: Type, indexType: Type, fullIndexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression | undefined, accessFlags: AccessFlags) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; const propName = accessNode && isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { + if (accessFlags & AccessFlags.Contextual) { + return getTypeOfPropertyOfContextualType(objectType, propName) || anyType; + } const prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(accessNode, prop)) { + if (accessFlags & AccessFlags.ReportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(accessNode, prop)) { const deprecatedNode = accessExpression?.argumentExpression ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName as string); } @@ -14643,7 +14643,7 @@ namespace ts { propType; } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { - if (accessNode && everyType(objectType, t => !(t).target.hasRestElement) && !(accessFlags & AccessFlags.NoTupleBoundsCheck)) { + if (accessNode && everyType(objectType, t => !(t as TupleTypeReference).target.hasRestElement) && !(accessFlags & AccessFlags.NoTupleBoundsCheck)) { const indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, @@ -14655,8 +14655,8 @@ namespace ts { } errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, IndexKind.Number)); return mapType(objectType, t => { - const restType = getRestTypeOfTupleType(t) || undefinedType; - return noUncheckedIndexedAccessCandidate ? getUnionType([restType, undefinedType]) : restType; + const restType = getRestTypeOfTupleType(t as TupleTypeReference) || undefinedType; + return accessFlags & AccessFlags.IncludeUndefined ? getUnionType([restType, undefinedType]) : restType; }); } } @@ -14676,10 +14676,10 @@ namespace ts { if (accessNode && !isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) { const indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + return accessFlags & AccessFlags.IncludeUndefined ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + return accessFlags & AccessFlags.IncludeUndefined ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } if (indexType.flags & TypeFlags.Never) { return neverType; @@ -14694,7 +14694,7 @@ namespace ts { return undefinedType; } else if (indexType.flags & (TypeFlags.Number | TypeFlags.String)) { - const types = map((objectType).properties, property => { + const types = map((objectType as ResolvedType).properties, property => { return getTypeOfSymbol(property); }); return getUnionType(append(types, undefinedType)); @@ -14704,7 +14704,7 @@ namespace ts { if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports!.has(propName) && (globalThisSymbol.exports!.get(propName)!.flags & SymbolFlags.BlockScoped)) { error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } - else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) { + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !(accessFlags & AccessFlags.SuppressNoImplicitAnyError)) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { const typeName = typeToString(objectType); error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName as string, typeName, typeName + "[" + getTextOfNode(accessExpression.argumentExpression) + "]"); @@ -14761,7 +14761,7 @@ namespace ts { if (accessNode) { const indexNode = getIndexNodeForAccessExpression(accessNode); if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { - error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType as StringLiteralType | NumberLiteralType).value, typeToString(objectType)); } else if (indexType.flags & (TypeFlags.String | TypeFlags.Number)) { error(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); @@ -14799,47 +14799,47 @@ namespace ts { function isGenericObjectType(type: Type): boolean { if (type.flags & TypeFlags.UnionOrIntersection) { - if (!((type).objectFlags & ObjectFlags.IsGenericObjectTypeComputed)) { - (type).objectFlags |= ObjectFlags.IsGenericObjectTypeComputed | - (some((type).types, isGenericObjectType) ? ObjectFlags.IsGenericObjectType : 0); + if (!((type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericObjectTypeComputed)) { + (type as UnionOrIntersectionType).objectFlags |= ObjectFlags.IsGenericObjectTypeComputed | + (some((type as UnionOrIntersectionType).types, isGenericObjectType) ? ObjectFlags.IsGenericObjectType : 0); } - return !!((type).objectFlags & ObjectFlags.IsGenericObjectType); + return !!((type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericObjectType); } if (type.flags & TypeFlags.Substitution) { - if (!((type).objectFlags & ObjectFlags.IsGenericObjectTypeComputed)) { - (type).objectFlags |= ObjectFlags.IsGenericObjectTypeComputed | - (isGenericObjectType((type).substitute) || isGenericObjectType((type).baseType) ? ObjectFlags.IsGenericObjectType : 0); + if (!((type as SubstitutionType).objectFlags & ObjectFlags.IsGenericObjectTypeComputed)) { + (type as SubstitutionType).objectFlags |= ObjectFlags.IsGenericObjectTypeComputed | + (isGenericObjectType((type as SubstitutionType).substitute) || isGenericObjectType((type as SubstitutionType).baseType) ? ObjectFlags.IsGenericObjectType : 0); } - return !!((type).objectFlags & ObjectFlags.IsGenericObjectType); + return !!((type as SubstitutionType).objectFlags & ObjectFlags.IsGenericObjectType); } return !!(type.flags & TypeFlags.InstantiableNonPrimitive) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type: Type): boolean { if (type.flags & TypeFlags.UnionOrIntersection) { - if (!((type).objectFlags & ObjectFlags.IsGenericIndexTypeComputed)) { - (type).objectFlags |= ObjectFlags.IsGenericIndexTypeComputed | - (some((type).types, isGenericIndexType) ? ObjectFlags.IsGenericIndexType : 0); + if (!((type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericIndexTypeComputed)) { + (type as UnionOrIntersectionType).objectFlags |= ObjectFlags.IsGenericIndexTypeComputed | + (some((type as UnionOrIntersectionType).types, isGenericIndexType) ? ObjectFlags.IsGenericIndexType : 0); } - return !!((type).objectFlags & ObjectFlags.IsGenericIndexType); + return !!((type as UnionOrIntersectionType).objectFlags & ObjectFlags.IsGenericIndexType); } if (type.flags & TypeFlags.Substitution) { - if (!((type).objectFlags & ObjectFlags.IsGenericIndexTypeComputed)) { - (type).objectFlags |= ObjectFlags.IsGenericIndexTypeComputed | - (isGenericIndexType((type).substitute) || isGenericIndexType((type).baseType) ? ObjectFlags.IsGenericIndexType : 0); + if (!((type as SubstitutionType).objectFlags & ObjectFlags.IsGenericIndexTypeComputed)) { + (type as SubstitutionType).objectFlags |= ObjectFlags.IsGenericIndexTypeComputed | + (isGenericIndexType((type as SubstitutionType).substitute) || isGenericIndexType((type as SubstitutionType).baseType) ? ObjectFlags.IsGenericIndexType : 0); } - return !!((type).objectFlags & ObjectFlags.IsGenericIndexType); + return !!((type as SubstitutionType).objectFlags & ObjectFlags.IsGenericIndexType); } return !!(type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping)) && !isPatternLiteralType(type); } function isThisTypeParameter(type: Type): boolean { - return !!(type.flags & TypeFlags.TypeParameter && (type).isThisType); + return !!(type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType); } function getSimplifiedType(type: Type, writing: boolean): Type { - return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(type, writing) : - type.flags & TypeFlags.Conditional ? getSimplifiedConditionalType(type, writing) : + return type.flags & TypeFlags.IndexedAccess ? getSimplifiedIndexedAccessType(type as IndexedAccessType, writing) : + type.flags & TypeFlags.Conditional ? getSimplifiedConditionalType(type as ConditionalType, writing) : type; } @@ -14957,14 +14957,14 @@ namespace ts { return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType: Type, indexType: Type, noUncheckedIndexedAccessCandidate?: boolean, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[], accessFlags = AccessFlags.None): Type { - return getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType); + function getIndexedAccessType(objectType: Type, indexType: Type, accessFlags = AccessFlags.None, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type { + return getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType); } function indexTypeLessThan(indexType: Type, limit: number) { return everyType(indexType, t => { if (t.flags & TypeFlags.StringOrNumberLiteral) { - const propName = getPropertyNameFromType(t); + const propName = getPropertyNameFromType(t as StringLiteralType | NumberLiteralType); if (isNumericLiteralName(propName)) { const index = +propName; return index >= 0 && index < limit; @@ -14974,20 +14974,18 @@ namespace ts { }); } - function getIndexedAccessTypeOrUndefined(objectType: Type, indexType: Type, noUncheckedIndexedAccessCandidate?: boolean, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression, accessFlags = AccessFlags.None, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type | undefined { + function getIndexedAccessTypeOrUndefined(objectType: Type, indexType: Type, accessFlags = AccessFlags.None, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type | undefined { if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } - - const shouldIncludeUndefined = noUncheckedIndexedAccessCandidate || - (!!compilerOptions.noUncheckedIndexedAccess && - (accessFlags & (AccessFlags.Writing | AccessFlags.ExpressionPosition)) === AccessFlags.ExpressionPosition); - // If the object type has a string index signature and no other members we know that the result will // always be the type of that index signature and we can simplify accordingly. if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) { indexType = stringType; } + // In noUncheckedIndexedAccess mode, indexed access operations that occur in an expression in a read position and resolve to + // an index signature have 'undefined' included in their type. + if (compilerOptions.noUncheckedIndexedAccess && accessFlags & AccessFlags.ExpressionPosition) accessFlags |= AccessFlags.IncludeUndefined; // If the index type is generic, or if the object type is generic and doesn't originate in an expression and // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that @@ -15001,10 +14999,11 @@ namespace ts { return objectType; } // Defer the operation by creating an indexed access type. - const id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); + const persistentAccessFlags = accessFlags & AccessFlags.Persistent; + const id = objectType.id + "," + indexType.id + "," + persistentAccessFlags + getAliasId(aliasSymbol, aliasTypeArguments); let type = indexedAccessTypes.get(id); if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, persistentAccessFlags, aliasSymbol, aliasTypeArguments)); } return type; @@ -15016,8 +15015,8 @@ namespace ts { if (indexType.flags & TypeFlags.Union && !(indexType.flags & TypeFlags.Boolean)) { const propTypes: Type[] = []; let wasMissingProp = false; - for (const t of (indexType).types) { - const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags, shouldIncludeUndefined); + for (const t of (indexType as UnionType).types) { + const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, accessNode, accessFlags | (wasMissingProp ? AccessFlags.SuppressNoImplicitAnyError : 0)); if (propType) { propTypes.push(propType); } @@ -15037,7 +15036,7 @@ namespace ts { ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, UnionReduction.Literal, aliasSymbol, aliasTypeArguments); } - return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | AccessFlags.CacheSymbol, shouldIncludeUndefined, /* reportDeprecated */ true); + return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | AccessFlags.CacheSymbol | AccessFlags.ReportDeprecated); } function getTypeFromIndexedAccessTypeNode(node: IndexedAccessTypeNode) { @@ -15046,10 +15045,10 @@ namespace ts { const objectType = getTypeFromTypeNode(node.objectType); const indexType = getTypeFromTypeNode(node.indexType); const potentialAlias = getAliasSymbolForTypeNode(node); - const resolved = getIndexedAccessType(objectType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias)); + const resolved = getIndexedAccessType(objectType, indexType, AccessFlags.None, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias)); links.resolvedType = resolved.flags & TypeFlags.IndexedAccess && - (resolved).objectType === objectType && - (resolved).indexType === indexType ? + (resolved as IndexedAccessType).objectType === objectType && + (resolved as IndexedAccessType).indexType === indexType ? getConditionalFlowTypeOfType(resolved, node) : resolved; } return links.resolvedType; @@ -15058,7 +15057,7 @@ namespace ts { function getTypeFromMappedTypeNode(node: MappedTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - const type = createObjectType(ObjectFlags.Mapped, node.symbol); + const type = createObjectType(ObjectFlags.Mapped, node.symbol) as MappedType; type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); @@ -15072,12 +15071,12 @@ namespace ts { function getActualTypeVariable(type: Type): Type { if (type.flags & TypeFlags.Substitution) { - return (type).baseType; + return (type as SubstitutionType).baseType; } if (type.flags & TypeFlags.IndexedAccess && ( - (type).objectType.flags & TypeFlags.Substitution || - (type).indexType.flags & TypeFlags.Substitution)) { - return getIndexedAccessType(getActualTypeVariable((type).objectType), getActualTypeVariable((type).indexType)); + (type as IndexedAccessType).objectType.flags & TypeFlags.Substitution || + (type as IndexedAccessType).indexType.flags & TypeFlags.Substitution)) { + return getIndexedAccessType(getActualTypeVariable((type as IndexedAccessType).objectType), getActualTypeVariable((type as IndexedAccessType).indexType)); } return type; } @@ -15144,7 +15143,7 @@ namespace ts { // identical checkType, switch to that type and loop. const falseType = getTypeFromTypeNode(root.node.falseType); if (falseType.flags & TypeFlags.Conditional) { - const newRoot = (falseType).root; + const newRoot = (falseType as ConditionalType).root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; continue; @@ -15164,7 +15163,7 @@ namespace ts { } } // Return a deferred type for a check that is neither definitely true nor definitely false - result = createType(TypeFlags.Conditional); + result = createType(TypeFlags.Conditional) as ConditionalType; result.root = root; result.checkType = instantiateType(root.checkType, mapper); result.extendsType = instantiateType(root.extendsType, mapper); @@ -15453,7 +15452,7 @@ namespace ts { // intersection with the right type. For example when the left type is 'T & { a: string }' // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. if (left.flags & TypeFlags.Intersection) { - const types = (left).types; + const types = (left as IntersectionType).types; const lastLeft = types[types.length - 1]; if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)])); @@ -15546,7 +15545,7 @@ namespace ts { } function createLiteralType(flags: TypeFlags, value: string | number | PseudoBigInt, symbol: Symbol | undefined) { - const type = createType(flags); + const type = createType(flags) as LiteralType; type.symbol = symbol!; type.value = value; return type; @@ -15554,25 +15553,25 @@ namespace ts { function getFreshTypeOfLiteralType(type: Type): Type { if (type.flags & TypeFlags.Literal) { - if (!(type).freshType) { - const freshType = createLiteralType(type.flags, (type).value, (type).symbol); - freshType.regularType = type; + if (!(type as LiteralType).freshType) { + const freshType = createLiteralType(type.flags, (type as LiteralType).value, (type as LiteralType).symbol); + freshType.regularType = type as LiteralType; freshType.freshType = freshType; - (type).freshType = freshType; + (type as LiteralType).freshType = freshType; } - return (type).freshType; + return (type as LiteralType).freshType; } return type; } function getRegularTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.Literal ? (type).regularType : - type.flags & TypeFlags.Union ? ((type).regularType || ((type).regularType = mapType(type, getRegularTypeOfLiteralType) as UnionType)) : + return type.flags & TypeFlags.Literal ? (type as LiteralType).regularType : + type.flags & TypeFlags.Union ? ((type as UnionType).regularType || ((type as UnionType).regularType = mapType(type, getRegularTypeOfLiteralType) as UnionType)) : type; } function isFreshLiteralType(type: Type) { - return !!(type.flags & TypeFlags.Literal) && (type).freshType === type; + return !!(type.flags & TypeFlags.Literal) && (type as LiteralType).freshType === type; } function getLiteralType(value: string): StringLiteralType; @@ -15607,7 +15606,7 @@ namespace ts { } function createUniqueESSymbolType(symbol: Symbol) { - const type = createType(TypeFlags.UniqueESSymbol); + const type = createType(TypeFlags.UniqueESSymbol) as UniqueESSymbolType; type.symbol = symbol; type.escapedName = `__@${type.symbol.escapedName}@${getSymbolId(type.symbol)}` as __String; return type; @@ -15728,26 +15727,26 @@ namespace ts { // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node as ThisExpression | ThisTypeNode); case SyntaxKind.LiteralType: - return getTypeFromLiteralTypeNode(node); + return getTypeFromLiteralTypeNode(node as LiteralTypeNode); case SyntaxKind.TypeReference: - return getTypeFromTypeReference(node); + return getTypeFromTypeReference(node as TypeReferenceNode); case SyntaxKind.TypePredicate: - return (node).assertsModifier ? voidType : booleanType; + return (node as TypePredicateNode).assertsModifier ? voidType : booleanType; case SyntaxKind.ExpressionWithTypeArguments: - return getTypeFromTypeReference(node); + return getTypeFromTypeReference(node as ExpressionWithTypeArguments); case SyntaxKind.TypeQuery: - return getTypeFromTypeQueryNode(node); + return getTypeFromTypeQueryNode(node as TypeQueryNode); case SyntaxKind.ArrayType: case SyntaxKind.TupleType: - return getTypeFromArrayOrTupleTypeNode(node); + return getTypeFromArrayOrTupleTypeNode(node as ArrayTypeNode | TupleTypeNode); case SyntaxKind.OptionalType: - return getTypeFromOptionalTypeNode(node); + return getTypeFromOptionalTypeNode(node as OptionalTypeNode); case SyntaxKind.UnionType: - return getTypeFromUnionTypeNode(node); + return getTypeFromUnionTypeNode(node as UnionTypeNode); case SyntaxKind.IntersectionType: - return getTypeFromIntersectionTypeNode(node); + return getTypeFromIntersectionTypeNode(node as IntersectionTypeNode); case SyntaxKind.JSDocNullableType: - return getTypeFromJSDocNullableTypeNode(node); + return getTypeFromJSDocNullableTypeNode(node as JSDocNullableType); case SyntaxKind.JSDocOptionalType: return addOptionality(getTypeFromTypeNode((node as JSDocOptionalType).type)); case SyntaxKind.NamedTupleMember: @@ -15755,9 +15754,9 @@ namespace ts { case SyntaxKind.ParenthesizedType: case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocTypeExpression: - return getTypeFromTypeNode((node).type); + return getTypeFromTypeNode((node as ParenthesizedTypeNode | JSDocTypeReferencingNode | JSDocTypeExpression | NamedTupleMember).type); case SyntaxKind.RestType: - return getTypeFromRestTypeNode(node); + return getTypeFromRestTypeNode(node as RestTypeNode); case SyntaxKind.JSDocVariadicType: return getTypeFromJSDocVariadicType(node as JSDocVariadicType); case SyntaxKind.FunctionType: @@ -15768,19 +15767,19 @@ namespace ts { case SyntaxKind.JSDocSignature: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case SyntaxKind.TypeOperator: - return getTypeFromTypeOperatorNode(node); + return getTypeFromTypeOperatorNode(node as TypeOperatorNode); case SyntaxKind.IndexedAccessType: - return getTypeFromIndexedAccessTypeNode(node); + return getTypeFromIndexedAccessTypeNode(node as IndexedAccessTypeNode); case SyntaxKind.MappedType: - return getTypeFromMappedTypeNode(node); + return getTypeFromMappedTypeNode(node as MappedTypeNode); case SyntaxKind.ConditionalType: - return getTypeFromConditionalTypeNode(node); + return getTypeFromConditionalTypeNode(node as ConditionalTypeNode); case SyntaxKind.InferType: - return getTypeFromInferTypeNode(node); + return getTypeFromInferTypeNode(node as InferTypeNode); case SyntaxKind.TemplateLiteralType: - return getTypeFromTemplateTypeNode(node); + return getTypeFromTemplateTypeNode(node as TemplateLiteralTypeNode); case SyntaxKind.ImportType: - return getTypeFromImportTypeNode(node); + return getTypeFromImportTypeNode(node as ImportTypeNode); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. @@ -15970,9 +15969,9 @@ namespace ts { } function getObjectTypeInstantiation(type: AnonymousType | DeferredTypeReference, mapper: TypeMapper, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]) { - const declaration = type.objectFlags & ObjectFlags.Reference ? (type).node! : type.symbol.declarations![0]; + const declaration = type.objectFlags & ObjectFlags.Reference ? (type as TypeReference).node! : type.symbol.declarations![0]; const links = getNodeLinks(declaration); - const target = type.objectFlags & ObjectFlags.Reference ? links.resolvedType! : + const target = type.objectFlags & ObjectFlags.Reference ? links.resolvedType! as DeferredTypeReference : type.objectFlags & ObjectFlags.Instantiated ? type.target! : type; let typeParameters = links.outerTypeParameters; if (!typeParameters) { @@ -16008,8 +16007,8 @@ namespace ts { let result = target.instantiations.get(id); if (!result) { const newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & ObjectFlags.Reference ? createDeferredTypeReference((type).target, (type).node, newMapper, newAliasSymbol, newAliasTypeArguments) : - target.objectFlags & ObjectFlags.Mapped ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + result = target.objectFlags & ObjectFlags.Reference ? createDeferredTypeReference((type as DeferredTypeReference).target, (type as DeferredTypeReference).node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & ObjectFlags.Mapped ? instantiateMappedType(target as MappedType, newMapper, newAliasSymbol, newAliasTypeArguments) : instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } @@ -16020,7 +16019,7 @@ namespace ts { function maybeTypeParameterReference(node: Node) { return !(node.kind === SyntaxKind.QualifiedName || - node.parent.kind === SyntaxKind.TypeReference && (node.parent).typeArguments && node === (node.parent).typeName || + node.parent.kind === SyntaxKind.TypeReference && (node.parent as TypeReferenceNode).typeArguments && node === (node.parent as TypeReferenceNode).typeName || node.parent.kind === SyntaxKind.ImportType && (node.parent as ImportTypeNode).typeArguments && node === (node.parent as ImportTypeNode).qualifier); } @@ -16031,7 +16030,7 @@ namespace ts { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { const container = tp.symbol.declarations[0].parent; for (let n = node; n !== container; n = n.parent) { - if (!n || n.kind === SyntaxKind.Block || n.kind === SyntaxKind.ConditionalType && forEachChild((n).extendsType, containsReference)) { + if (!n || n.kind === SyntaxKind.Block || n.kind === SyntaxKind.ConditionalType && forEachChild((n as ConditionalTypeNode).extendsType, containsReference)) { return true; } } @@ -16044,7 +16043,7 @@ namespace ts { return !!tp.isThisType; case SyntaxKind.Identifier: return !tp.isThisType && isPartOfTypeNode(node) && maybeTypeParameterReference(node) && - getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality + getTypeFromTypeNodeWorker(node as TypeNode) === tp; // use worker because we're looking for === equality case SyntaxKind.TypeQuery: return true; case SyntaxKind.MethodDeclaration: @@ -16058,9 +16057,9 @@ namespace ts { function getHomomorphicTypeVariable(type: MappedType) { const constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & TypeFlags.Index) { - const typeVariable = getActualTypeVariable((constraintType).type); + const typeVariable = getActualTypeVariable((constraintType as IndexType).type); if (typeVariable.flags & TypeFlags.TypeParameter) { - return typeVariable; + return typeVariable as TypeParameter; } } return undefined; @@ -16146,7 +16145,7 @@ namespace ts { function instantiateMappedTypeTemplate(type: MappedType, key: Type, isOptional: boolean, mapper: TypeMapper) { const templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key); - const propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + const propType = instantiateType(getTemplateTypeFromMappedType(type.target as MappedType || type), templateMapper); const modifiers = getMappedTypeModifiers(type); return strictNullChecks && modifiers & MappedTypeModifiers.IncludeOptional && !maybeTypeOfKind(propType, TypeFlags.Undefined | TypeFlags.Void) ? getOptionalType(propType) : strictNullChecks && modifiers & MappedTypeModifiers.ExcludeOptional && isOptional ? getTypeWithFacts(propType, TypeFacts.NEUndefined) : @@ -16154,13 +16153,13 @@ namespace ts { } function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): AnonymousType { - const result = createObjectType(type.objectFlags | ObjectFlags.Instantiated, type.symbol); + const result = createObjectType(type.objectFlags | ObjectFlags.Instantiated, type.symbol) as AnonymousType; if (type.objectFlags & ObjectFlags.Mapped) { - (result).declaration = (type).declaration; + (result as MappedType).declaration = (type as MappedType).declaration; // C.f. instantiateSignature - const origTypeParameter = getTypeParameterFromMappedType(type); + const origTypeParameter = getTypeParameterFromMappedType(type as MappedType); const freshTypeParameter = cloneTypeParameter(origTypeParameter); - (result).typeParameter = freshTypeParameter; + (result as MappedType).typeParameter = freshTypeParameter; mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); freshTypeParameter.mapper = mapper; } @@ -16195,7 +16194,7 @@ namespace ts { // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). if (root.isDistributive) { - const checkType = root.checkType; + const checkType = root.checkType as TypeParameter; const instantiatedType = getMappedType(checkType, mapper); if (checkType !== instantiatedType && instantiatedType.flags & (TypeFlags.Union | TypeFlags.Never)) { return mapTypeWithAlias(instantiatedType, t => getConditionalType(root, prependTypeMapping(checkType, t, mapper)), aliasSymbol, aliasTypeArguments); @@ -16236,23 +16235,23 @@ namespace ts { return getMappedType(type, mapper); } if (flags & TypeFlags.Object) { - const objectFlags = (type).objectFlags; + const objectFlags = (type as ObjectType).objectFlags; if (objectFlags & (ObjectFlags.Reference | ObjectFlags.Anonymous | ObjectFlags.Mapped)) { - if (objectFlags & ObjectFlags.Reference && !(type).node) { - const resolvedTypeArguments = (type).resolvedTypeArguments; + if (objectFlags & ObjectFlags.Reference && !(type as TypeReference).node) { + const resolvedTypeArguments = (type as TypeReference).resolvedTypeArguments; const newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference((type).target, newTypeArguments) : type; + return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference((type as TypeReference).target, newTypeArguments) : type; } if (objectFlags & ObjectFlags.ReverseMapped) { return instantiateReverseMappedType(type as ReverseMappedType, mapper); } - return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); + return getObjectTypeInstantiation(type as TypeReference | AnonymousType | MappedType, mapper, aliasSymbol, aliasTypeArguments); } return type; } if (flags & TypeFlags.UnionOrIntersection) { - const origin = type.flags & TypeFlags.Union ? (type).origin : undefined; - const types = origin && origin.flags & TypeFlags.UnionOrIntersection ? (origin).types : (type).types; + const origin = type.flags & TypeFlags.Union ? (type as UnionType).origin : undefined; + const types = origin && origin.flags & TypeFlags.UnionOrIntersection ? (origin as UnionOrIntersectionType).types : (type as UnionOrIntersectionType).types; const newTypes = instantiateTypes(types, mapper); if (newTypes === types && aliasSymbol === type.aliasSymbol) { return type; @@ -16264,29 +16263,29 @@ namespace ts { getUnionType(newTypes, UnionReduction.Literal, newAliasSymbol, newAliasTypeArguments); } if (flags & TypeFlags.Index) { - return getIndexType(instantiateType((type).type, mapper)); + return getIndexType(instantiateType((type as IndexType).type, mapper)); } if (flags & TypeFlags.TemplateLiteral) { - return getTemplateLiteralType((type).texts, instantiateTypes((type).types, mapper)); + return getTemplateLiteralType((type as TemplateLiteralType).texts, instantiateTypes((type as TemplateLiteralType).types, mapper)); } if (flags & TypeFlags.StringMapping) { - return getStringMappingType((type).symbol, instantiateType((type).type, mapper)); + return getStringMappingType((type as StringMappingType).symbol, instantiateType((type as StringMappingType).type, mapper)); } if (flags & TypeFlags.IndexedAccess) { const newAliasSymbol = aliasSymbol || type.aliasSymbol; const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); - return getIndexedAccessType(instantiateType((type).objectType, mapper), instantiateType((type).indexType, mapper), (type).noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); + return getIndexedAccessType(instantiateType((type as IndexedAccessType).objectType, mapper), instantiateType((type as IndexedAccessType).indexType, mapper), (type as IndexedAccessType).accessFlags, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & TypeFlags.Conditional) { - return getConditionalTypeInstantiation(type, combineTypeMappers((type).mapper, mapper), aliasSymbol, aliasTypeArguments); + return getConditionalTypeInstantiation(type as ConditionalType, combineTypeMappers((type as ConditionalType).mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & TypeFlags.Substitution) { - const maybeVariable = instantiateType((type).baseType, mapper); + const maybeVariable = instantiateType((type as SubstitutionType).baseType, mapper); if (maybeVariable.flags & TypeFlags.TypeVariable) { - return getSubstitutionType(maybeVariable as TypeVariable, instantiateType((type).substitute, mapper)); + return getSubstitutionType(maybeVariable as TypeVariable, instantiateType((type as SubstitutionType).substitute, mapper)); } else { - const sub = instantiateType((type).substitute, mapper); + const sub = instantiateType((type as SubstitutionType).substitute, mapper); if (sub.flags & TypeFlags.AnyOrUnknown || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { return maybeVariable; } @@ -16351,23 +16350,23 @@ namespace ts { case SyntaxKind.ArrowFunction: case SyntaxKind.MethodDeclaration: case SyntaxKind.FunctionDeclaration: // Function declarations can have context when annotated with a jsdoc @type - return isContextSensitiveFunctionLikeDeclaration(node); + return isContextSensitiveFunctionLikeDeclaration(node as FunctionExpression | ArrowFunction | MethodDeclaration); case SyntaxKind.ObjectLiteralExpression: - return some((node).properties, isContextSensitive); + return some((node as ObjectLiteralExpression).properties, isContextSensitive); case SyntaxKind.ArrayLiteralExpression: - return some((node).elements, isContextSensitive); + return some((node as ArrayLiteralExpression).elements, isContextSensitive); case SyntaxKind.ConditionalExpression: - return isContextSensitive((node).whenTrue) || - isContextSensitive((node).whenFalse); + return isContextSensitive((node as ConditionalExpression).whenTrue) || + isContextSensitive((node as ConditionalExpression).whenFalse); case SyntaxKind.BinaryExpression: - return ((node).operatorToken.kind === SyntaxKind.BarBarToken || (node).operatorToken.kind === SyntaxKind.QuestionQuestionToken) && - (isContextSensitive((node).left) || isContextSensitive((node).right)); + return ((node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken || (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken) && + (isContextSensitive((node as BinaryExpression).left) || isContextSensitive((node as BinaryExpression).right)); case SyntaxKind.PropertyAssignment: - return isContextSensitive((node).initializer); + return isContextSensitive((node as PropertyAssignment).initializer); case SyntaxKind.ParenthesizedExpression: - return isContextSensitive((node).expression); + return isContextSensitive((node as ParenthesizedExpression).expression); case SyntaxKind.JsxAttributes: - return some((node).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); + return some((node as JsxAttributes).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); case SyntaxKind.JsxAttribute: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. const { initializer } = node as JsxAttribute; @@ -16419,7 +16418,7 @@ namespace ts { function getTypeWithoutSignatures(type: Type): Type { if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); if (resolved.constructSignatures.length || resolved.callSignatures.length) { const result = createObjectType(ObjectFlags.Anonymous, type.symbol); result.members = resolved.members; @@ -16430,7 +16429,7 @@ namespace ts { } } else if (type.flags & TypeFlags.Intersection) { - return getIntersectionType(map((type).types, getTypeWithoutSignatures)); + return getIntersectionType(map((type as IntersectionType).types, getTypeWithoutSignatures)); } return type; } @@ -16470,8 +16469,8 @@ namespace ts { // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source: Type, target: Type): boolean { - return source.flags & TypeFlags.Union ? every((source).types, t => isTypeDerivedFrom(t, target)) : - target.flags & TypeFlags.Union ? some((target).types, t => isTypeDerivedFrom(source, t)) : + return source.flags & TypeFlags.Union ? every((source as UnionType).types, t => isTypeDerivedFrom(t, target)) : + target.flags & TypeFlags.Union ? some((target as UnionType).types, t => isTypeDerivedFrom(source, t)) : source.flags & TypeFlags.InstantiableNonPrimitive ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : @@ -17190,22 +17189,22 @@ namespace ts { } function isEmptyObjectType(type: Type): boolean { - return type.flags & TypeFlags.Object ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & TypeFlags.Object ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type as ObjectType)) : type.flags & TypeFlags.NonPrimitive ? true : - type.flags & TypeFlags.Union ? some((type).types, isEmptyObjectType) : - type.flags & TypeFlags.Intersection ? every((type).types, isEmptyObjectType) : + type.flags & TypeFlags.Union ? some((type as UnionType).types, isEmptyObjectType) : + type.flags & TypeFlags.Intersection ? every((type as UnionType).types, isEmptyObjectType) : false; } function isEmptyAnonymousObjectType(type: Type) { return !!(getObjectFlags(type) & ObjectFlags.Anonymous && ( - (type).members && isEmptyResolvedType(type) || + (type as ResolvedType).members && isEmptyResolvedType(type as ResolvedType) || type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && getMembersOfSymbol(type.symbol).size === 0)); } function isStringIndexSignatureOnlyType(type: Type): boolean { return type.flags & TypeFlags.Object && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, IndexKind.String) && !getIndexInfoOfType(type, IndexKind.Number) || - type.flags & TypeFlags.UnionOrIntersection && every((type).types, isStringIndexSignatureOnlyType) || + type.flags & TypeFlags.UnionOrIntersection && every((type as UnionOrIntersectionType).types, isStringIndexSignatureOnlyType) || false; } @@ -17251,11 +17250,11 @@ namespace ts { if (s & TypeFlags.StringLike && t & TypeFlags.String) return true; if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) && - (source).value === (target).value) return true; + (source as StringLiteralType).value === (target as StringLiteralType).value) return true; if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true; if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && - (source).value === (target).value) return true; + (source as NumberLiteralType).value === (target as NumberLiteralType).value) return true; if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true; if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true; @@ -17263,7 +17262,7 @@ namespace ts { if (s & TypeFlags.EnumLiteral && t & TypeFlags.EnumLiteral) { if (s & TypeFlags.Union && t & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & TypeFlags.Literal && t & TypeFlags.Literal && - (source).value === (target).value && + (source as LiteralType).value === (target as LiteralType).value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol)!, getParentOfSymbol(target.symbol)!, errorReporter)) return true; } if (s & TypeFlags.Undefined && (!strictNullChecks || t & (TypeFlags.Undefined | TypeFlags.Void))) return true; @@ -17282,10 +17281,10 @@ namespace ts { function isTypeRelatedTo(source: Type, target: Type, relation: ESMap) { if (isFreshLiteralType(source)) { - source = (source).regularType; + source = (source as FreshableType).regularType; } if (isFreshLiteralType(target)) { - target = (target).regularType; + target = (target as FreshableType).regularType; } if (source === target) { return true; @@ -17317,10 +17316,10 @@ namespace ts { function getNormalizedType(type: Type, writing: boolean): Type { while (true) { - let t = isFreshLiteralType(type) ? (type).regularType : - getObjectFlags(type) & ObjectFlags.Reference && (type).node ? createTypeReference((type).target, getTypeArguments(type)) : + let t = isFreshLiteralType(type) ? (type as FreshableType).regularType : + getObjectFlags(type) & ObjectFlags.Reference && (type as TypeReference).node ? createTypeReference((type as TypeReference).target, getTypeArguments(type as TypeReference)) : type.flags & TypeFlags.UnionOrIntersection ? getReducedType(type) : - type.flags & TypeFlags.Substitution ? writing ? (type).baseType : (type).substitute : + type.flags & TypeFlags.Substitution ? writing ? (type as SubstitutionType).baseType : (type as SubstitutionType).substitute : type.flags & TypeFlags.Simplifiable ? getSimplifiedType(type, writing) : type; t = getSingleBaseForNonAugmentingSubtype(t) || t; @@ -17725,7 +17724,7 @@ namespace ts { const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); const isPerformingExcessPropertyChecks = !(intersectionState & IntersectionState.Target) && (isObjectLiteralType(source) && getObjectFlags(source) & ObjectFlags.FreshLiteral); if (isPerformingExcessPropertyChecks) { - if (hasExcessProperties(source, target, reportErrors)) { + if (hasExcessProperties(source as FreshObjectLiteralType, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target); } @@ -17786,7 +17785,7 @@ namespace ts { // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source).types: [source], !!(target.flags & TypeFlags.Union)); + const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types: [source], !!(target.flags & TypeFlags.Union)); if (constraint && (source.flags & TypeFlags.Intersection || target.flags & TypeFlags.Union)) { if (everyType(constraint, c => c !== source)) { // Skip comparison if expansion contains the source itself // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this @@ -17814,7 +17813,7 @@ namespace ts { // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && ( target.flags & TypeFlags.Intersection && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source as IntersectionType).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, IntersectionState.PropertyCheck); inPropertyCheck = false; @@ -17905,9 +17904,9 @@ namespace ts { } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & TypeFlags.UnionOrIntersection) { - let result = eachTypeRelatedToSomeType(source, target); + let result = eachTypeRelatedToSomeType(source as UnionOrIntersectionType, target as UnionOrIntersectionType); if (result) { - result &= eachTypeRelatedToSomeType(target, source); + result &= eachTypeRelatedToSomeType(target as UnionOrIntersectionType, source as UnionOrIntersectionType); } return result; } @@ -17917,7 +17916,7 @@ namespace ts { function getTypeOfPropertyInTypes(types: Type[], name: __String) { const appendPropType = (propTypes: Type[] | undefined, type: Type) => { type = getApparentType(type); - const prop = type.flags & TypeFlags.UnionOrIntersection ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name); + const prop = type.flags & TypeFlags.UnionOrIntersection ? getPropertyOfUnionOrIntersectionType(type as UnionOrIntersectionType, name) : getPropertyOfObjectType(type, name); const propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, IndexKind.Number) || getIndexTypeOfType(type, IndexKind.String) || undefinedType; return append(propTypes, propType); }; @@ -17936,8 +17935,8 @@ namespace ts { let reducedTarget = target; let checkTypes: Type[] | undefined; if (target.flags & TypeFlags.Union) { - reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); - checkTypes = reducedTarget.flags & TypeFlags.Union ? (reducedTarget).types : [reducedTarget]; + reducedTarget = findMatchingDiscriminantType(source, target as UnionType, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target as UnionType); + checkTypes = reducedTarget.flags & TypeFlags.Union ? (reducedTarget as UnionType).types : [reducedTarget]; } for (const prop of getPropertiesOfType(source)) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { @@ -18029,7 +18028,7 @@ namespace ts { if (containsType(targetTypes, source)) { return Ternary.True; } - const match = getMatchingUnionConstituentForType(target, source); + const match = getMatchingUnionConstituentForType(target as UnionType, source); if (match) { const related = isRelatedTo(source, match, /*reportErrors*/ false); if (related) { @@ -18305,7 +18304,7 @@ namespace ts { eachTypeRelatedToType(source as UnionType, target, reportErrors && !(source.flags & TypeFlags.Primitive), intersectionState & ~IntersectionState.UnionIntersectionCheck); } if (target.flags & TypeFlags.Union) { - return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive)); + return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target as UnionType, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive)); } if (target.flags & TypeFlags.Intersection) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target as IntersectionType, reportErrors, IntersectionState.Target); @@ -18316,8 +18315,8 @@ namespace ts { // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't // appear to be comparable to '2'. if (relation === comparableRelation && target.flags & TypeFlags.Primitive) { - const constraints = sameMap((source).types, t => t.flags & TypeFlags.Primitive ? t : getBaseConstraintOfType(t) || unknownType); - if (constraints !== (source).types) { + const constraints = sameMap((source as IntersectionType).types, t => t.flags & TypeFlags.Primitive ? t : getBaseConstraintOfType(t) || unknownType); + if (constraints !== (source as IntersectionType).types) { source = getIntersectionType(constraints); if (!(source.flags & TypeFlags.Intersection)) { return isRelatedTo(source, target, /*reportErrors*/ false); @@ -18337,27 +18336,27 @@ namespace ts { // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - return someTypeRelatedToType(source, target, /*reportErrors*/ false, IntersectionState.Source); + return someTypeRelatedToType(source as IntersectionType, target, /*reportErrors*/ false, IntersectionState.Source); } const flags = source.flags & target.flags; if (relation === identityRelation && !(flags & TypeFlags.Object)) { if (flags & TypeFlags.Index) { - return isRelatedTo((source).type, (target).type, /*reportErrors*/ false); + return isRelatedTo((source as IndexType).type, (target as IndexType).type, /*reportErrors*/ false); } let result = Ternary.False; if (flags & TypeFlags.IndexedAccess) { - if (result = isRelatedTo((source).objectType, (target).objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo((source).indexType, (target).indexType, /*reportErrors*/ false)) { + if (result = isRelatedTo((source as IndexedAccessType).objectType, (target as IndexedAccessType).objectType, /*reportErrors*/ false)) { + if (result &= isRelatedTo((source as IndexedAccessType).indexType, (target as IndexedAccessType).indexType, /*reportErrors*/ false)) { return result; } } } if (flags & TypeFlags.Conditional) { - if ((source).root.isDistributive === (target).root.isDistributive) { - if (result = isRelatedTo((source).checkType, (target).checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo((source).extendsType, (target).extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if ((source as ConditionalType).root.isDistributive === (target as ConditionalType).root.isDistributive) { + if (result = isRelatedTo((source as ConditionalType).checkType, (target as ConditionalType).checkType, /*reportErrors*/ false)) { + if (result &= isRelatedTo((source as ConditionalType).extendsType, (target as ConditionalType).extendsType, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source as ConditionalType), getTrueTypeFromConditionalType(target as ConditionalType), /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source as ConditionalType), getFalseTypeFromConditionalType(target as ConditionalType), /*reportErrors*/ false)) { return result; } } @@ -18366,7 +18365,7 @@ namespace ts { } } if (flags & TypeFlags.Substitution) { - return isRelatedTo((source).substitute, (target).substitute, /*reportErrors*/ false); + return isRelatedTo((source as SubstitutionType).substitute, (target as SubstitutionType).substitute, /*reportErrors*/ false); } return Ternary.False; } @@ -18401,11 +18400,11 @@ namespace ts { if (target.flags & TypeFlags.TypeParameter) { // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. - if (getObjectFlags(source) & ObjectFlags.Mapped && !(source).declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { + if (getObjectFlags(source) & ObjectFlags.Mapped && !(source as MappedType).declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source as MappedType))) { - if (!(getMappedTypeModifiers(source) & MappedTypeModifiers.IncludeOptional)) { - const templateType = getTemplateTypeFromMappedType(source); - const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (!(getMappedTypeModifiers(source as MappedType) & MappedTypeModifiers.IncludeOptional)) { + const templateType = getTemplateTypeFromMappedType(source as MappedType); + const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source as MappedType)); if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { return result; } @@ -18416,7 +18415,7 @@ namespace ts { const targetType = (target as IndexType).type; // A keyof S is related to a keyof T if T is related to S. if (source.flags & TypeFlags.Index) { - if (result = isRelatedTo(targetType, (source).type, /*reportErrors*/ false)) { + if (result = isRelatedTo(targetType, (source as IndexType).type, /*reportErrors*/ false)) { return result; } } @@ -18446,8 +18445,8 @@ namespace ts { if (source.flags & TypeFlags.IndexedAccess) { // Relate components directly before falling back to constraint relationships // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) { - result &= isRelatedTo((source).indexType, (target).indexType, reportErrors); + if (result = isRelatedTo((source as IndexedAccessType).objectType, (target as IndexedAccessType).objectType, reportErrors)) { + result &= isRelatedTo((source as IndexedAccessType).indexType, (target as IndexedAccessType).indexType, reportErrors); } if (result) { resetErrorInfo(saveErrorInfo); @@ -18460,13 +18459,13 @@ namespace ts { // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { - const objectType = (target).objectType; - const indexType = (target).indexType; + const objectType = (target as IndexedAccessType).objectType; + const indexType = (target as IndexedAccessType).indexType; const baseObjectType = getBaseConstraintOfType(objectType) || objectType; const baseIndexType = getBaseConstraintOfType(indexType) || indexType; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { const accessFlags = AccessFlags.Writing | (baseObjectType !== objectType ? AccessFlags.NoIndexSignatures : 0); - const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, (target).noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); + const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, accessFlags); if (constraint) { if (reportErrors && originalErrorInfo) { // create a new chain for the constraint error @@ -18491,8 +18490,8 @@ namespace ts { const template = getTemplateTypeFromMappedType(target); const modifiers = getMappedTypeModifiers(target); if (!(modifiers & MappedTypeModifiers.ExcludeOptional)) { - if (template.flags & TypeFlags.IndexedAccess && (template).objectType === source && - (template).indexType === getTypeParameterFromMappedType(target)) { + if (template.flags & TypeFlags.IndexedAccess && (template as IndexedAccessType).objectType === source && + (template as IndexedAccessType).indexType === getTypeParameterFromMappedType(target)) { return Ternary.True; } if (!isGenericMappedType(source)) { @@ -18574,7 +18573,7 @@ namespace ts { if (source.flags & TypeFlags.TypeVariable) { // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch if (!(source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess)) { - const constraint = getConstraintOfType(source); + const constraint = getConstraintOfType(source as TypeVariable); if (!constraint || (source.flags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.Any)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~TypeFlags.NonPrimitive))) { @@ -18611,8 +18610,8 @@ namespace ts { } } else if (source.flags & TypeFlags.StringMapping) { - if (target.flags & TypeFlags.StringMapping && (source).symbol === (target).symbol) { - if (result = isRelatedTo((source).type, (target).type, reportErrors)) { + if (target.flags & TypeFlags.StringMapping && (source as StringMappingType).symbol === (target as StringMappingType).symbol) { + if (result = isRelatedTo((source as StringMappingType).type, (target as StringMappingType).type, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -18631,19 +18630,19 @@ namespace ts { // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. const sourceParams = (source as ConditionalType).root.inferTypeParameters; - let sourceExtends = (source).extendsType; + let sourceExtends = (source as ConditionalType).extendsType; let mapper: TypeMapper | undefined; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target const ctx = createInferenceContext(sourceParams, /*signature*/ undefined, InferenceFlags.None, isRelatedTo); - inferTypes(ctx.inferences, (target).extendsType, sourceExtends, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict); + inferTypes(ctx.inferences, (target as ConditionalType).extendsType, sourceExtends, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } - if (isTypeIdenticalTo(sourceExtends, (target).extendsType) && - (isRelatedTo((source).checkType, (target).checkType) || isRelatedTo((target).checkType, (source).checkType))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (isTypeIdenticalTo(sourceExtends, (target as ConditionalType).extendsType) && + (isRelatedTo((source as ConditionalType).checkType, (target as ConditionalType).checkType) || isRelatedTo((target as ConditionalType).checkType, (source as ConditionalType).checkType))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source as ConditionalType), mapper), getTrueTypeFromConditionalType(target as ConditionalType), reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source as ConditionalType), getFalseTypeFromConditionalType(target as ConditionalType), reportErrors); } if (result) { resetErrorInfo(saveErrorInfo); @@ -18654,7 +18653,7 @@ namespace ts { else { // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way // more assignments than are desirable (since it maps the source check type to its constraint, it loses information) - const distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + const distributiveConstraint = getConstraintOfDistributiveConditionalType(source as ConditionalType); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); @@ -18664,7 +18663,7 @@ namespace ts { } // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!). - const defaultConstraint = getDefaultConstraintOfConditionalType(source); + const defaultConstraint = getDefaultConstraintOfConditionalType(source as ConditionalType); if (defaultConstraint) { if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); @@ -18693,19 +18692,19 @@ namespace ts { else if (isGenericMappedType(source)) { return Ternary.False; } - if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target && + if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target && !(getObjectFlags(source) & ObjectFlags.MarkerType || getObjectFlags(target) & ObjectFlags.MarkerType)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. - const variances = getVariances((source).target); + const variances = getVariances((source as TypeReference).target); // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This // effectively means we measure variance only from type parameter occurrences that aren't nested in // recursive instantiations of the generic type. if (variances === emptyArray) { return Ternary.Unknown; } - const varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); + const varianceResult = relateVariances(getTypeArguments(source as TypeReference), getTypeArguments(target as TypeReference), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; } @@ -19420,7 +19419,7 @@ namespace ts { function eachPropertyRelatedTo(source: Type, target: Type, kind: IndexKind, reportErrors: boolean): Ternary { let result = Ternary.True; - const props = source.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source); + const props = source.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(source as IntersectionType) : getPropertiesOfObjectType(source); for (const prop of props) { // Skip over ignored JSX and symbol-named members if (isIgnoredJsxProperty(source, prop)) { @@ -19617,14 +19616,14 @@ namespace ts { */ function isWeakType(type: Type): boolean { if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && every(resolved.properties, p => !!(p.flags & SymbolFlags.Optional)); } if (type.flags & TypeFlags.Intersection) { - return every((type).types, isWeakType); + return every((type as IntersectionType).types, isWeakType); } return false; } @@ -19723,11 +19722,11 @@ namespace ts { } function isUnconstrainedTypeParameter(type: Type) { - return type.flags & TypeFlags.TypeParameter && !getConstraintOfTypeParameter(type); + return type.flags & TypeFlags.TypeParameter && !getConstraintOfTypeParameter(type as TypeParameter); } function isNonDeferredTypeReference(type: Type): type is TypeReference { - return !!(getObjectFlags(type) & ObjectFlags.Reference) && !(type).node; + return !!(getObjectFlags(type) & ObjectFlags.Reference) && !(type as TypeReference).node; } function isTypeReferenceWithGenericArguments(type: Type): boolean { @@ -19772,7 +19771,7 @@ namespace ts { const postFix = intersectionState ? ":" + intersectionState : ""; if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { const typeParameters: Type[] = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix; + return getTypeReferenceId(source as TypeReference, typeParameters) + "," + getTypeReferenceId(target as TypeReference, typeParameters) + postFix; } return source.id + "," + target.id + postFix; } @@ -19781,7 +19780,7 @@ namespace ts { // value that isn't undefined. function forEachProperty(prop: Symbol, callback: (p: Symbol) => T): T | undefined { if (getCheckFlags(prop) & CheckFlags.Synthetic) { - for (const t of (prop).containingType!.types) { + for (const t of (prop as TransientSymbol).containingType!.types) { const p = getPropertyOfType(t, prop.escapedName); const result = p && forEachProperty(p, callback); if (result) { @@ -19795,7 +19794,7 @@ namespace ts { // Return the declaring class type of a property or undefined if property not declared in class function getDeclaringClass(prop: Symbol) { - return prop.parent && prop.parent.flags & SymbolFlags.Class ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)!) : undefined; + return prop.parent && prop.parent.flags & SymbolFlags.Class ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)!) as InterfaceType : undefined; } // Return the inherited type of the given property or undefined if property doesn't exist in a base class. @@ -20063,11 +20062,11 @@ namespace ts { } function isArrayType(type: Type): type is TypeReference { - return !!(getObjectFlags(type) & ObjectFlags.Reference) && ((type).target === globalArrayType || (type).target === globalReadonlyArrayType); + return !!(getObjectFlags(type) & ObjectFlags.Reference) && ((type as TypeReference).target === globalArrayType || (type as TypeReference).target === globalReadonlyArrayType); } function isReadonlyArrayType(type: Type): boolean { - return !!(getObjectFlags(type) & ObjectFlags.Reference) && (type).target === globalReadonlyArrayType; + return !!(getObjectFlags(type) & ObjectFlags.Reference) && (type as TypeReference).target === globalReadonlyArrayType; } function isMutableArrayOrTuple(type: Type): boolean { @@ -20131,7 +20130,7 @@ namespace ts { return propType; } if (everyType(type, isTupleType)) { - return mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); + return mapType(type, t => getRestTypeOfTupleType(t as TupleTypeReference) || undefinedType); } return undefined; } @@ -20145,43 +20144,43 @@ namespace ts { } function isUnitLikeType(type: Type): boolean { - return type.flags & TypeFlags.Intersection ? some((type).types, isUnitType) : + return type.flags & TypeFlags.Intersection ? some((type as IntersectionType).types, isUnitType) : !!(type.flags & TypeFlags.Unit); } function extractUnitType(type: Type) { - return type.flags & TypeFlags.Intersection ? find((type).types, isUnitType) || type : type; + return type.flags & TypeFlags.Intersection ? find((type as IntersectionType).types, isUnitType) || type : type; } function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : - type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : every((type).types, isUnitType) : + type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : every((type as UnionType).types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type as LiteralType) : type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral ? booleanType : - type.flags & TypeFlags.Union ? mapType(type, getBaseTypeOfLiteralType) : + type.flags & TypeFlags.Union ? mapType(type as UnionType, getBaseTypeOfLiteralType) : type; } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.EnumLiteral && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & TypeFlags.EnumLiteral && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type as LiteralType) : type.flags & TypeFlags.StringLiteral && isFreshLiteralType(type) ? stringType : type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : - type.flags & TypeFlags.Union ? mapType(type, getWidenedLiteralType) : + type.flags & TypeFlags.Union ? mapType(type as UnionType, getWidenedLiteralType) : type; } function getWidenedUniqueESSymbolType(type: Type): Type { return type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : - type.flags & TypeFlags.Union ? mapType(type, getWidenedUniqueESSymbolType) : + type.flags & TypeFlags.Union ? mapType(type as UnionType, getWidenedUniqueESSymbolType) : type; } @@ -20216,7 +20215,7 @@ namespace ts { * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required. */ function isTupleType(type: Type): type is TupleTypeReference { - return !!(getObjectFlags(type) & ObjectFlags.Reference && (type).target.objectFlags & ObjectFlags.Tuple); + return !!(getObjectFlags(type) & ObjectFlags.Reference && (type as TypeReference).target.objectFlags & ObjectFlags.Tuple); } function isGenericTupleType(type: Type): type is TupleTypeReference { @@ -20271,10 +20270,10 @@ namespace ts { // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type: Type): TypeFlags { - return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : - type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : - type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : - type.flags & TypeFlags.BigIntLiteral ? isZeroBigInt(type) ? TypeFlags.BigIntLiteral : 0 : + return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type as UnionType).types) : + type.flags & TypeFlags.StringLiteral ? (type as StringLiteralType).value === "" ? TypeFlags.StringLiteral : 0 : + type.flags & TypeFlags.NumberLiteral ? (type as NumberLiteralType).value === 0 ? TypeFlags.NumberLiteral : 0 : + type.flags & TypeFlags.BigIntLiteral ? isZeroBigInt(type as BigIntLiteralType) ? TypeFlags.BigIntLiteral : 0 : type.flags & TypeFlags.BooleanLiteral ? (type === falseType || type === regularFalseType) ? TypeFlags.BooleanLiteral : 0 : type.flags & TypeFlags.PossiblyFalsy; } @@ -20296,9 +20295,9 @@ namespace ts { type === regularFalseType || type === falseType || type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || - type.flags & TypeFlags.StringLiteral && (type).value === "" || - type.flags & TypeFlags.NumberLiteral && (type).value === 0 || - type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type) ? type : + type.flags & TypeFlags.StringLiteral && (type as StringLiteralType).value === "" || + type.flags & TypeFlags.NumberLiteral && (type as NumberLiteralType).value === 0 || + type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type as BigIntLiteralType) ? type : neverType; } @@ -20387,7 +20386,7 @@ namespace ts { * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type: Type): boolean { - return type.flags & TypeFlags.Intersection ? every((type).types, isObjectTypeWithInferableIndex) : + return type.flags & TypeFlags.Intersection ? every((type as IntersectionType).types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (SymbolFlags.ObjectLiteral | SymbolFlags.TypeLiteral | SymbolFlags.Enum | SymbolFlags.ValueModule)) !== 0 && !typeHasCallOrConstructSignatures(type)) || !!(getObjectFlags(type) & ObjectFlags.ReverseMapped && isObjectTypeWithInferableIndex((type as ReverseMappedType).source)); } @@ -20427,12 +20426,12 @@ namespace ts { if (!(isObjectLiteralType(type) && getObjectFlags(type) & ObjectFlags.FreshLiteral)) { return type; } - const regularType = (type).regularType; + const regularType = (type as FreshObjectLiteralType).regularType; if (regularType) { return regularType; } - const resolved = type; + const resolved = type as ResolvedType; const members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); const regularNew = createAnonymousType(resolved.symbol, members, @@ -20442,7 +20441,7 @@ namespace ts { resolved.numberIndexInfo); regularNew.flags = resolved.flags; regularNew.objectFlags |= resolved.objectFlags & ~ObjectFlags.FreshLiteral; - (type).regularType = regularNew; + (type as FreshObjectLiteralType).regularType = regularNew; return regularNew; } @@ -20544,15 +20543,15 @@ namespace ts { result = getWidenedTypeOfObjectLiteral(type, context); } else if (type.flags & TypeFlags.Union) { - const unionContext = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, (type).types); - const widenedTypes = sameMap((type).types, t => t.flags & TypeFlags.Nullable ? t : getWidenedTypeWithContext(t, unionContext)); + const unionContext = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, (type as UnionType).types); + const widenedTypes = sameMap((type as UnionType).types, t => t.flags & TypeFlags.Nullable ? t : getWidenedTypeWithContext(t, unionContext)); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? UnionReduction.Subtype : UnionReduction.Literal); } else if (type.flags & TypeFlags.Intersection) { - result = getIntersectionType(sameMap((type).types, getWidenedType)); + result = getIntersectionType(sameMap((type as IntersectionType).types, getWidenedType)); } else if (isArrayType(type) || isTupleType(type)) { result = createTypeReference(type.target, sameMap(getTypeArguments(type), getWidenedType)); @@ -20580,11 +20579,11 @@ namespace ts { let errorReported = false; if (getObjectFlags(type) & ObjectFlags.ContainsWideningType) { if (type.flags & TypeFlags.Union) { - if (some((type).types, isEmptyObjectType)) { + if (some((type as UnionType).types, isEmptyObjectType)) { errorReported = true; } else { - for (const t of (type).types) { + for (const t of (type as UnionType).types) { if (reportWideningErrorsInType(t)) { errorReported = true; } @@ -20637,7 +20636,7 @@ namespace ts { errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, declarationNameToString(param.name)); return; } - diagnostic = (declaration).dotDotDotToken ? + diagnostic = (declaration as ParameterDeclaration).dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; @@ -20814,12 +20813,12 @@ namespace ts { } const result = !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.Object && !isNonGenericTopLevelType(type) && ( - objectFlags & ObjectFlags.Reference && ((type).node || forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & ObjectFlags.Reference && ((type as TypeReference).node || forEach(getTypeArguments(type as TypeReference), couldContainTypeVariables)) || objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType)) || - type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type).types, couldContainTypeVariables)); + type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type as UnionOrIntersectionType).types, couldContainTypeVariables)); if (type.flags & TypeFlags.ObjectFlagsType) { - (type).objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0); + (type as ObjectFlagsType).objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0); } return result; } @@ -20834,8 +20833,8 @@ namespace ts { function isTypeParameterAtTopLevel(type: Type, typeParameter: TypeParameter): boolean { return !!(type === typeParameter || - type.flags & TypeFlags.UnionOrIntersection && some((type).types, t => isTypeParameterAtTopLevel(t, typeParameter)) || - type.flags & TypeFlags.Conditional && (getTrueTypeFromConditionalType(type) === typeParameter || getFalseTypeFromConditionalType(type) === typeParameter)); + type.flags & TypeFlags.UnionOrIntersection && some((type as UnionOrIntersectionType).types, t => isTypeParameterAtTopLevel(t, typeParameter)) || + type.flags & TypeFlags.Conditional && (getTrueTypeFromConditionalType(type as ConditionalType) === typeParameter || getFalseTypeFromConditionalType(type as ConditionalType) === typeParameter)); } /** Create an object with properties named in the string literal type. Every property has type `any` */ @@ -20925,7 +20924,7 @@ namespace ts { } function inferReverseMappedType(sourceType: Type, target: MappedType, constraint: IndexType): Type { - const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); + const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)) as TypeParameter; const templateType = getTemplateTypeFromMappedType(target); const inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); @@ -21012,23 +21011,23 @@ namespace ts { return true; } if (source.flags & TypeFlags.StringLiteral) { - const value = (source).value; + const value = (source as StringLiteralType).value; return !!(target.flags & TypeFlags.Number && value !== "" && isFinite(+value) || target.flags & TypeFlags.BigInt && value !== "" && isValidBigIntString(value) || - target.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) && value === (target).intrinsicName); + target.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) && value === (target as IntrinsicType).intrinsicName); } if (source.flags & TypeFlags.TemplateLiteral) { - const texts = (source).texts; - return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo((source).types[0], target); + const texts = (source as TemplateLiteralType).texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo((source as TemplateLiteralType).types[0], target); } return isTypeAssignableTo(source, target); } function inferTypesFromTemplateLiteralType(source: Type, target: TemplateLiteralType): Type[] | undefined { - return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source).value], emptyArray, target) : + return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source as StringLiteralType).value], emptyArray, target) : source.flags & TypeFlags.TemplateLiteral ? - arraysEqual((source).texts, target.texts) ? map((source).types, getStringLikeTypeForType) : - inferFromLiteralPartsToTemplateLiteral((source).texts, (source).types, target) : + arraysEqual((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral((source as TemplateLiteralType).texts, (source as TemplateLiteralType).types, target) : undefined; } @@ -21146,7 +21145,7 @@ namespace ts { if (source === target && source.flags & TypeFlags.UnionOrIntersection) { // When source and target are the same union or intersection type, just relate each constituent // type to itself. - for (const t of (source).types) { + for (const t of (source as UnionOrIntersectionType).types) { inferFromTypes(t, t); } return; @@ -21154,7 +21153,7 @@ namespace ts { if (target.flags & TypeFlags.Union) { // First, infer between identically matching source and target constituents and remove the // matching types. - const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & TypeFlags.Union ? (source).types : [source], (target).types, isTypeOrBaseIdenticalTo); + const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & TypeFlags.Union ? (source as UnionType).types : [source], (target as UnionType).types, isTypeOrBaseIdenticalTo); // Next, infer between closely matching source and target constituents and remove // the matching types. Types closely match when they are instantiations of the same // object type or instantiations of the same type alias. @@ -21174,7 +21173,7 @@ namespace ts { } source = getUnionType(sources); } - else if (target.flags & TypeFlags.Intersection && some((target).types, + else if (target.flags & TypeFlags.Intersection && some((target as IntersectionType).types, t => !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)))) { // We reduce intersection types only when they contain naked type parameters. For example, when // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and @@ -21184,7 +21183,7 @@ namespace ts { // in such scenarios. if (!(source.flags & TypeFlags.Union)) { // Infer between identically matching source and target constituents and remove the matching types. - const [sources, targets] = inferFromMatchingTypes(source.flags & TypeFlags.Intersection ? (source).types : [source], (target).types, isTypeIdenticalTo); + const [sources, targets] = inferFromMatchingTypes(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types : [source], (target as IntersectionType).types, isTypeIdenticalTo); if (sources.length === 0 || targets.length === 0) { return; } @@ -21231,7 +21230,7 @@ namespace ts { clearCachedInferences(inferences); } } - if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target as TypeParameter)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -21259,14 +21258,14 @@ namespace ts { } } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( - (source).target === (target).target || isArrayType(source) && isArrayType(target)) && - !((source).node && (target).node)) { + (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target)) && + !((source as TypeReference).node && (target as TypeReference).node)) { // If source and target are references to the same generic type, infer from type arguments - inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances((source).target)); + inferFromTypeArguments(getTypeArguments(source as TypeReference), getTypeArguments(target as TypeReference), getVariances((source as TypeReference).target)); } else if (source.flags & TypeFlags.Index && target.flags & TypeFlags.Index) { contravariant = !contravariant; - inferFromTypes((source).type, (target).type); + inferFromTypes((source as IndexType).type, (target as IndexType).type); contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & TypeFlags.String) && target.flags & TypeFlags.Index) { @@ -21276,12 +21275,12 @@ namespace ts { contravariant = !contravariant; } else if (source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess) { - inferFromTypes((source).objectType, (target).objectType); - inferFromTypes((source).indexType, (target).indexType); + inferFromTypes((source as IndexedAccessType).objectType, (target as IndexedAccessType).objectType); + inferFromTypes((source as IndexedAccessType).indexType, (target as IndexedAccessType).indexType); } else if (source.flags & TypeFlags.StringMapping && target.flags & TypeFlags.StringMapping) { - if ((source).symbol === (target).symbol) { - inferFromTypes((source).type, (target).type); + if ((source as StringMappingType).symbol === (target as StringMappingType).symbol) { + inferFromTypes((source as StringMappingType).type, (target as StringMappingType).type); } } else if (source.flags & TypeFlags.Substitution) { @@ -21295,17 +21294,17 @@ namespace ts { invokeOnce(source, target, inferToConditionalType); } else if (target.flags & TypeFlags.UnionOrIntersection) { - inferToMultipleTypes(source, (target).types, target.flags); + inferToMultipleTypes(source, (target as UnionOrIntersectionType).types, target.flags); } else if (source.flags & TypeFlags.Union) { // Source is a union or intersection type, infer from each constituent type - const sourceTypes = (source).types; + const sourceTypes = (source as UnionOrIntersectionType).types; for (const sourceType of sourceTypes) { inferFromTypes(sourceType, target); } } else if (target.flags & TypeFlags.TemplateLiteral) { - inferToTemplateLiteralType(source, target); + inferToTemplateLiteralType(source, target as TemplateLiteralType); } else { source = getReducedType(source); @@ -21427,7 +21426,7 @@ namespace ts { function getSingleTypeVariableFromIntersectionTypes(types: Type[]) { let typeVariable: Type | undefined; for (const type of types) { - const t = type.flags & TypeFlags.Intersection && find((type).types, t => !!getInferenceInfoForType(t)); + const t = type.flags & TypeFlags.Intersection && find((type as IntersectionType).types, t => !!getInferenceInfoForType(t)); if (!t || typeVariable && t !== typeVariable) { return undefined; } @@ -21440,7 +21439,7 @@ namespace ts { let typeVariableCount = 0; if (targetFlags & TypeFlags.Union) { let nakedTypeVariable: Type | undefined; - const sources = source.flags & TypeFlags.Union ? (source).types : [source]; + const sources = source.flags & TypeFlags.Union ? (source as UnionType).types : [source]; const matched = new Array(sources.length); let inferenceCircularity = false; // First infer to types that are not naked type variables. For each source type we @@ -21524,9 +21523,9 @@ namespace ts { // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference // such that direct inferences to T get priority over inferences to Partial, for example. - const inference = getInferenceInfoForType((constraintType).type); + const inference = getInferenceInfoForType((constraintType as IndexType).type); if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) { - const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType as IndexType); if (inferredType) { // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make @@ -21565,10 +21564,10 @@ namespace ts { function inferToConditionalType(source: Type, target: ConditionalType) { if (source.flags & TypeFlags.Conditional) { - inferFromTypes((source).checkType, target.checkType); - inferFromTypes((source).extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes((source as ConditionalType).checkType, target.checkType); + inferFromTypes((source as ConditionalType).extendsType, target.extendsType); + inferFromTypes(getTrueTypeFromConditionalType(source as ConditionalType), getTrueTypeFromConditionalType(target)); + inferFromTypes(getFalseTypeFromConditionalType(source as ConditionalType), getFalseTypeFromConditionalType(target)); } else { const savePriority = priority; @@ -21589,9 +21588,9 @@ namespace ts { function inferFromObjectTypes(source: Type, target: Type) { if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( - (source).target === (target).target || isArrayType(source) && isArrayType(target))) { + (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target))) { // If source and target are references to the same generic type, infer from type arguments - inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances((source).target)); + inferFromTypeArguments(getTypeArguments(source as TypeReference), getTypeArguments(target as TypeReference), getVariances((source as TypeReference).target)); return; } if (isGenericMappedType(source) && isGenericMappedType(target)) { @@ -21603,9 +21602,9 @@ namespace ts { const targetNameType = getNameTypeFromMappedType(target); if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType); } - if (getObjectFlags(target) & ObjectFlags.Mapped && !(target).declaration.nameType) { - const constraintType = getConstraintTypeFromMappedType(target); - if (inferToMappedType(source, target, constraintType)) { + if (getObjectFlags(target) & ObjectFlags.Mapped && !(target as MappedType).declaration.nameType) { + const constraintType = getConstraintTypeFromMappedType(target as MappedType); + if (inferToMappedType(source, target as MappedType, constraintType)) { return; } } @@ -21949,18 +21948,21 @@ namespace ts { function getFlowCacheKey(node: Node, declaredType: Type, initialType: Type, flowContainer: Node | undefined): string | undefined { switch (node.kind) { case SyntaxKind.Identifier: - const symbol = getResolvedSymbol(node); + const symbol = getResolvedSymbol(node as Identifier); return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : undefined; case SyntaxKind.ThisKeyword: return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: - return getFlowCacheKey((node).expression, declaredType, initialType, flowContainer); + return getFlowCacheKey((node as NonNullExpression | ParenthesizedExpression).expression, declaredType, initialType, flowContainer); + case SyntaxKind.QualifiedName: + const left = getFlowCacheKey((node as QualifiedName).left, declaredType, initialType, flowContainer); + return left && left + "." + (node as QualifiedName).right.escapedText; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - const propName = getAccessedPropertyName(node); + const propName = getAccessedPropertyName(node as AccessExpression); if (propName !== undefined) { - const key = getFlowCacheKey((node).expression, declaredType, initialType, flowContainer); + const key = getFlowCacheKey((node as AccessExpression).expression, declaredType, initialType, flowContainer); return key && key + "." + propName; } } @@ -21983,9 +21985,9 @@ namespace ts { && (source as MetaProperty).name.escapedText === (target as MetaProperty).name.escapedText; case SyntaxKind.Identifier: case SyntaxKind.PrivateIdentifier: - return target.kind === SyntaxKind.Identifier && getResolvedSymbol(source) === getResolvedSymbol(target) || + return target.kind === SyntaxKind.Identifier && getResolvedSymbol(source as Identifier) === getResolvedSymbol(target as Identifier) || (target.kind === SyntaxKind.VariableDeclaration || target.kind === SyntaxKind.BindingElement) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source as Identifier)) === getSymbolOfNode(target); case SyntaxKind.ThisKeyword: return target.kind === SyntaxKind.ThisKeyword; case SyntaxKind.SuperKeyword: @@ -22011,8 +22013,8 @@ namespace ts { // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source: Node, target: Node): boolean { return isMatchingReference(source, target) || - (target.kind === SyntaxKind.BinaryExpression && (target).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && - (containsTruthyCheck(source, (target).left) || containsTruthyCheck(source, (target).right))); + (target.kind === SyntaxKind.BinaryExpression && (target as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && + (containsTruthyCheck(source, (target as BinaryExpression).left) || containsTruthyCheck(source, (target as BinaryExpression).right))); } function getAccessedPropertyName(access: AccessExpression): __String | undefined { @@ -22043,14 +22045,14 @@ namespace ts { function isDiscriminantProperty(type: Type | undefined, name: __String) { if (type && type.flags & TypeFlags.Union) { - const prop = getUnionOrIntersectionProperty(type, name); + const prop = getUnionOrIntersectionProperty(type as UnionType, name); if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { - if ((prop).isDiscriminantProperty === undefined) { - (prop).isDiscriminantProperty = - ((prop).checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && + if ((prop as TransientSymbol).isDiscriminantProperty === undefined) { + (prop as TransientSymbol).isDiscriminantProperty = + ((prop as TransientSymbol).checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && !maybeTypeOfKind(getTypeOfSymbol(prop), TypeFlags.Instantiable); } - return !!(prop).isDiscriminantProperty; + return !!(prop as TransientSymbol).isDiscriminantProperty; } } return false; @@ -22142,7 +22144,7 @@ namespace ts { const keyPropertyName = getKeyPropertyName(unionType); const propNode = keyPropertyName && find(node.properties, p => p.symbol && p.kind === SyntaxKind.PropertyAssignment && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); - const propType = propNode && getTypeOfExpression((propNode).initializer); + const propType = propNode && getTypeOfExpression((propNode as PropertyAssignment).initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } @@ -22159,7 +22161,7 @@ namespace ts { } } if (expression.expression.kind === SyntaxKind.PropertyAccessExpression && - isOrContainsMatchingReference(reference, (expression.expression).expression)) { + isOrContainsMatchingReference(reference, (expression.expression as PropertyAccessExpression).expression)) { return true; } return false; @@ -22177,7 +22179,7 @@ namespace ts { if (!(source.flags & TypeFlags.Union)) { return isTypeAssignableTo(source, target); } - for (const t of (source).types) { + for (const t of (source as UnionType).types) { if (isTypeAssignableTo(t, target)) { return true; } @@ -22222,7 +22224,7 @@ namespace ts { return strictNullChecks ? TypeFacts.StringStrictFacts : TypeFacts.StringFacts; } if (flags & TypeFlags.StringLiteral) { - const isEmpty = (type).value === ""; + const isEmpty = (type as StringLiteralType).value === ""; return strictNullChecks ? isEmpty ? TypeFacts.EmptyStringStrictFacts : TypeFacts.NonEmptyStringStrictFacts : isEmpty ? TypeFacts.EmptyStringFacts : TypeFacts.NonEmptyStringFacts; @@ -22231,7 +22233,7 @@ namespace ts { return strictNullChecks ? TypeFacts.NumberStrictFacts : TypeFacts.NumberFacts; } if (flags & TypeFlags.NumberLiteral) { - const isZero = (type).value === 0; + const isZero = (type as NumberLiteralType).value === 0; return strictNullChecks ? isZero ? TypeFacts.ZeroNumberStrictFacts : TypeFacts.NonZeroNumberStrictFacts : isZero ? TypeFacts.ZeroNumberFacts : TypeFacts.NonZeroNumberFacts; @@ -22240,7 +22242,7 @@ namespace ts { return strictNullChecks ? TypeFacts.BigIntStrictFacts : TypeFacts.BigIntFacts; } if (flags & TypeFlags.BigIntLiteral) { - const isZero = isZeroBigInt(type); + const isZero = isZeroBigInt(type as BigIntLiteralType); return strictNullChecks ? isZero ? TypeFacts.ZeroBigIntStrictFacts : TypeFacts.NonZeroBigIntStrictFacts : isZero ? TypeFacts.ZeroBigIntFacts : TypeFacts.NonZeroBigIntFacts; @@ -22254,9 +22256,9 @@ namespace ts { (type === falseType || type === regularFalseType) ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; } if (flags & TypeFlags.Object && !ignoreObjects) { - return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type) ? + return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type as ObjectType) ? strictNullChecks ? TypeFacts.EmptyObjectStrictFacts : TypeFacts.EmptyObjectFacts : - isFunctionObjectType(type) ? + isFunctionObjectType(type as ObjectType) ? strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; } @@ -22280,13 +22282,13 @@ namespace ts { strictNullChecks ? TypeFacts.NonEmptyStringStrictFacts : TypeFacts.NonEmptyStringFacts; } if (flags & TypeFlags.Union) { - return reduceLeft((type).types, (facts, t) => facts | getTypeFacts(t, ignoreObjects), TypeFacts.None); + return reduceLeft((type as UnionType).types, (facts, t) => facts | getTypeFacts(t, ignoreObjects), TypeFacts.None); } if (flags & TypeFlags.Intersection) { // When an intersection contains a primitive type we ignore object type constituents as they are // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. ignoreObjects ||= maybeTypeOfKind(type, TypeFlags.Primitive); - return reduceLeft((type).types, (facts, t) => facts & getTypeFacts(t, ignoreObjects), TypeFacts.All); + return reduceLeft((type as UnionType).types, (facts, t) => facts & getTypeFacts(t, ignoreObjects), TypeFacts.All); } return TypeFacts.All; } @@ -22347,7 +22349,7 @@ namespace ts { } function getAssignedTypeOfSpreadExpression(node: SpreadElement): Type { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent as ArrayLiteralExpression)); } function getAssignedTypeOfPropertyAssignment(node: PropertyAssignment | ShorthandPropertyAssignment): Type { @@ -22364,28 +22366,28 @@ namespace ts { case SyntaxKind.ForInStatement: return stringType; case SyntaxKind.ForOfStatement: - return checkRightHandSideOfForOf(parent) || errorType; + return checkRightHandSideOfForOf(parent as ForOfStatement) || errorType; case SyntaxKind.BinaryExpression: - return getAssignedTypeOfBinaryExpression(parent); + return getAssignedTypeOfBinaryExpression(parent as BinaryExpression); case SyntaxKind.DeleteExpression: return undefinedType; case SyntaxKind.ArrayLiteralExpression: - return getAssignedTypeOfArrayLiteralElement(parent, node); + return getAssignedTypeOfArrayLiteralElement(parent as ArrayLiteralExpression, node); case SyntaxKind.SpreadElement: - return getAssignedTypeOfSpreadExpression(parent); + return getAssignedTypeOfSpreadExpression(parent as SpreadElement); case SyntaxKind.PropertyAssignment: - return getAssignedTypeOfPropertyAssignment(parent); + return getAssignedTypeOfPropertyAssignment(parent as PropertyAssignment); case SyntaxKind.ShorthandPropertyAssignment: - return getAssignedTypeOfShorthandPropertyAssignment(parent); + return getAssignedTypeOfShorthandPropertyAssignment(parent as ShorthandPropertyAssignment); } return errorType; } function getInitialTypeOfBindingElement(node: BindingElement): Type { const pattern = node.parent; - const parentType = getInitialType(pattern.parent); + const parentType = getInitialType(pattern.parent as VariableDeclaration | BindingElement); const type = pattern.kind === SyntaxKind.ObjectBindingPattern ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name as Identifier) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); @@ -22420,25 +22422,25 @@ namespace ts { } function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { - return node.kind === SyntaxKind.VariableDeclaration && (node).initializer && - isEmptyArrayLiteral((node).initializer!) || + return node.kind === SyntaxKind.VariableDeclaration && (node as VariableDeclaration).initializer && + isEmptyArrayLiteral((node as VariableDeclaration).initializer!) || node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && - isEmptyArrayLiteral((node.parent).right); + isEmptyArrayLiteral((node.parent as BinaryExpression).right); } function getReferenceCandidate(node: Expression): Expression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: - return getReferenceCandidate((node).expression); + return getReferenceCandidate((node as ParenthesizedExpression).expression); case SyntaxKind.BinaryExpression: - switch ((node).operatorToken.kind) { + switch ((node as BinaryExpression).operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.BarBarEqualsToken: case SyntaxKind.AmpersandAmpersandEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: - return getReferenceCandidate((node).left); + return getReferenceCandidate((node as BinaryExpression).left); case SyntaxKind.CommaToken: - return getReferenceCandidate((node).right); + return getReferenceCandidate((node as BinaryExpression).right); } } return node; @@ -22447,8 +22449,8 @@ namespace ts { function getReferenceRoot(node: Node): Node { const { parent } = node; return parent.kind === SyntaxKind.ParenthesizedExpression || - parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node || - parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.CommaToken && (parent).right === node ? + parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && (parent as BinaryExpression).left === node || + parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken && (parent as BinaryExpression).right === node ? getReferenceRoot(parent) : node; } @@ -22490,38 +22492,38 @@ namespace ts { } function eachTypeContainedIn(source: Type, types: Type[]) { - return source.flags & TypeFlags.Union ? !forEach((source).types, t => !contains(types, t)) : contains(types, source); + return source.flags & TypeFlags.Union ? !forEach((source as UnionType).types, t => !contains(types, t)) : contains(types, source); } function isTypeSubsetOf(source: Type, target: Type) { - return source === target || target.flags & TypeFlags.Union && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & TypeFlags.Union && isTypeSubsetOfUnion(source, target as UnionType); } function isTypeSubsetOfUnion(source: Type, target: UnionType) { if (source.flags & TypeFlags.Union) { - for (const t of (source).types) { + for (const t of (source as UnionType).types) { if (!containsType(target.types, t)) { return false; } } return true; } - if (source.flags & TypeFlags.EnumLiteral && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & TypeFlags.EnumLiteral && getBaseTypeOfEnumLiteralType(source as LiteralType) === target) { return true; } return containsType(target.types, source); } function forEachType(type: Type, f: (t: Type) => T | undefined): T | undefined { - return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); + return type.flags & TypeFlags.Union ? forEach((type as UnionType).types, f) : f(type); } function someType(type: Type, f: (t: Type) => boolean): boolean { - return type.flags & TypeFlags.Union ? some((type).types, f) : f(type); + return type.flags & TypeFlags.Union ? some((type as UnionType).types, f) : f(type); } function everyType(type: Type, f: (t: Type) => boolean): boolean { - return type.flags & TypeFlags.Union ? every((type).types, f) : f(type); + return type.flags & TypeFlags.Union ? every((type as UnionType).types, f) : f(type); } function everyContainedType(type: Type, f: (t: Type) => boolean): boolean { @@ -22530,12 +22532,12 @@ namespace ts { function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { - const types = (type).types; + const types = (type as UnionType).types; const filtered = filter(types, f); if (filtered === types) { return type; } - const origin = (type).origin; + const origin = (type as UnionType).origin; let newOrigin: Type | undefined; if (origin && origin.flags & TypeFlags.Union) { // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends @@ -22543,7 +22545,7 @@ namespace ts { // filtered types are within nested unions in the origin), then we can't construct a new origin type. // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. // Otherwise, construct a new filtered origin type. - const originTypes = (origin).types; + const originTypes = (origin as UnionType).types; const originFiltered = filter(originTypes, t => !!(t.flags & TypeFlags.Union) || f(t)); if (originTypes.length - originFiltered.length === types.length - filtered.length) { if (originFiltered.length === 1) { @@ -22552,7 +22554,7 @@ namespace ts { newOrigin = createOriginUnionOrIntersectionType(TypeFlags.Union, originFiltered); } } - return getUnionTypeFromSortedList(filtered, (type).objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); + return getUnionTypeFromSortedList(filtered, (type as UnionType).objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & TypeFlags.Never || f(type) ? type : neverType; } @@ -22573,8 +22575,8 @@ namespace ts { if (!(type.flags & TypeFlags.Union)) { return mapper(type); } - const origin = (type).origin; - const types = origin && origin.flags & TypeFlags.Union ? (origin).types : (type).types; + const origin = (type as UnionType).origin; + const types = origin && origin.flags & TypeFlags.Union ? (origin as UnionType).types : (type as UnionType).types; let mappedTypes: Type[] | undefined; let changed = false; for (const t of types) { @@ -22594,12 +22596,12 @@ namespace ts { function mapTypeWithAlias(type: Type, mapper: (t: Type) => Type, aliasSymbol: Symbol | undefined, aliasTypeArguments: readonly Type[] | undefined) { return type.flags & TypeFlags.Union && aliasSymbol ? - getUnionType(map((type).types, mapper), UnionReduction.Literal, aliasSymbol, aliasTypeArguments) : + getUnionType(map((type as UnionType).types, mapper), UnionReduction.Literal, aliasSymbol, aliasTypeArguments) : mapType(type, mapper); } function getConstituentCount(type: Type) { - return type.flags & TypeFlags.UnionOrIntersection ? (type).types.length : 1; + return type.flags & TypeFlags.UnionOrIntersection ? (type as UnionOrIntersectionType).types.length : 1; } function extractTypesOfKind(type: Type, kind: TypeFlags) { @@ -22626,7 +22628,7 @@ namespace ts { } function getTypeFromFlowType(flowType: FlowType) { - return flowType.flags === 0 ? (flowType).type : flowType; + return flowType.flags === 0 ? (flowType as IncompleteType).type : flowType as Type; } function createFlowType(type: Type, incomplete: boolean): FlowType { @@ -22638,7 +22640,7 @@ namespace ts { // array types are ultimately converted into manifest array types (using getFinalArrayType) // and never escape the getFlowTypeOfReference function. function createEvolvingArrayType(elementType: Type): EvolvingArrayType { - const result = createObjectType(ObjectFlags.EvolvingArray); + const result = createObjectType(ObjectFlags.EvolvingArray) as EvolvingArrayType; result.elementType = elementType; return result; } @@ -22659,7 +22661,7 @@ namespace ts { return elementType.flags & TypeFlags.Never ? autoArrayType : createArrayType(elementType.flags & TypeFlags.Union ? - getUnionType((elementType).types, UnionReduction.Subtype) : + getUnionType((elementType as UnionType).types, UnionReduction.Subtype) : elementType); } @@ -22669,11 +22671,11 @@ namespace ts { } function finalizeEvolvingArrayType(type: Type): Type { - return getObjectFlags(type) & ObjectFlags.EvolvingArray ? getFinalArrayType(type) : type; + return getObjectFlags(type) & ObjectFlags.EvolvingArray ? getFinalArrayType(type as EvolvingArrayType) : type; } function getElementTypeOfEvolvingArrayType(type: Type) { - return getObjectFlags(type) & ObjectFlags.EvolvingArray ? (type).elementType : neverType; + return getObjectFlags(type) & ObjectFlags.EvolvingArray ? (type as EvolvingArrayType).elementType : neverType; } function isEvolvingArrayTypeList(types: Type[]) { @@ -22700,12 +22702,12 @@ namespace ts { && isIdentifier(parent.name) && isPushOrUnshiftIdentifier(parent.name)); const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && - (parent).expression === root && + (parent as ElementAccessExpression).expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && - (parent.parent).operatorToken.kind === SyntaxKind.EqualsToken && - (parent.parent).left === parent && + (parent.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && + (parent.parent as BinaryExpression).left === parent && !isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression((parent).argumentExpression), TypeFlags.NumberLike); + isTypeAssignableToKind(getTypeOfExpression((parent as ElementAccessExpression).argumentExpression), TypeFlags.NumberLike); return isLengthPushOrUnshift || isElementAssignment; } @@ -22721,7 +22723,7 @@ namespace ts { } if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) { if (getCheckFlags(symbol) & CheckFlags.Mapped) { - const origin = (symbol).syntheticOrigin; + const origin = (symbol as MappedSymbol).syntheticOrigin; if (origin && getExplicitTypeOfSymbol(origin)) { return getTypeOfSymbol(symbol); } @@ -22754,16 +22756,16 @@ namespace ts { if (!(node.flags & NodeFlags.InWithStatement)) { switch (node.kind) { case SyntaxKind.Identifier: - const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); + const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node as Identifier)); return getExplicitTypeOfSymbol(symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol, diagnostic); case SyntaxKind.ThisKeyword: return getExplicitThisType(node); case SyntaxKind.SuperKeyword: return checkSuperExpression(node); case SyntaxKind.PropertyAccessExpression: { - const type = getTypeOfDottedName((node).expression, diagnostic); + const type = getTypeOfDottedName((node as PropertyAccessExpression).expression, diagnostic); if (type) { - const name = (node).name; + const name = (node as PropertyAccessExpression).name; let prop: Symbol | undefined; if (isPrivateIdentifier(name)) { if (!type.symbol) { @@ -22779,7 +22781,7 @@ namespace ts { return undefined; } case SyntaxKind.ParenthesizedExpression: - return getTypeOfDottedName((node).expression, diagnostic); + return getTypeOfDottedName((node as ParenthesizedExpression).expression, diagnostic); } } } @@ -22830,7 +22832,7 @@ namespace ts { } function reportFlowControlError(node: Node) { - const block = findAncestor(node, isFunctionOrModuleBlock); + const block = findAncestor(node, isFunctionOrModuleBlock) as Block | ModuleBlock | SourceFile; const sourceFile = getSourceFileOfNode(node); const span = getSpanOfTokenAtPosition(sourceFile, block.statements.pos); diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); @@ -22846,8 +22848,8 @@ namespace ts { function isFalseExpression(expr: Expression): boolean { const node = skipParentheses(expr); return node.kind === SyntaxKind.FalseKeyword || node.kind === SyntaxKind.BinaryExpression && ( - (node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node).left) || isFalseExpression((node).right)) || - (node).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node).left) && isFalseExpression((node).right)); + (node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node as BinaryExpression).left) || isFalseExpression((node as BinaryExpression).right)) || + (node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node as BinaryExpression).left) && isFalseExpression((node as BinaryExpression).right)); } function isReachableFlowNodeWorker(flow: FlowNode, noCacheCheck: boolean): boolean { @@ -22865,14 +22867,14 @@ namespace ts { noCacheCheck = false; } if (flags & (FlowFlags.Assignment | FlowFlags.Condition | FlowFlags.ArrayMutation)) { - flow = (flow).antecedent; + flow = (flow as FlowAssignment | FlowCondition | FlowArrayMutation).antecedent; } else if (flags & FlowFlags.Call) { - const signature = getEffectsSignature((flow).node); + const signature = getEffectsSignature((flow as FlowCall).node); if (signature) { const predicate = getTypePredicateOfSignature(signature); if (predicate && predicate.kind === TypePredicateKind.AssertsIdentifier && !predicate.type) { - const predicateArgument = (flow).node.arguments[predicate.parameterIndex]; + const predicateArgument = (flow as FlowCall).node.arguments[predicate.parameterIndex]; if (predicateArgument && isFalseExpression(predicateArgument)) { return false; } @@ -22881,14 +22883,14 @@ namespace ts { return false; } } - flow = (flow).antecedent; + flow = (flow as FlowCall).antecedent; } else if (flags & FlowFlags.BranchLabel) { // A branching point is reachable if any branch is reachable. - return some((flow).antecedents, f => isReachableFlowNodeWorker(f, /*noCacheCheck*/ false)); + return some((flow as FlowLabel).antecedents, f => isReachableFlowNodeWorker(f, /*noCacheCheck*/ false)); } else if (flags & FlowFlags.LoopLabel) { - const antecedents = (flow).antecedents; + const antecedents = (flow as FlowLabel).antecedents; if (antecedents === undefined || antecedents.length === 0) { return false; } @@ -22898,18 +22900,18 @@ namespace ts { else if (flags & FlowFlags.SwitchClause) { // The control flow path representing an unmatched value in a switch statement with // no default clause is unreachable if the switch statement is exhaustive. - if ((flow).clauseStart === (flow).clauseEnd && isExhaustiveSwitchStatement((flow).switchStatement)) { + if ((flow as FlowSwitchClause).clauseStart === (flow as FlowSwitchClause).clauseEnd && isExhaustiveSwitchStatement((flow as FlowSwitchClause).switchStatement)) { return false; } - flow = (flow).antecedent; + flow = (flow as FlowSwitchClause).antecedent; } else if (flags & FlowFlags.ReduceLabel) { // Cache is unreliable once we start adjusting labels lastFlowNode = undefined; - const target = (flow).target; + const target = (flow as FlowReduceLabel).target; const saveAntecedents = target.antecedents; - target.antecedents = (flow).antecedents; - const result = isReachableFlowNodeWorker((flow).antecedent, /*noCacheCheck*/ false); + target.antecedents = (flow as FlowReduceLabel).antecedents; + const result = isReachableFlowNodeWorker((flow as FlowReduceLabel).antecedent, /*noCacheCheck*/ false); target.antecedents = saveAntecedents; return result; } @@ -22933,27 +22935,27 @@ namespace ts { noCacheCheck = false; } if (flags & (FlowFlags.Assignment | FlowFlags.Condition | FlowFlags.ArrayMutation | FlowFlags.SwitchClause)) { - flow = (flow).antecedent; + flow = (flow as FlowAssignment | FlowCondition | FlowArrayMutation | FlowSwitchClause).antecedent; } else if (flags & FlowFlags.Call) { - if ((flow).node.expression.kind === SyntaxKind.SuperKeyword) { + if ((flow as FlowCall).node.expression.kind === SyntaxKind.SuperKeyword) { return true; } - flow = (flow).antecedent; + flow = (flow as FlowCall).antecedent; } else if (flags & FlowFlags.BranchLabel) { // A branching point is post-super if every branch is post-super. - return every((flow).antecedents, f => isPostSuperFlowNode(f, /*noCacheCheck*/ false)); + return every((flow as FlowLabel).antecedents, f => isPostSuperFlowNode(f, /*noCacheCheck*/ false)); } else if (flags & FlowFlags.LoopLabel) { // A loop is post-super if the control flow path that leads to the top is post-super. - flow = (flow).antecedents![0]; + flow = (flow as FlowLabel).antecedents![0]; } else if (flags & FlowFlags.ReduceLabel) { - const target = (flow).target; + const target = (flow as FlowReduceLabel).target; const saveAntecedents = target.antecedents; - target.antecedents = (flow).antecedents; - const result = isPostSuperFlowNode((flow).antecedent, /*noCacheCheck*/ false); + target.antecedents = (flow as FlowReduceLabel).antecedents; + const result = isPostSuperFlowNode((flow as FlowReduceLabel).antecedent, /*noCacheCheck*/ false); target.antecedents = saveAntecedents; return result; } @@ -23023,51 +23025,51 @@ namespace ts { } let type: FlowType | undefined; if (flags & FlowFlags.Assignment) { - type = getTypeAtFlowAssignment(flow); + type = getTypeAtFlowAssignment(flow as FlowAssignment); if (!type) { - flow = (flow).antecedent; + flow = (flow as FlowAssignment).antecedent; continue; } } else if (flags & FlowFlags.Call) { - type = getTypeAtFlowCall(flow); + type = getTypeAtFlowCall(flow as FlowCall); if (!type) { - flow = (flow).antecedent; + flow = (flow as FlowCall).antecedent; continue; } } else if (flags & FlowFlags.Condition) { - type = getTypeAtFlowCondition(flow); + type = getTypeAtFlowCondition(flow as FlowCondition); } else if (flags & FlowFlags.SwitchClause) { - type = getTypeAtSwitchClause(flow); + type = getTypeAtSwitchClause(flow as FlowSwitchClause); } else if (flags & FlowFlags.Label) { - if ((flow).antecedents!.length === 1) { - flow = (flow).antecedents![0]; + if ((flow as FlowLabel).antecedents!.length === 1) { + flow = (flow as FlowLabel).antecedents![0]; continue; } type = flags & FlowFlags.BranchLabel ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); + getTypeAtFlowBranchLabel(flow as FlowLabel) : + getTypeAtFlowLoopLabel(flow as FlowLabel); } else if (flags & FlowFlags.ArrayMutation) { - type = getTypeAtFlowArrayMutation(flow); + type = getTypeAtFlowArrayMutation(flow as FlowArrayMutation); if (!type) { - flow = (flow).antecedent; + flow = (flow as FlowArrayMutation).antecedent; continue; } } else if (flags & FlowFlags.ReduceLabel) { - const target = (flow).target; + const target = (flow as FlowReduceLabel).target; const saveAntecedents = target.antecedents; - target.antecedents = (flow).antecedents; - type = getTypeAtFlowNode((flow).antecedent); + target.antecedents = (flow as FlowReduceLabel).antecedents; + type = getTypeAtFlowNode((flow as FlowReduceLabel).antecedent); target.antecedents = saveAntecedents; } else if (flags & FlowFlags.Start) { // Check if we should continue with the control flow of the containing function. - const container = (flow).node; + const container = (flow as FlowStart).node; if (container && container !== flowContainer && reference.kind !== SyntaxKind.PropertyAccessExpression && reference.kind !== SyntaxKind.ElementAccessExpression && @@ -23097,7 +23099,7 @@ namespace ts { function getInitialOrAssignedType(flow: FlowAssignment) { const node = flow.node; return getNarrowableTypeForReference(node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? - getInitialType(node) : + getInitialType(node as VariableDeclaration | BindingElement) : getAssignedType(node), reference); } @@ -23121,7 +23123,7 @@ namespace ts { return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & TypeFlags.Union) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow)); + return getAssignmentReducedType(declaredType as UnionType, getInitialOrAssignedType(flow)); } return declaredType; } @@ -23157,11 +23159,11 @@ namespace ts { return unreachableNeverType; } if (node.kind === SyntaxKind.BinaryExpression) { - if ((node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { - return narrowTypeByAssertion(narrowTypeByAssertion(type, (node).left), (node).right); + if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { + return narrowTypeByAssertion(narrowTypeByAssertion(type, (node as BinaryExpression).left), (node as BinaryExpression).right); } - if ((node).operatorToken.kind === SyntaxKind.BarBarToken) { - return getUnionType([narrowTypeByAssertion(type, (node).left), narrowTypeByAssertion(type, (node).right)]); + if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken) { + return getUnionType([narrowTypeByAssertion(type, (node as BinaryExpression).left), narrowTypeByAssertion(type, (node as BinaryExpression).right)]); } } return narrowType(type, node, /*assumeTrue*/ true); @@ -23190,13 +23192,13 @@ namespace ts { if (declaredType === autoType || declaredType === autoArrayType) { const node = flow.node; const expr = node.kind === SyntaxKind.CallExpression ? - (node.expression).expression : - (node.left).expression; + (node.expression as PropertyAccessExpression).expression : + (node.left as ElementAccessExpression).expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { const flowType = getTypeAtFlowNode(flow.antecedent); const type = getTypeFromFlowType(flowType); if (getObjectFlags(type) & ObjectFlags.EvolvingArray) { - let evolvedType = type; + let evolvedType = type as EvolvingArrayType; if (node.kind === SyntaxKind.CallExpression) { for (const arg of node.arguments) { evolvedType = addEvolvingArrayElementType(evolvedType, arg); @@ -23204,7 +23206,7 @@ namespace ts { } else { // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) - const indexType = getContextFreeTypeOfExpression((node.left).argumentExpression); + const indexType = getContextFreeTypeOfExpression((node.left as ElementAccessExpression).argumentExpression); if (isTypeAssignableToKind(indexType, TypeFlags.NumberLike)) { evolvedType = addEvolvingArrayElementType(evolvedType, node.right); } @@ -23257,7 +23259,7 @@ namespace ts { } else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference((expr as TypeOfExpression).expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, - t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t).value === "undefined")); + t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t as StringLiteralType).value === "undefined")); } } if (isMatchingReferenceDiscriminant(expr, type)) { @@ -23273,9 +23275,9 @@ namespace ts { let seenIncomplete = false; let bypassFlow: FlowSwitchClause | undefined; for (const antecedent of flow.antecedents!) { - if (!bypassFlow && antecedent.flags & FlowFlags.SwitchClause && (antecedent).clauseStart === (antecedent).clauseEnd) { + if (!bypassFlow && antecedent.flags & FlowFlags.SwitchClause && (antecedent as FlowSwitchClause).clauseStart === (antecedent as FlowSwitchClause).clauseEnd) { // The antecedent is the bypass branch of a potentially exhaustive switch statement. - bypassFlow = antecedent; + bypassFlow = antecedent as FlowSwitchClause; continue; } const flowType = getTypeAtFlowNode(antecedent); @@ -23412,7 +23414,7 @@ namespace ts { return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))); } const result = getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - if (result !== declaredType && result.flags & declaredType.flags & TypeFlags.Union && arraysEqual((result).types, (declaredType).types)) { + if (result !== declaredType && result.flags & declaredType.flags & TypeFlags.Union && arraysEqual((result as UnionType).types, (declaredType as UnionType).types)) { return declaredType; } return result; @@ -23450,9 +23452,9 @@ namespace ts { function narrowTypeByDiscriminantProperty(type: Type, access: AccessExpression, operator: SyntaxKind, value: Expression, assumeTrue: boolean) { if ((operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) && type.flags & TypeFlags.Union) { - const keyPropertyName = getKeyPropertyName(type); + const keyPropertyName = getKeyPropertyName(type as UnionType); if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { - const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + const candidate = getConstituentTypeForKeyType(type as UnionType, getTypeOfExpression(value)); if (candidate) { return operator === (assumeTrue ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? filterType(type, t => t !== candidate) : @@ -23464,9 +23466,9 @@ namespace ts { } function narrowTypeBySwitchOnDiscriminantProperty(type: Type, access: AccessExpression, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number) { - if (clauseStart < clauseEnd && type.flags & TypeFlags.Union && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + if (clauseStart < clauseEnd && type.flags & TypeFlags.Union && getKeyPropertyName(type as UnionType) === getAccessedPropertyName(access)) { const clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); - const candidate = getUnionType(map(clauseTypes, t => getConstituentTypeForKeyType(type, t) || unknownType)); + const candidate = getUnionType(map(clauseTypes, t => getConstituentTypeForKeyType(type as UnionType, t) || unknownType)); if (candidate !== unknownType) { return candidate; } @@ -23482,7 +23484,7 @@ namespace ts { type = getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); } if (isMatchingReferenceDiscriminant(expr, type)) { - return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); + return narrowTypeByDiscriminant(type, expr as AccessExpression, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); } return type; } @@ -23524,10 +23526,10 @@ namespace ts { const left = getReferenceCandidate(expr.left); const right = getReferenceCandidate(expr.right); if (left.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(right)) { - return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + return narrowTypeByTypeof(type, left as TypeOfExpression, operator, right, assumeTrue); } if (right.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(left)) { - return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + return narrowTypeByTypeof(type, right as TypeOfExpression, operator, left, assumeTrue); } if (isMatchingReference(reference, left)) { return narrowTypeByEquality(type, operator, right, assumeTrue); @@ -23544,10 +23546,10 @@ namespace ts { } } if (isMatchingReferenceDiscriminant(left, type)) { - return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); + return narrowTypeByDiscriminantProperty(type, left as AccessExpression, operator, right, assumeTrue); } if (isMatchingReferenceDiscriminant(right, type)) { - return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); + return narrowTypeByDiscriminantProperty(type, right as AccessExpression, operator, left, assumeTrue); } if (isMatchingConstructorReference(left)) { return narrowTypeByConstructor(type, operator, right, assumeTrue); @@ -23649,7 +23651,7 @@ namespace ts { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. if (typeOfExpr.parent.parent.kind === SyntaxKind.BinaryExpression) { - const expr = typeOfExpr.parent.parent; + const expr = typeOfExpr.parent.parent as BinaryExpression; if (expr.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; } @@ -23760,7 +23762,7 @@ namespace ts { // We no longer need the undefined denoting an explicit default case. Remove the undefined and // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the // witness array. - const witnesses = switchWitnesses.filter(witness => witness !== undefined); + const witnesses = switchWitnesses.filter(witness => witness !== undefined) as string[]; // The adjusted clause start and end after removing the `default` statement. const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; const fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; @@ -23768,8 +23770,8 @@ namespace ts { switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); } else { - clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); - switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd) as string[]; + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses as string[], hasDefaultClause); } if (hasDefaultClause) { return filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts); @@ -23899,7 +23901,7 @@ namespace ts { // We can't narrow a union based off instanceof without negated types see #31576 for more info if (!assumeTrue && rightType.flags & TypeFlags.Union) { - const nonConstructorTypeInUnion = find((rightType).types, (t) => !isConstructorType(t)); + const nonConstructorTypeInUnion = find((rightType as UnionType).types, (t) => !isConstructorType(t)); if (!nonConstructorTypeInUnion) return type; } @@ -23986,15 +23988,15 @@ namespace ts { case SyntaxKind.ElementAccessExpression: return narrowTypeByTruthiness(type, expr, assumeTrue); case SyntaxKind.CallExpression: - return narrowTypeByCallExpression(type, expr, assumeTrue); + return narrowTypeByCallExpression(type, expr as CallExpression, assumeTrue); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return narrowType(type, (expr).expression, assumeTrue); + return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression).expression, assumeTrue); case SyntaxKind.BinaryExpression: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); + return narrowTypeByBinaryExpression(type, expr as BinaryExpression, assumeTrue); case SyntaxKind.PrefixUnaryExpression: - if ((expr).operator === SyntaxKind.ExclamationToken) { - return narrowType(type, (expr).operand, !assumeTrue); + if ((expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) { + return narrowType(type, (expr as PrefixUnaryExpression).operand, !assumeTrue); } break; } @@ -24006,7 +24008,7 @@ namespace ts { return getTypeWithFacts(type, assumePresent ? TypeFacts.NEUndefinedOrNull : TypeFacts.EQUndefinedOrNull); } if (isMatchingReferenceDiscriminant(expr, type)) { - return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumePresent ? TypeFacts.NEUndefinedOrNull : TypeFacts.EQUndefinedOrNull)); + return narrowTypeByDiscriminant(type, expr as AccessExpression, t => getTypeWithFacts(t, assumePresent ? TypeFacts.NEUndefinedOrNull : TypeFacts.EQUndefinedOrNull)); } return type; } @@ -24024,7 +24026,7 @@ namespace ts { location = location.parent; } if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { - const type = getTypeOfExpression(location); + const type = getTypeOfExpression(location as Expression); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -24054,7 +24056,7 @@ namespace ts { if (!symbol.valueDeclaration) { return false; } - const func = getRootDeclaration(symbol.valueDeclaration).parent; + const func = getRootDeclaration(symbol.valueDeclaration).parent as FunctionLikeDeclaration; const links = getNodeLinks(func); if (!(links.flags & NodeCheckFlags.AssignmentsMarked)) { links.flags |= NodeCheckFlags.AssignmentsMarked; @@ -24072,7 +24074,7 @@ namespace ts { function markParameterAssignments(node: Node) { if (node.kind === SyntaxKind.Identifier) { if (isAssignmentTarget(node)) { - const symbol = getResolvedSymbol(node); + const symbol = getResolvedSymbol(node as Identifier); if (symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration).kind === SyntaxKind.Parameter) { symbol.isAssigned = true; } @@ -24111,9 +24113,9 @@ namespace ts { // of a generic type. This is because when both obj and x are of generic types T and K, we want // the resulting type to be T[K]. return parent.kind === SyntaxKind.PropertyAccessExpression || - parent.kind === SyntaxKind.CallExpression && (parent).expression === node || - parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node && - !isGenericIndexType(getTypeOfExpression((parent).argumentExpression)); + parent.kind === SyntaxKind.CallExpression && (parent as CallExpression).expression === node || + parent.kind === SyntaxKind.ElementAccessExpression && (parent as ElementAccessExpression).expression === node && + !isGenericIndexType(getTypeOfExpression((parent as ElementAccessExpression).argumentExpression)); } function isGenericTypeWithUnionConstraint(type: Type) { @@ -24121,7 +24123,7 @@ namespace ts { } function containsGenericType(type: Type): boolean { - return !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.UnionOrIntersection && some((type).types, containsGenericType)); + return !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.UnionOrIntersection && some((type as UnionOrIntersectionType).types, containsGenericType)); } function hasNonBindingPatternContextualTypeWithNoGenericTypes(node: Node) { @@ -24322,7 +24324,7 @@ namespace ts { type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || - declaration.kind === SyntaxKind.VariableDeclaration && (declaration).exclamationToken || + declaration.kind === SyntaxKind.VariableDeclaration && (declaration as VariableDeclaration).exclamationToken || declaration.flags & NodeFlags.Ambient; const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -24442,7 +24444,7 @@ namespace ts { isAssigned = true; } else if ((current.parent.kind === SyntaxKind.PrefixUnaryExpression || current.parent.kind === SyntaxKind.PostfixUnaryExpression)) { - const expr = current.parent; + const expr = current.parent as PrefixUnaryExpression | PostfixUnaryExpression; isAssigned = expr.operator === SyntaxKind.PlusPlusToken || expr.operator === SyntaxKind.MinusMinusToken; } @@ -24479,14 +24481,14 @@ namespace ts { */ function classDeclarationExtendsNull(classDecl: ClassDeclaration): boolean { const classSymbol = getSymbolOfNode(classDecl); - const classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + const classInstanceType = getDeclaredTypeOfSymbol(classSymbol) as InterfaceType; const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } function checkThisBeforeSuper(node: Node, container: Node, diagnosticMessage: DiagnosticMessage) { - const containingClassDecl = container.parent; + const containingClassDecl = container.parent as ClassDeclaration; const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null @@ -24684,7 +24686,7 @@ namespace ts { function getTypeForThisExpressionFromJSDoc(node: Node) { const jsdocType = getJSDocType(node); if (jsdocType && jsdocType.kind === SyntaxKind.JSDocFunctionType) { - const jsDocFunctionType = jsdocType; + const jsDocFunctionType = jsdocType as JSDocFunctionType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && (jsDocFunctionType.parameters[0].name as Identifier).escapedText === InternalSymbolName.This) { @@ -24702,7 +24704,7 @@ namespace ts { } function checkSuperExpression(node: Node): Type { - const isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; + const isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent as CallExpression).expression === node; const immediateContainer = getSuperContainer(node, /*stopOnFunctions*/ true); let container = immediateContainer; @@ -24841,13 +24843,13 @@ namespace ts { } // at this point the only legal case for parent is ClassLikeDeclaration - const classLikeDeclaration = container.parent; + const classLikeDeclaration = container.parent as ClassLikeDeclaration; if (!getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } - const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)) as InterfaceType; const baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { return errorType; @@ -24907,17 +24909,17 @@ namespace ts { return (func.kind === SyntaxKind.MethodDeclaration || func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : - func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent : + func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent as ObjectLiteralExpression : undefined; } function getThisTypeArgument(type: Type): Type | undefined { - return getObjectFlags(type) & ObjectFlags.Reference && (type).target === globalThisType ? getTypeArguments(type)[0] : undefined; + return getObjectFlags(type) & ObjectFlags.Reference && (type as TypeReference).target === globalThisType ? getTypeArguments(type as TypeReference)[0] : undefined; } function getThisTypeFromContextualType(type: Type): Type | undefined { return mapType(type, t => { - return t.flags & TypeFlags.Intersection ? forEach((t).types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & TypeFlags.Intersection ? forEach((t as IntersectionType).types, getThisTypeArgument) : getThisTypeArgument(t); }); } @@ -24952,7 +24954,7 @@ namespace ts { if (literal.parent.kind !== SyntaxKind.PropertyAssignment) { break; } - literal = literal.parent.parent; + literal = literal.parent.parent as ObjectLiteralExpression; type = getApparentTypeOfContextualType(literal); } // There was no contextual ThisType for the containing object literal, so the contextual type @@ -24963,8 +24965,8 @@ namespace ts { // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. const parent = walkUpParenthesizedExpressions(func.parent); - if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken) { - const target = (parent).left; + if (parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + const target = (parent as BinaryExpression).left; if (isAccessExpression(target)) { const { expression } = target; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` @@ -25064,7 +25066,7 @@ namespace ts { // Otherwise, in a binding pattern inside a variable or parameter declaration, // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node: Expression, contextFlags?: ContextFlags): Type | undefined { - const declaration = node.parent; + const declaration = node.parent as VariableLikeDeclaration; if (hasInitializer(declaration) && node === declaration.initializer) { const result = getContextualTypeForVariableLikeDeclaration(declaration); if (result) { @@ -25164,7 +25166,7 @@ namespace ts { } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl as FunctionExpression); if (signature && !isResolvingReturnTypeOfSignature(signature)) { return getReturnTypeOfSignature(signature); } @@ -25186,19 +25188,22 @@ namespace ts { if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } - return getTypeAtPosition(signature, argIndex); + const restIndex = signature.parameters.length - 1; + return signatureHasRestParameter(signature) && argIndex >= restIndex ? + getIndexedAccessType(getTypeOfSymbol(signature.parameters[restIndex]), getLiteralType(argIndex - restIndex), AccessFlags.Contextual) : + getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template: TemplateExpression, substitutionExpression: Expression) { if (template.parent.kind === SyntaxKind.TaggedTemplateExpression) { - return getContextualTypeForArgument(template.parent, substitutionExpression); + return getContextualTypeForArgument(template.parent as TaggedTemplateExpression, substitutionExpression); } return undefined; } function getContextualTypeForBinaryOperand(node: Expression, contextFlags?: ContextFlags): Type | undefined { - const binaryExpression = node.parent; + const binaryExpression = node.parent as BinaryExpression; const { left, operatorToken, right } = binaryExpression; switch (operatorToken.kind) { case SyntaxKind.EqualsToken: @@ -25320,7 +25325,7 @@ namespace ts { } function isCircularMappedProperty(symbol: Symbol) { - return !!(getCheckFlags(symbol) & CheckFlags.Mapped && !(symbol).type && findResolutionCycleStartIndex(symbol, TypeSystemPropertyName.Type) >= 0); + return !!(getCheckFlags(symbol) & CheckFlags.Mapped && !(symbol as MappedSymbol).type && findResolutionCycleStartIndex(symbol, TypeSystemPropertyName.Type) >= 0); } function getTypeOfPropertyOfContextualType(type: Type, name: __String) { @@ -25368,7 +25373,7 @@ namespace ts { } function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike, contextFlags?: ContextFlags) { - const objectLiteral = element.parent; + const objectLiteral = element.parent as ObjectLiteralExpression; const propertyAssignmentType = isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); if (propertyAssignmentType) { return propertyAssignmentType; @@ -25406,7 +25411,7 @@ namespace ts { // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node: Expression, contextFlags?: ContextFlags): Type | undefined { - const conditional = node.parent; + const conditional = node.parent as ConditionalExpression; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined; } @@ -25472,7 +25477,7 @@ namespace ts { return true; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ParenthesizedExpression: - return isPossiblyDiscriminantValue((node).expression); + return isPossiblyDiscriminantValue((node as PropertyAccessExpression | ParenthesizedExpression).expression); case SyntaxKind.JsxExpression: return !(node as JsxExpression).expression || isPossiblyDiscriminantValue((node as JsxExpression).expression!); } @@ -25559,10 +25564,10 @@ namespace ts { return instantiateType(type, mapper); } if (type.flags & TypeFlags.Union) { - return getUnionType(map((type).types, t => instantiateInstantiableTypes(t, mapper)), UnionReduction.None); + return getUnionType(map((type as UnionType).types, t => instantiateInstantiableTypes(t, mapper)), UnionReduction.None); } if (type.flags & TypeFlags.Intersection) { - return getIntersectionType(map((type).types, t => instantiateInstantiableTypes(t, mapper))); + return getIntersectionType(map((type as IntersectionType).types, t => instantiateInstantiableTypes(t, mapper))); } return type; } @@ -25604,28 +25609,28 @@ namespace ts { case SyntaxKind.ReturnStatement: return getContextualTypeForReturnExpression(node); case SyntaxKind.YieldExpression: - return getContextualTypeForYieldOperand(parent); + return getContextualTypeForYieldOperand(parent as YieldExpression); case SyntaxKind.AwaitExpression: - return getContextualTypeForAwaitOperand(parent, contextFlags); + return getContextualTypeForAwaitOperand(parent as AwaitExpression, contextFlags); case SyntaxKind.CallExpression: - if ((parent).expression.kind === SyntaxKind.ImportKeyword) { + if ((parent as CallExpression).expression.kind === SyntaxKind.ImportKeyword) { return stringType; } /* falls through */ case SyntaxKind.NewExpression: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent as CallExpression | NewExpression, node); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: - return isConstTypeReference((parent).type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode((parent).type); + return isConstTypeReference((parent as AssertionExpression).type) ? tryFindWhenConstTypeReference(parent as AssertionExpression) : getTypeFromTypeNode((parent as AssertionExpression).type); case SyntaxKind.BinaryExpression: return getContextualTypeForBinaryOperand(node, contextFlags); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - return getContextualTypeForObjectLiteralElement(parent, contextFlags); + return getContextualTypeForObjectLiteralElement(parent as PropertyAssignment | ShorthandPropertyAssignment, contextFlags); case SyntaxKind.SpreadAssignment: return getContextualType(parent.parent as ObjectLiteralExpression, contextFlags); case SyntaxKind.ArrayLiteralExpression: { - const arrayLiteral = parent; + const arrayLiteral = parent as ArrayLiteralExpression; const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, indexOfNode(arrayLiteral.elements, node)); } @@ -25633,22 +25638,22 @@ namespace ts { return getContextualTypeForConditionalOperand(node, contextFlags); case SyntaxKind.TemplateSpan: Debug.assert(parent.parent.kind === SyntaxKind.TemplateExpression); - return getContextualTypeForSubstitutionExpression(parent.parent, node); + return getContextualTypeForSubstitutionExpression(parent.parent as TemplateExpression, node); case SyntaxKind.ParenthesizedExpression: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. const tag = isInJSFile(parent) ? getJSDocTypeTag(parent) : undefined; - return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent as ParenthesizedExpression, contextFlags); } case SyntaxKind.NonNullExpression: return getContextualType(parent as NonNullExpression, contextFlags); case SyntaxKind.JsxExpression: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxExpression(parent as JsxExpression); case SyntaxKind.JsxAttribute: case SyntaxKind.JsxSpreadAttribute: - return getContextualTypeForJsxAttribute(parent); + return getContextualTypeForJsxAttribute(parent as JsxAttribute | JsxSpreadAttribute); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - return getContextualJsxElementAttributesType(parent, contextFlags); + return getContextualJsxElementAttributesType(parent as JsxOpeningLikeElement, contextFlags); } return undefined; @@ -25786,7 +25791,7 @@ namespace ts { const hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes( typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context))) + ? createTypeReference(intrinsicClassAttribs as GenericType, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType ); @@ -25928,7 +25933,7 @@ namespace ts { function getContextualSignatureForFunctionLikeDeclaration(node: FunctionLikeDeclaration): Signature | undefined { // Only function expressions, arrow functions, and object literal methods are contextually typed. return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) - ? getContextualSignature(node) + ? getContextualSignature(node as FunctionExpression) : undefined; } @@ -25951,7 +25956,7 @@ namespace ts { return getContextualCallSignature(type, node); } let signatureList: Signature[] | undefined; - const types = (type).types; + const types = (type as UnionType).types; for (const current of types) { const signature = getContextualCallSignature(current, node); if (signature) { @@ -25989,8 +25994,8 @@ namespace ts { } function hasDefaultValue(node: BindingElement | Expression): boolean { - return (node.kind === SyntaxKind.BindingElement && !!(node).initializer) || - (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.EqualsToken); + return (node.kind === SyntaxKind.BindingElement && !!(node as BindingElement).initializer) || + (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken); } function checkArrayLiteral(node: ArrayLiteralExpression, checkMode: CheckMode | undefined, forceTuple: boolean | undefined): Type { @@ -26007,7 +26012,7 @@ namespace ts { if (languageVersion < ScriptTarget.ES2015) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? ExternalEmitHelpers.SpreadIncludes : ExternalEmitHelpers.SpreadArray); } - const spreadType = checkExpression((e).expression, checkMode, forceTuple); + const spreadType = checkExpression((e as SpreadElement).expression, checkMode, forceTuple); if (isArrayLikeType(spreadType)) { elementTypes.push(spreadType); elementFlags.push(ElementFlags.Variadic); @@ -26032,7 +26037,7 @@ namespace ts { elementFlags.push(ElementFlags.Rest); } else { - elementTypes.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, (e).expression)); + elementTypes.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, (e as SpreadElement).expression)); elementFlags.push(ElementFlags.Rest); } } @@ -26058,9 +26063,9 @@ namespace ts { if (!(getObjectFlags(type) & ObjectFlags.Reference)) { return type; } - let literalType = (type).literalType; + let literalType = (type as TypeReference).literalType; if (!literalType) { - literalType = (type).literalType = cloneTypeReference(type); + literalType = (type as TypeReference).literalType = cloneTypeReference(type as TypeReference); literalType.objectFlags |= ObjectFlags.ArrayLiteral | ObjectFlags.ContainsObjectOrArrayLiteral; } return literalType; @@ -26338,7 +26343,7 @@ namespace ts { for (const prop of getPropertiesOfType(contextualType!)) { if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { if (!(prop.flags & SymbolFlags.Optional)) { - error(prop.valueDeclaration || (prop).bindingElement, + error(prop.valueDeclaration || (prop as TransientSymbol).bindingElement, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.escapedName, prop); @@ -26392,7 +26397,7 @@ namespace ts { } return !!(type.flags & (TypeFlags.Any | TypeFlags.NonPrimitive | TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) || getFalsyFlags(type) & TypeFlags.DefinitelyFalsy && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & TypeFlags.UnionOrIntersection && every((type).types, isValidSpreadType)); + type.flags & TypeFlags.UnionOrIntersection && every((type as UnionOrIntersectionType).types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node: JsxSelfClosingElement) { @@ -26924,7 +26929,7 @@ namespace ts { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { - checkGrammarJsxElement(node); + checkGrammarJsxElement(node as JsxOpeningLikeElement); } checkJsxPreconditions(node); @@ -26934,7 +26939,7 @@ namespace ts { // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === JsxEmit.React ? Diagnostics.Cannot_find_name_0 : undefined; const jsxFactoryNamespace = getJsxNamespace(node); - const jsxFactoryLocation = isNodeOpeningLikeElement ? (node).tagName : node; + const jsxFactoryLocation = isNodeOpeningLikeElement ? (node as JsxOpeningLikeElement).tagName : node; // allow null as jsxFragmentFactory let jsxFactorySym: Symbol | undefined; @@ -26957,7 +26962,7 @@ namespace ts { if (isNodeOpeningLikeElement) { const jsxOpeningLikeNode = node as JsxOpeningLikeElement; const sig = getResolvedSignature(jsxOpeningLikeNode); - checkDeprecatedSignature(sig, node); + checkDeprecatedSignature(sig, node as JsxOpeningLikeElement); checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } @@ -26999,8 +27004,8 @@ namespace ts { function isExcessPropertyCheckTarget(type: Type): boolean { return !!(type.flags & TypeFlags.Object && !(getObjectFlags(type) & ObjectFlags.ObjectLiteralPatternWithComputedProperties) || type.flags & TypeFlags.NonPrimitive || - type.flags & TypeFlags.Union && some((type).types, isExcessPropertyCheckTarget) || - type.flags & TypeFlags.Intersection && every((type).types, isExcessPropertyCheckTarget)); + type.flags & TypeFlags.Union && some((type as UnionType).types, isExcessPropertyCheckTarget) || + type.flags & TypeFlags.Intersection && every((type as IntersectionType).types, isExcessPropertyCheckTarget)); } function checkJsxExpression(node: JsxExpression, checkMode?: CheckMode) { @@ -27122,7 +27127,7 @@ namespace ts { // Find the first enclosing class that has the declaring classes of the protected constituents // of the property as base classes let enclosingClass = forEachEnclosingClass(node, enclosingDeclaration => { - const enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)!); + const enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)!) as InterfaceType; return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it @@ -27138,7 +27143,7 @@ namespace ts { } const thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = (((thisType.flags & TypeFlags.TypeParameter) ? getConstraintOfTypeParameter(thisType) : thisType) as TypeReference).target; + enclosingClass = (((thisType.flags & TypeFlags.TypeParameter) ? getConstraintOfTypeParameter(thisType as TypeParameter) : thisType) as TypeReference).target; } // No further restrictions for static properties if (flags & ModifierFlags.Static) { @@ -27146,7 +27151,7 @@ namespace ts { } if (type.flags & TypeFlags.TypeParameter) { // get the original type -- represented as the type constraint of the 'this' type - type = (type as TypeParameter).isThisType ? getConstraintOfTypeParameter(type)! : getBaseConstraintOfType(type)!; // TODO: GH#18217 Use a different variable that's allowed to be undefined + type = (type as TypeParameter).isThisType ? getConstraintOfTypeParameter(type as TypeParameter)! : getBaseConstraintOfType(type as TypeParameter)!; // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { if (reportError) { @@ -27736,7 +27741,7 @@ namespace ts { function getSuggestionForNonexistentIndexSignature(objectType: Type, expr: ElementAccessExpression, keyedType: Type): string | undefined { // check if object type has setter or getter function hasProp(name: "set" | "get") { - const prop = getPropertyOfObjectType(objectType, <__String>name); + const prop = getPropertyOfObjectType(objectType, name as __String); if (prop) { const s = getSingleCallSignature(getTypeOfSymbol(prop)); return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0)); @@ -27862,7 +27867,7 @@ namespace ts { return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion - return isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); + return isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type as UnionType).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); } /** @@ -27871,13 +27876,13 @@ namespace ts { function getForInVariableSymbol(node: ForInStatement): Symbol | undefined { const initializer = node.initializer; if (initializer.kind === SyntaxKind.VariableDeclarationList) { - const variable = (initializer).declarations[0]; + const variable = (initializer as VariableDeclarationList).declarations[0]; if (variable && !isBindingPattern(variable.name)) { return getSymbolOfNode(variable); } } else if (initializer.kind === SyntaxKind.Identifier) { - return getResolvedSymbol(initializer); + return getResolvedSymbol(initializer as Identifier); } return undefined; } @@ -27896,15 +27901,15 @@ namespace ts { function isForInVariableForNumericPropertyNames(expr: Expression) { const e = skipParentheses(expr); if (e.kind === SyntaxKind.Identifier) { - const symbol = getResolvedSymbol(e); + const symbol = getResolvedSymbol(e as Identifier); if (symbol.flags & SymbolFlags.Variable) { let child: Node = expr; let node = expr.parent; while (node) { if (node.kind === SyntaxKind.ForInStatement && - child === (node).statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression((node).expression))) { + child === (node as ForInStatement).statement && + getForInVariableSymbol(node as ForInStatement) === symbol && + hasNumericPropertyNames(getTypeOfExpression((node as ForInStatement).expression))) { return true; } child = node; @@ -27943,8 +27948,8 @@ namespace ts { const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType; const accessFlags = isAssignmentTarget(node) ? AccessFlags.Writing | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? AccessFlags.NoIndexSignatures : 0) : - AccessFlags.None; - const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | AccessFlags.ExpressionPosition) || errorType; + AccessFlags.ExpressionPosition; + const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType; return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } @@ -27966,7 +27971,7 @@ namespace ts { checkExpression(node.attributes); } else if (node.kind !== SyntaxKind.Decorator) { - forEach((node).arguments, argument => { + forEach((node as CallExpression).arguments, argument => { checkExpression(argument); }); } @@ -28033,7 +28038,7 @@ namespace ts { } function isSpreadArgument(arg: Expression | undefined): arg is Expression { - return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && (arg).isSpread); + return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && (arg as SyntheticExpression).isSpread); } function getSpreadArgumentIndex(args: readonly Expression[]): number { @@ -28066,7 +28071,7 @@ namespace ts { // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. - const templateLiteral = node.template; + const templateLiteral = node.template as LiteralExpression; Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral); callIsIncomplete = !!templateLiteral.isUnterminated; } @@ -28141,7 +28146,7 @@ namespace ts { function getSingleSignature(type: Type, kind: SignatureKind, allowMembers: boolean): Signature | undefined { if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type as ObjectType); if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (kind === SignatureKind.Call && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) { return resolved.callSignatures[0]; @@ -28280,8 +28285,8 @@ namespace ts { if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - return getMutableArrayOrTupleType(arg.kind === SyntaxKind.SyntheticExpression ? (arg).type : - checkExpressionWithContextualType((arg).expression, restType, context, checkMode)); + return getMutableArrayOrTupleType(arg.kind === SyntaxKind.SyntheticExpression ? (arg as SyntheticExpression).type : + checkExpressionWithContextualType((arg as SpreadElement).expression, restType, context, checkMode)); } } const types = []; @@ -28290,18 +28295,18 @@ namespace ts { for (let i = index; i < argCount; i++) { const arg = args[i]; if (isSpreadArgument(arg)) { - const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? (arg).type : checkExpression((arg).expression); + const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? (arg as SyntheticExpression).type : checkExpression((arg as SpreadElement).expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(ElementFlags.Variadic); } else { - types.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? (arg).expression : arg)); + types.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? (arg as SpreadElement).expression : arg)); flags.push(ElementFlags.Rest); } } else { - const contextualType = getIndexedAccessType(restType, getLiteralType(i - index)); + const contextualType = getIndexedAccessType(restType, getLiteralType(i - index), AccessFlags.Contextual); const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode); const hasPrimitiveContextualType = maybeTypeOfKind(contextualType, TypeFlags.Primitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping); types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); @@ -28591,7 +28596,7 @@ namespace ts { for (let i = spreadIndex; i < args.length; i++) { const arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - const spreadType = arg.kind === SyntaxKind.SpreadElement && (flowLoopCount ? checkExpression((arg).expression) : checkExpressionCached((arg).expression)); + const spreadType = arg.kind === SyntaxKind.SpreadElement && (flowLoopCount ? checkExpression((arg as SpreadElement).expression) : checkExpressionCached((arg as SpreadElement).expression)); if (spreadType && isTupleType(spreadType)) { forEach(getTypeArguments(spreadType), (t, i) => { const flags = spreadType.target.elementFlags[i]; @@ -28626,7 +28631,7 @@ namespace ts { case SyntaxKind.Parameter: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts). - const func = parent.parent; + const func = parent.parent as FunctionLikeDeclaration; return [ createSyntheticExpression(expr, parent.parent.kind === SyntaxKind.Constructor ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), @@ -28641,8 +28646,8 @@ namespace ts { // for ES3, we will only pass two arguments. const hasPropDesc = parent.kind !== SyntaxKind.PropertyDeclaration && languageVersion !== ScriptTarget.ES3; return [ - createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), - createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, getParentTypeOfClassElement(parent as ClassElement)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent as ClassElement)), createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) ]; } @@ -28814,10 +28819,10 @@ namespace ts { let typeArguments: NodeArray | undefined; if (!isDecorator) { - typeArguments = (node).typeArguments; + typeArguments = (node as CallExpression).typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || (node).expression.kind !== SyntaxKind.SuperKeyword) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || (node as CallExpression).expression.kind !== SyntaxKind.SuperKeyword) { forEach(typeArguments, checkSourceElement); } } @@ -29478,7 +29483,7 @@ namespace ts { } const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol)!; - const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol) as InterfaceType; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { @@ -30024,18 +30029,18 @@ namespace ts { case SyntaxKind.CallExpression: case SyntaxKind.Decorator: case SyntaxKind.NewExpression: - return getDeprecatedSuggestionNode((node).expression); + return getDeprecatedSuggestionNode((node as Decorator | CallExpression | NewExpression).expression); case SyntaxKind.TaggedTemplateExpression: - return getDeprecatedSuggestionNode((node).tag); + return getDeprecatedSuggestionNode((node as TaggedTemplateExpression).tag); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - return getDeprecatedSuggestionNode((node).tagName); + return getDeprecatedSuggestionNode((node as JsxOpeningLikeElement).tagName); case SyntaxKind.ElementAccessExpression: - return (node).argumentExpression; + return (node as ElementAccessExpression).argumentExpression; case SyntaxKind.PropertyAccessExpression: - return (node).name; + return (node as PropertyAccessExpression).name; case SyntaxKind.TypeReference: - const typeReference = node; + const typeReference = node as TypeReferenceNode; return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: return node; @@ -30173,15 +30178,15 @@ namespace ts { case SyntaxKind.TemplateExpression: return true; case SyntaxKind.ParenthesizedExpression: - return isValidConstAssertionArgument((node).expression); + return isValidConstAssertionArgument((node as ParenthesizedExpression).expression); case SyntaxKind.PrefixUnaryExpression: - const op = (node).operator; - const arg = (node).operand; + const op = (node as PrefixUnaryExpression).operator; + const arg = (node as PrefixUnaryExpression).operand; return op === SyntaxKind.MinusToken && (arg.kind === SyntaxKind.NumericLiteral || arg.kind === SyntaxKind.BigIntLiteral) || op === SyntaxKind.PlusToken && arg.kind === SyntaxKind.NumericLiteral; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - const expr = (node).expression; + const expr = (node as PropertyAccessExpression | ElementAccessExpression).expression; if (isIdentifier(expr)) { let symbol = getSymbolAtLocation(expr); if (symbol && symbol.flags & SymbolFlags.Alias) { @@ -30289,7 +30294,7 @@ namespace ts { const restParameter = signature.parameters[paramCount] || unknownSymbol; const restType = overrideRestType || getTypeOfSymbol(restParameter); if (isTupleType(restType)) { - const associatedNames = ((restType).target).labeledElementDeclarations; + const associatedNames = ((restType as TypeReference).target as TupleType).labeledElementDeclarations; const index = pos - paramCount; return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index as __String; } @@ -30309,7 +30314,7 @@ namespace ts { const restParameter = signature.parameters[paramCount] || unknownSymbol; const restType = getTypeOfSymbol(restParameter); if (isTupleType(restType)) { - const associatedNames = ((restType).target).labeledElementDeclarations; + const associatedNames = ((restType as TypeReference).target as TupleType).labeledElementDeclarations; const index = pos - paramCount; return associatedNames && associatedNames[index]; } @@ -30453,7 +30458,7 @@ namespace ts { function inferFromAnnotatedParameters(signature: Signature, context: Signature, inferenceContext: InferenceContext) { const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (let i = 0; i < len; i++) { - const declaration = signature.parameters[i].valueDeclaration; + const declaration = signature.parameters[i].valueDeclaration as ParameterDeclaration; if (declaration.type) { const typeNode = getEffectiveTypeAnnotationNode(declaration); if (typeNode) { @@ -30485,7 +30490,7 @@ namespace ts { } if (context.thisParameter) { const parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !(parameter.valueDeclaration).type) { + if (!parameter || parameter.valueDeclaration && !(parameter.valueDeclaration as ParameterDeclaration).type) { if (!parameter) { signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); } @@ -30495,7 +30500,7 @@ namespace ts { const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (let i = 0; i < len; i++) { const parameter = signature.parameters[i]; - if (!getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (!getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration)) { const contextualParameterType = tryGetTypeAtPosition(context, i); assignParameterType(parameter, contextualParameterType); } @@ -30503,7 +30508,7 @@ namespace ts { if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. const parameter = last(signature.parameters); - if (isTransientSymbol(parameter) || !getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration)) { const contextualParameterType = getRestTypeAtPosition(context, len); assignParameterType(parameter, contextualParameterType); } @@ -30724,7 +30729,7 @@ namespace ts { const yieldTypes: Type[] = []; const nextTypes: Type[] = []; const isAsync = (getFunctionFlags(func) & FunctionFlags.Async) !== 0; - forEachYieldExpression(func.body, yieldExpression => { + forEachYieldExpression(func.body as Block, yieldExpression => { const yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType; pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync)); let nextType: Type | undefined; @@ -30834,7 +30839,7 @@ namespace ts { const aggregatedTypes: Type[] = []; let hasReturnWithNoExpression = functionHasImplicitReturn(func); let hasReturnOfTypeNever = false; - forEachReturnStatement(func.body, returnStatement => { + forEachReturnStatement(func.body as Block, returnStatement => { const expr = returnStatement.expression; if (expr) { let type = checkExpressionCached(expr, checkMode && checkMode & ~CheckMode.SkipGenericFunctions); @@ -31356,7 +31361,7 @@ namespace ts { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { - const types = (type).types; + const types = (type as UnionOrIntersectionType).types; for (const t of types) { if (maybeTypeOfKind(t, kind)) { return true; @@ -31487,7 +31492,7 @@ namespace ts { checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } - const elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, AccessFlags.ExpressionPosition); + const elementType = getIndexedAccessType(objectLiteralType, exprType, AccessFlags.ExpressionPosition, name); const type = getFlowTypeOfDestructuring(property, elementType); return checkDestructuringAssignment(property.kind === SyntaxKind.ShorthandPropertyAssignment ? property : property.initializer, type); } @@ -31548,7 +31553,7 @@ namespace ts { // We create a synthetic expression so that getIndexedAccessType doesn't get confused // when the element is a SyntaxKind.ElementAccessExpression. const accessFlags = AccessFlags.ExpressionPosition | (hasDefaultValue(element) ? AccessFlags.NoTupleBoundsCheck : 0); - const elementType = getIndexedAccessTypeOrUndefined(sourceType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, createSyntheticExpression(element, indexType), accessFlags) || errorType; + const elementType = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType; const assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType, TypeFacts.NEUndefined) : elementType; const type = getFlowTypeOfDestructuring(element, assignedType); return checkDestructuringAssignment(element, type, checkMode); @@ -31559,14 +31564,14 @@ namespace ts { error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - const restExpression = (element).expression; - if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); + const restExpression = (element as SpreadElement).expression; + if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + error((restExpression as BinaryExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); const type = everyType(sourceType, isTupleType) ? - mapType(sourceType, t => sliceTupleType(t, elementIndex)) : + mapType(sourceType, t => sliceTupleType(t as TupleTypeReference, elementIndex)) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -31578,7 +31583,7 @@ namespace ts { function checkDestructuringAssignment(exprOrAssignment: Expression | ShorthandPropertyAssignment, sourceType: Type, checkMode?: CheckMode, rightIsThis?: boolean): Type { let target: Expression; if (exprOrAssignment.kind === SyntaxKind.ShorthandPropertyAssignment) { - const prop = exprOrAssignment; + const prop = exprOrAssignment as ShorthandPropertyAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. @@ -31588,21 +31593,21 @@ namespace ts { } checkBinaryLikeExpression(prop.name, prop.equalsToken!, prop.objectAssignmentInitializer, checkMode); } - target = (exprOrAssignment).name; + target = (exprOrAssignment as ShorthandPropertyAssignment).name; } else { target = exprOrAssignment; } - if (target.kind === SyntaxKind.BinaryExpression && (target).operatorToken.kind === SyntaxKind.EqualsToken) { - checkBinaryExpression(target, checkMode); - target = (target).left; + if (target.kind === SyntaxKind.BinaryExpression && (target as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + checkBinaryExpression(target as BinaryExpression, checkMode); + target = (target as BinaryExpression).left; } if (target.kind === SyntaxKind.ObjectLiteralExpression) { - return checkObjectLiteralAssignment(target, sourceType, rightIsThis); + return checkObjectLiteralAssignment(target as ObjectLiteralExpression, sourceType, rightIsThis); } if (target.kind === SyntaxKind.ArrayLiteralExpression) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); + return checkArrayLiteralAssignment(target as ArrayLiteralExpression, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } @@ -32457,7 +32462,7 @@ namespace ts { function isLiteralOfContextualType(candidateType: Type, contextualType: Type | undefined): boolean { if (contextualType) { if (contextualType.flags & TypeFlags.UnionOrIntersection) { - const types = (contextualType).types; + const types = (contextualType as UnionType).types; return some(types, t => isLiteralOfContextualType(candidateType, t)); } if (contextualType.flags & TypeFlags.InstantiableNonPrimitive) { @@ -32528,7 +32533,7 @@ namespace ts { const constructSignature = getSingleSignature(type, SignatureKind.Construct, /*allowMembers*/ true); const signature = callSignature || constructSignature; if (signature && signature.typeParameters) { - const contextualType = getApparentTypeOfContextualType(node, ContextFlags.NoConstraints); + const contextualType = getApparentTypeOfContextualType(node as Expression, ContextFlags.NoConstraints); if (contextualType) { const contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? SignatureKind.Call : SignatureKind.Construct, /*allowMembers*/ false); if (contextualSignature && !contextualSignature.typeParameters) { @@ -32643,11 +32648,11 @@ namespace ts { } function getUniqueTypeParameterName(typeParameters: readonly TypeParameter[], baseName: __String) { - let len = (baseName).length; - while (len > 1 && (baseName).charCodeAt(len - 1) >= CharacterCodes._0 && (baseName).charCodeAt(len - 1) <= CharacterCodes._9) len--; - const s = (baseName).slice(0, len); + let len = (baseName as string).length; + while (len > 1 && (baseName as string).charCodeAt(len - 1) >= CharacterCodes._0 && (baseName as string).charCodeAt(len - 1) <= CharacterCodes._9) len--; + const s = (baseName as string).slice(0, len); for (let index = 1; true; index++) { - const augmentedName = <__String>(s + index); + const augmentedName = (s + index as __String); if (!hasTypeParameterByName(typeParameters, augmentedName)) { return augmentedName; } @@ -32708,7 +32713,7 @@ namespace ts { } } else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) { - return getTypeFromTypeNode((expr).type); + return getTypeFromTypeNode((expr as TypeAssertion).type); } else if (node.kind === SyntaxKind.NumericLiteral || node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.TrueKeyword || node.kind === SyntaxKind.FalseKeyword) { @@ -32764,10 +32769,10 @@ namespace ts { // - 'object' in indexed access // - target in rhs of import statement const ok = - (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).expression === node) || - (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).expression === node) || - ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === SyntaxKind.TypeQuery && (node.parent).exprName === node)) || + (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).expression === node) || + (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent as ElementAccessExpression).expression === node) || + ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node as Identifier) || + (node.parent.kind === SyntaxKind.TypeQuery && (node.parent as TypeQueryNode).exprName === node)) || (node.parent.kind === SyntaxKind.ExportSpecifier); // We allow reexporting const enums if (!ok) { @@ -32805,7 +32810,7 @@ namespace ts { } switch (kind) { case SyntaxKind.Identifier: - return checkIdentifier(node, checkMode); + return checkIdentifier(node as Identifier, checkMode); case SyntaxKind.ThisKeyword: return checkThisExpression(node); case SyntaxKind.SuperKeyword: @@ -32826,76 +32831,76 @@ namespace ts { case SyntaxKind.FalseKeyword: return falseType; case SyntaxKind.TemplateExpression: - return checkTemplateExpression(node); + return checkTemplateExpression(node as TemplateExpression); case SyntaxKind.RegularExpressionLiteral: return globalRegExpType; case SyntaxKind.ArrayLiteralExpression: - return checkArrayLiteral(node, checkMode, forceTuple); + return checkArrayLiteral(node as ArrayLiteralExpression, checkMode, forceTuple); case SyntaxKind.ObjectLiteralExpression: - return checkObjectLiteral(node, checkMode); + return checkObjectLiteral(node as ObjectLiteralExpression, checkMode); case SyntaxKind.PropertyAccessExpression: - return checkPropertyAccessExpression(node, checkMode); + return checkPropertyAccessExpression(node as PropertyAccessExpression, checkMode); case SyntaxKind.QualifiedName: - return checkQualifiedName(node, checkMode); + return checkQualifiedName(node as QualifiedName, checkMode); case SyntaxKind.ElementAccessExpression: - return checkIndexedAccess(node, checkMode); + return checkIndexedAccess(node as ElementAccessExpression, checkMode); case SyntaxKind.CallExpression: - if ((node).expression.kind === SyntaxKind.ImportKeyword) { - return checkImportCallExpression(node); + if ((node as CallExpression).expression.kind === SyntaxKind.ImportKeyword) { + return checkImportCallExpression(node as ImportCall); } // falls through case SyntaxKind.NewExpression: - return checkCallExpression(node, checkMode); + return checkCallExpression(node as CallExpression, checkMode); case SyntaxKind.TaggedTemplateExpression: - return checkTaggedTemplateExpression(node); + return checkTaggedTemplateExpression(node as TaggedTemplateExpression); case SyntaxKind.ParenthesizedExpression: - return checkParenthesizedExpression(node, checkMode); + return checkParenthesizedExpression(node as ParenthesizedExpression, checkMode); case SyntaxKind.ClassExpression: - return checkClassExpression(node); + return checkClassExpression(node as ClassExpression); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return checkFunctionExpressionOrObjectLiteralMethod(node as FunctionExpression | ArrowFunction, checkMode); case SyntaxKind.TypeOfExpression: - return checkTypeOfExpression(node); + return checkTypeOfExpression(node as TypeOfExpression); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: - return checkAssertion(node); + return checkAssertion(node as AssertionExpression); case SyntaxKind.NonNullExpression: - return checkNonNullAssertion(node); + return checkNonNullAssertion(node as NonNullExpression); case SyntaxKind.MetaProperty: - return checkMetaProperty(node); + return checkMetaProperty(node as MetaProperty); case SyntaxKind.DeleteExpression: - return checkDeleteExpression(node); + return checkDeleteExpression(node as DeleteExpression); case SyntaxKind.VoidExpression: - return checkVoidExpression(node); + return checkVoidExpression(node as VoidExpression); case SyntaxKind.AwaitExpression: - return checkAwaitExpression(node); + return checkAwaitExpression(node as AwaitExpression); case SyntaxKind.PrefixUnaryExpression: - return checkPrefixUnaryExpression(node); + return checkPrefixUnaryExpression(node as PrefixUnaryExpression); case SyntaxKind.PostfixUnaryExpression: - return checkPostfixUnaryExpression(node); + return checkPostfixUnaryExpression(node as PostfixUnaryExpression); case SyntaxKind.BinaryExpression: - return checkBinaryExpression(node, checkMode); + return checkBinaryExpression(node as BinaryExpression, checkMode); case SyntaxKind.ConditionalExpression: - return checkConditionalExpression(node, checkMode); + return checkConditionalExpression(node as ConditionalExpression, checkMode); case SyntaxKind.SpreadElement: - return checkSpreadExpression(node, checkMode); + return checkSpreadExpression(node as SpreadElement, checkMode); case SyntaxKind.OmittedExpression: return undefinedWideningType; case SyntaxKind.YieldExpression: - return checkYieldExpression(node); + return checkYieldExpression(node as YieldExpression); case SyntaxKind.SyntheticExpression: - return checkSyntheticExpression(node); + return checkSyntheticExpression(node as SyntheticExpression); case SyntaxKind.JsxExpression: - return checkJsxExpression(node, checkMode); + return checkJsxExpression(node as JsxExpression, checkMode); case SyntaxKind.JsxElement: - return checkJsxElement(node, checkMode); + return checkJsxElement(node as JsxElement, checkMode); case SyntaxKind.JsxSelfClosingElement: - return checkJsxSelfClosingElement(node, checkMode); + return checkJsxSelfClosingElement(node as JsxSelfClosingElement, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node); + return checkJsxFragment(node as JsxFragment); case SyntaxKind.JsxAttributes: - return checkJsxAttributes(node, checkMode); + return checkJsxAttributes(node as JsxAttributes, checkMode); case SyntaxKind.JsxOpeningElement: Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } @@ -33031,7 +33036,7 @@ namespace ts { case SyntaxKind.FunctionType: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - const parent = node.parent; + const parent = node.parent as SignatureDeclaration; if (node === parent.type) { return parent; } @@ -33068,16 +33073,16 @@ namespace ts { function checkSignatureDeclaration(node: SignatureDeclaration) { // Grammar checking if (node.kind === SyntaxKind.IndexSignature) { - checkGrammarIndexSignature(node); + checkGrammarIndexSignature(node as SignatureDeclaration); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled else if (node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType || node.kind === SyntaxKind.CallSignature || node.kind === SyntaxKind.Constructor || node.kind === SyntaxKind.ConstructSignature) { - checkGrammarFunctionLikeDeclaration(node); + checkGrammarFunctionLikeDeclaration(node as FunctionLikeDeclaration); } - const functionFlags = getFunctionFlags(node); + const functionFlags = getFunctionFlags(node as FunctionLikeDeclaration); if (!(functionFlags & FunctionFlags.Invalid)) { // Async generators prior to ESNext require the __await and __asyncGenerator helpers if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && languageVersion < ScriptTarget.ESNext) { @@ -33120,7 +33125,7 @@ namespace ts { } if (returnTypeNode) { - const functionFlags = getFunctionFlags(node); + const functionFlags = getFunctionFlags(node as FunctionDeclaration); if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Generator)) === FunctionFlags.Generator) { const returnType = getTypeFromTypeNode(returnTypeNode); if (returnType === voidType) { @@ -33141,7 +33146,7 @@ namespace ts { } } else if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { - checkAsyncFunctionReturnType(node, returnTypeNode); + checkAsyncFunctionReturnType(node as FunctionLikeDeclaration, returnTypeNode); } } if (node.kind !== SyntaxKind.IndexSignature && node.kind !== SyntaxKind.JSDocFunctionType) { @@ -33308,7 +33313,7 @@ namespace ts { let seenNumericIndexer = false; let seenStringIndexer = false; for (const decl of indexSymbol.declarations) { - const declaration = decl; + const declaration = decl as SignatureDeclaration; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: @@ -33342,6 +33347,10 @@ namespace ts { if (isPrivateIdentifier(node.name) && hasStaticModifier(node) && node.initializer && languageVersion === ScriptTarget.ESNext && !compilerOptions.useDefineForClassFields) { error(node.initializer, Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } + // property signatures already report "initializer not allowed in ambient context" elsewhere + if (hasSyntacticModifier(node, ModifierFlags.Abstract) && node.kind === SyntaxKind.PropertyDeclaration && node.initializer) { + error(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name)); + } } function checkPropertySignature(node: PropertySignature) { @@ -33358,8 +33367,7 @@ namespace ts { // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); - // Abstract methods cannot have an implementation. - // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + // method signatures already report "implementation not allowed in ambient context" elsewhere if (hasSyntacticModifier(node, ModifierFlags.Abstract) && node.kind === SyntaxKind.MethodDeclaration && node.body) { error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); } @@ -33422,13 +33430,13 @@ namespace ts { } return n.kind === SyntaxKind.PropertyDeclaration && !hasSyntacticModifier(n, ModifierFlags.Static) && - !!(n).initializer; + !!(n as PropertyDeclaration).initializer; } // TS 1.0 spec (April 2014): 8.3.2 // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. - const containingClassDecl = node.parent; + const containingClassDecl = node.parent as ClassDeclaration; if (getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); @@ -33445,7 +33453,7 @@ namespace ts { // or the containing class declares instance member variables with initializers. const superCallShouldBeFirst = (compilerOptions.target !== ScriptTarget.ESNext || !useDefineForClassFields) && - (some((node.parent).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + (some((node.parent as ClassDeclaration).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); // Skip past any prologue directives to find the first statement @@ -33455,8 +33463,8 @@ namespace ts { let superCallStatement: ExpressionStatement | undefined; for (const statement of statements) { - if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCall((statement).expression)) { - superCallStatement = statement; + if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCall((statement as ExpressionStatement).expression)) { + superCallStatement = statement as ExpressionStatement; break; } if (!isPrologueDirective(statement)) { @@ -33567,7 +33575,7 @@ namespace ts { const symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { return symbol.flags & SymbolFlags.TypeAlias && getSymbolLinks(symbol).typeParameters || - (getObjectFlags(type) & ObjectFlags.Reference ? (type).target.localTypeParameters : undefined); + (getObjectFlags(type) & ObjectFlags.Reference ? (type as TypeReference).target.localTypeParameters : undefined); } } return undefined; @@ -33641,7 +33649,7 @@ namespace ts { } const flags = getTupleElementFlags(e); if (flags & ElementFlags.Variadic) { - const type = getTypeFromTypeNode((e).type); + const type = getTypeFromTypeNode((e as RestTypeNode | NamedTupleMember).type); if (!isArrayLikeType(type)) { error(e, Diagnostics.A_rest_element_type_must_be_an_array_type); break; @@ -33683,11 +33691,11 @@ namespace ts { return type; } // Check if the index type is assignable to 'keyof T' for the object type. - const objectType = (type).objectType; - const indexType = (type).indexType; + const objectType = (type as IndexedAccessType).objectType; + const indexType = (type as IndexedAccessType).indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { if (accessNode.kind === SyntaxKind.ElementAccessExpression && isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & ObjectFlags.Mapped && getMappedTypeModifiers(objectType) & MappedTypeModifiers.IncludeReadonly) { + getObjectFlags(objectType) & ObjectFlags.Mapped && getMappedTypeModifiers(objectType as MappedType) & MappedTypeModifiers.IncludeReadonly) { error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -33727,7 +33735,7 @@ namespace ts { reportImplicitAny(node, anyType); } - const type = getTypeFromMappedTypeNode(node); + const type = getTypeFromMappedTypeNode(node) as MappedType; const nameType = getNameTypeFromMappedType(type); if (nameType) { checkTypeAssignableTo(nameType, keyofConstraintType, node.nameType); @@ -33752,7 +33760,7 @@ namespace ts { } function checkInferType(node: InferTypeNode) { - if (!findAncestor(node, n => n.parent && n.parent.kind === SyntaxKind.ConditionalType && (n.parent).extendsType === n)) { + if (!findAncestor(node, n => n.parent && n.parent.kind === SyntaxKind.ConditionalType && (n.parent as ConditionalTypeNode).extendsType === n)) { grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -33892,8 +33900,8 @@ namespace ts { // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { - const errorNode: Node = (subsequentNode).name || subsequentNode; - const subsequentName = (subsequentNode).name; + const errorNode: Node = (subsequentNode as FunctionLikeDeclaration).name || subsequentNode; + const subsequentName = (subsequentNode as FunctionLikeDeclaration).name; if (node.name && subsequentName && ( // both are private identifiers isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || @@ -33917,7 +33925,7 @@ namespace ts { } return; } - if (nodeIsPresent((subsequentNode).body)) { + if (nodeIsPresent((subsequentNode as FunctionLikeDeclaration).body)) { error(errorNode, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); return; } @@ -33945,7 +33953,7 @@ namespace ts { const functionDeclarations = [] as Declaration[]; if (declarations) { for (const current of declarations) { - const node = current; + const node = current as SignatureDeclaration | ClassDeclaration | ClassExpression; const inAmbientContext = node.flags & NodeFlags.Ambient; const inAmbientContextOrInterface = node.parent && (node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral) || inAmbientContext; if (inAmbientContextOrInterface) { @@ -34200,13 +34208,13 @@ namespace ts { return undefined; } - const typeAsPromise = type; + const typeAsPromise = type as PromiseOrAwaitableType; if (typeAsPromise.promisedTypeOfPromise) { return typeAsPromise.promisedTypeOfPromise; } if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) { - return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; + return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type as GenericType)[0]; } const thenFunction = getTypeOfPropertyOfType(type, "then" as __String)!; // TODO: GH#18217 @@ -34273,7 +34281,7 @@ namespace ts { return type; } - const typeAsAwaitable = type; + const typeAsAwaitable = type as PromiseOrAwaitableType; if (typeAsAwaitable.awaitedTypeOfType) { return typeAsAwaitable.awaitedTypeOfType; } @@ -34285,7 +34293,7 @@ namespace ts { } function getAwaitedTypeWorker(type: Type, errorNode?: Node, diagnosticMessage?: DiagnosticMessage, arg0?: string | number): Type | undefined { - const typeAsAwaitable = type; + const typeAsAwaitable = type as PromiseOrAwaitableType; if (typeAsAwaitable.awaitedTypeOfType) { return typeAsAwaitable.awaitedTypeOfType; } @@ -34570,17 +34578,17 @@ namespace ts { switch (node.kind) { case SyntaxKind.IntersectionType: case SyntaxKind.UnionType: - return getEntityNameForDecoratorMetadataFromTypeList((node).types); + return getEntityNameForDecoratorMetadataFromTypeList((node as UnionOrIntersectionTypeNode).types); case SyntaxKind.ConditionalType: - return getEntityNameForDecoratorMetadataFromTypeList([(node).trueType, (node).falseType]); + return getEntityNameForDecoratorMetadataFromTypeList([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType]); case SyntaxKind.ParenthesizedType: case SyntaxKind.NamedTupleMember: - return getEntityNameForDecoratorMetadata((node).type); + return getEntityNameForDecoratorMetadata((node as ParenthesizedTypeNode).type); case SyntaxKind.TypeReference: - return (node).typeName; + return (node as TypeReferenceNode).typeName; } } } @@ -34656,7 +34664,7 @@ namespace ts { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { case SyntaxKind.ClassDeclaration: - const constructor = getFirstConstructorWithBody(node); + const constructor = getFirstConstructorWithBody(node as ClassDeclaration); if (constructor) { for (const parameter of constructor.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -34671,19 +34679,19 @@ namespace ts { markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node as AccessorDeclaration) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; case SyntaxKind.MethodDeclaration: - for (const parameter of (node).parameters) { + for (const parameter of (node as FunctionLikeDeclaration).parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node as FunctionLikeDeclaration)); break; case SyntaxKind.PropertyDeclaration: - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node as ParameterDeclaration)); break; case SyntaxKind.Parameter: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node as ParameterDeclaration)); const containingSignature = (node as ParameterDeclaration).parent; for (const parameter of containingSignature.parameters) { markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -34981,7 +34989,7 @@ namespace ts { } break; case SyntaxKind.Constructor: - for (const parameter of (member).parameters) { + for (const parameter of (member as ConstructorDeclaration).parameters) { if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, ModifierFlags.Private)) { addDiagnostic(parameter, UnusedKind.Local, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); } @@ -35209,7 +35217,7 @@ namespace ts { function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) { // no rest parameters \ declaration context \ overload - no codegen impact - if (languageVersion >= ScriptTarget.ES2015 || !hasRestParameter(node) || node.flags & NodeFlags.Ambient || nodeIsMissing((node).body)) { + if (languageVersion >= ScriptTarget.ES2015 || !hasRestParameter(node) || node.flags & NodeFlags.Ambient || nodeIsMissing((node as FunctionLikeDeclaration).body)) { return; } @@ -35241,7 +35249,7 @@ namespace ts { } const root = getRootDeclaration(node); - if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent).body)) { + if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent as FunctionLikeDeclaration).body)) { // just an overload - no codegen impact return false; } @@ -35255,7 +35263,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(getNameOfDeclaration(node as Declaration), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -35271,7 +35279,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureNewTarget) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(getNameOfDeclaration(node as Declaration), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -35307,7 +35315,7 @@ namespace ts { // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent const parent = getDeclarationContainer(node); - if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent)) { + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); @@ -35326,7 +35334,7 @@ namespace ts { // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent const parent = getDeclarationContainer(node); - if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent) && parent.flags & NodeFlags.HasAsyncFunctions) { + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile) && parent.flags & NodeFlags.HasAsyncFunctions) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); @@ -35774,13 +35782,13 @@ namespace ts { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { - checkGrammarVariableDeclarationList(node.initializer); + checkGrammarVariableDeclarationList(node.initializer as VariableDeclarationList); } } if (node.initializer) { if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - forEach((node.initializer).declarations, checkVariableDeclaration); + forEach((node.initializer as VariableDeclarationList).declarations, checkVariableDeclaration); } else { checkExpression(node.initializer); @@ -35863,7 +35871,7 @@ namespace ts { // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - const variable = (node.initializer).declarations[0]; + const variable = (node.initializer as VariableDeclarationList).declarations[0]; if (variable && isBindingPattern(variable.name)) { error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } @@ -35904,7 +35912,7 @@ namespace ts { } function checkForInOrForOfVariableDeclaration(iterationStatement: ForInOrOfStatement): void { - const variableDeclarationList = iterationStatement.initializer; + const variableDeclarationList = iterationStatement.initializer as VariableDeclarationList; // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. if (variableDeclarationList.declarations.length >= 1) { const decl = variableDeclarationList.declarations[0]; @@ -35975,7 +35983,7 @@ namespace ts { if (arrayType.flags & TypeFlags.Union) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. - const arrayTypes = (inputType).types; + const arrayTypes = (inputType as UnionType).types; const filteredTypes = filter(arrayTypes, t => !(t.flags & TypeFlags.StringLike)); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, UnionReduction.Subtype); @@ -36794,7 +36802,7 @@ namespace ts { if (isFunctionLike(current)) { return "quit"; } - if (current.kind === SyntaxKind.LabeledStatement && (current).label.escapedText === node.label.escapedText) { + if (current.kind === SyntaxKind.LabeledStatement && (current as LabeledStatement).label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); return true; } @@ -36895,7 +36903,7 @@ namespace ts { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (getObjectFlags(type) & ObjectFlags.Interface)) { - const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); + const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type as InterfaceType), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } if (!errorNode) { @@ -36951,7 +36959,7 @@ namespace ts { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together - const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind)); + const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType as InterfaceType), base => getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind)); errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } @@ -37026,7 +37034,7 @@ namespace ts { visit(root); function visit(node: Node) { if (node.kind === SyntaxKind.TypeReference) { - const type = getTypeFromTypeReference(node); + const type = getTypeFromTypeReference(node as TypeReferenceNode); if (type.flags & TypeFlags.TypeParameter) { for (let i = index; i < typeParameters.length; i++) { if (type.symbol === getSymbolOfNode(typeParameters[i])) { @@ -37053,7 +37061,7 @@ namespace ts { return; } - const type = getDeclaredTypeOfSymbol(symbol); + const type = getDeclaredTypeOfSymbol(symbol) as InterfaceType; if (!areTypeParametersIdentical(declarations, type.localTypeParameters!)) { // Report an error on every conflicting declaration. const name = symbolToString(symbol); @@ -37148,9 +37156,9 @@ namespace ts { checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfNode(node); - const type = getDeclaredTypeOfSymbol(symbol); + const type = getDeclaredTypeOfSymbol(symbol) as InterfaceType; const typeWithThis = getTypeWithThisArgument(type); - const staticType = getTypeOfSymbol(symbol); + const staticType = getTypeOfSymbol(symbol) as ObjectType; checkTypeParameterListsIdentical(symbol); checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); @@ -37369,7 +37377,7 @@ namespace ts { function getTargetSymbol(s: Symbol) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return getCheckFlags(s) & CheckFlags.Instantiated ? (s).target! : s; + return getCheckFlags(s) & CheckFlags.Instantiated ? (s as TransientSymbol).target! : s; } function getClassOrInterfaceDeclarationsOfSymbol(symbol: Symbol) { @@ -37583,7 +37591,7 @@ namespace ts { continue; } if (isInstancePropertyWithoutInitializer(member)) { - const propName = (member).name; + const propName = (member as PropertyDeclaration).name; if (isIdentifier(propName) || isPrivateIdentifier(propName)) { const type = getTypeOfSymbol(getSymbolOfNode(member)); if (!(type.flags & TypeFlags.AnyOrUnknown || getFalsyFlags(type) & TypeFlags.Undefined)) { @@ -37599,8 +37607,8 @@ namespace ts { function isInstancePropertyWithoutInitializer(node: Node) { return node.kind === SyntaxKind.PropertyDeclaration && !hasSyntacticModifier(node, ModifierFlags.Static | ModifierFlags.Abstract) && - !(node).exclamationToken && - !(node).initializer; + !(node as PropertyDeclaration).exclamationToken && + !(node as PropertyDeclaration).initializer; } function isPropertyInitializedInConstructor(propName: Identifier | PrivateIdentifier, propType: Type, constructor: ConstructorDeclaration) { @@ -37627,7 +37635,7 @@ namespace ts { // Only check this symbol once const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (node === firstInterfaceDecl) { - const type = getDeclaredTypeOfSymbol(symbol); + const type = getDeclaredTypeOfSymbol(symbol) as InterfaceType; const typeWithThis = getTypeWithThisArgument(type); // run subsequent checks only if first set succeeded if (checkInheritedPropertiesAreIdentical(type, node.name)) { @@ -37750,9 +37758,9 @@ namespace ts { function evaluate(expr: Expression): string | number | undefined { switch (expr.kind) { case SyntaxKind.PrefixUnaryExpression: - const value = evaluate((expr).operand); + const value = evaluate((expr as PrefixUnaryExpression).operand); if (typeof value === "number") { - switch ((expr).operator) { + switch ((expr as PrefixUnaryExpression).operator) { case SyntaxKind.PlusToken: return value; case SyntaxKind.MinusToken: return -value; case SyntaxKind.TildeToken: return ~value; @@ -37760,10 +37768,10 @@ namespace ts { } break; case SyntaxKind.BinaryExpression: - const left = evaluate((expr).left); - const right = evaluate((expr).right); + const left = evaluate((expr as BinaryExpression).left); + const right = evaluate((expr as BinaryExpression).right); if (typeof left === "number" && typeof right === "number") { - switch ((expr).operatorToken.kind) { + switch ((expr as BinaryExpression).operatorToken.kind) { case SyntaxKind.BarToken: return left | right; case SyntaxKind.AmpersandToken: return left & right; case SyntaxKind.GreaterThanGreaterThanToken: return left >> right; @@ -37778,27 +37786,27 @@ namespace ts { case SyntaxKind.AsteriskAsteriskToken: return left ** right; } } - else if (typeof left === "string" && typeof right === "string" && (expr).operatorToken.kind === SyntaxKind.PlusToken) { + else if (typeof left === "string" && typeof right === "string" && (expr as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken) { return left + right; } break; case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: - return (expr).text; + return (expr as StringLiteralLike).text; case SyntaxKind.NumericLiteral: - checkGrammarNumericLiteral(expr); - return +(expr).text; + checkGrammarNumericLiteral(expr as NumericLiteral); + return +(expr as NumericLiteral).text; case SyntaxKind.ParenthesizedExpression: - return evaluate((expr).expression); + return evaluate((expr as ParenthesizedExpression).expression); case SyntaxKind.Identifier: - const identifier = expr; + const identifier = expr as Identifier; if (isInfinityOrNaNString(identifier.escapedText)) { return +(identifier.escapedText); } return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: - const ex = expr; + const ex = expr as AccessExpression; if (isConstantMemberAccess(ex)) { const type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & SymbolFlags.Enum) { @@ -37838,9 +37846,9 @@ namespace ts { function isConstantMemberAccess(node: Expression): boolean { return node.kind === SyntaxKind.Identifier || - node.kind === SyntaxKind.PropertyAccessExpression && isConstantMemberAccess((node).expression) || - node.kind === SyntaxKind.ElementAccessExpression && isConstantMemberAccess((node).expression) && - isStringLiteralLike((node).argumentExpression); + node.kind === SyntaxKind.PropertyAccessExpression && isConstantMemberAccess((node as PropertyAccessExpression).expression) || + node.kind === SyntaxKind.ElementAccessExpression && isConstantMemberAccess((node as ElementAccessExpression).expression) && + isStringLiteralLike((node as ElementAccessExpression).argumentExpression); } function checkEnumDeclaration(node: EnumDeclaration) { @@ -37885,7 +37893,7 @@ namespace ts { return false; } - const enumDeclaration = declaration; + const enumDeclaration = declaration as EnumDeclaration; if (!enumDeclaration.members.length) { return false; } @@ -37914,7 +37922,7 @@ namespace ts { if (declarations) { for (const declaration of declarations) { if ((declaration.kind === SyntaxKind.ClassDeclaration || - (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && + (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration as FunctionLikeDeclaration).body))) && !(declaration.flags & NodeFlags.Ambient)) { return declaration; } @@ -38041,7 +38049,7 @@ namespace ts { switch (node.kind) { case SyntaxKind.VariableStatement: // error each individual name in variable statement instead of marking the entire variable statement - for (const decl of (node).declarationList.declarations) { + for (const decl of (node as VariableStatement).declarationList.declarations) { checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -38055,7 +38063,7 @@ namespace ts { break; case SyntaxKind.BindingElement: case SyntaxKind.VariableDeclaration: - const name = (node).name; + const name = (node as VariableDeclaration | BindingElement).name; if (isBindingPattern(name)) { for (const el of name.elements) { // mark individual names in binding pattern @@ -38415,7 +38423,7 @@ namespace ts { return; } - const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; + const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent as ModuleDeclaration; if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { if (node.isExportEquals) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); @@ -38560,60 +38568,60 @@ namespace ts { switch (kind) { case SyntaxKind.TypeParameter: - return checkTypeParameter(node); + return checkTypeParameter(node as TypeParameterDeclaration); case SyntaxKind.Parameter: - return checkParameter(node); + return checkParameter(node as ParameterDeclaration); case SyntaxKind.PropertyDeclaration: - return checkPropertyDeclaration(node); + return checkPropertyDeclaration(node as PropertyDeclaration); case SyntaxKind.PropertySignature: - return checkPropertySignature(node); + return checkPropertySignature(node as PropertySignature); case SyntaxKind.ConstructorType: case SyntaxKind.FunctionType: case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: - return checkSignatureDeclaration(node); + return checkSignatureDeclaration(node as SignatureDeclaration); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - return checkMethodDeclaration(node); + return checkMethodDeclaration(node as MethodDeclaration | MethodSignature); case SyntaxKind.Constructor: - return checkConstructorDeclaration(node); + return checkConstructorDeclaration(node as ConstructorDeclaration); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return checkAccessorDeclaration(node); + return checkAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.TypeReference: - return checkTypeReferenceNode(node); + return checkTypeReferenceNode(node as TypeReferenceNode); case SyntaxKind.TypePredicate: - return checkTypePredicate(node); + return checkTypePredicate(node as TypePredicateNode); case SyntaxKind.TypeQuery: - return checkTypeQuery(node); + return checkTypeQuery(node as TypeQueryNode); case SyntaxKind.TypeLiteral: - return checkTypeLiteral(node); + return checkTypeLiteral(node as TypeLiteralNode); case SyntaxKind.ArrayType: - return checkArrayType(node); + return checkArrayType(node as ArrayTypeNode); case SyntaxKind.TupleType: - return checkTupleType(node); + return checkTupleType(node as TupleTypeNode); case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: - return checkUnionOrIntersectionType(node); + return checkUnionOrIntersectionType(node as UnionOrIntersectionTypeNode); case SyntaxKind.ParenthesizedType: case SyntaxKind.OptionalType: case SyntaxKind.RestType: - return checkSourceElement((node).type); + return checkSourceElement((node as ParenthesizedTypeNode | OptionalTypeNode | RestTypeNode).type); case SyntaxKind.ThisType: - return checkThisType(node); + return checkThisType(node as ThisTypeNode); case SyntaxKind.TypeOperator: - return checkTypeOperator(node); + return checkTypeOperator(node as TypeOperatorNode); case SyntaxKind.ConditionalType: - return checkConditionalType(node); + return checkConditionalType(node as ConditionalTypeNode); case SyntaxKind.InferType: - return checkInferType(node); + return checkInferType(node as InferTypeNode); case SyntaxKind.TemplateLiteralType: - return checkTemplateLiteralType(node); + return checkTemplateLiteralType(node as TemplateLiteralTypeNode); case SyntaxKind.ImportType: - return checkImportType(node); + return checkImportType(node as ImportTypeNode); case SyntaxKind.NamedTupleMember: - return checkNamedTupleMember(node); + return checkNamedTupleMember(node as NamedTupleMember); case SyntaxKind.JSDocAugmentsTag: return checkJSDocAugmentsTag(node as JSDocAugmentsTag); case SyntaxKind.JSDocImplementsTag: @@ -38647,67 +38655,67 @@ namespace ts { case SyntaxKind.JSDocTypeExpression: return checkSourceElement((node as JSDocTypeExpression).type); case SyntaxKind.IndexedAccessType: - return checkIndexedAccessType(node); + return checkIndexedAccessType(node as IndexedAccessTypeNode); case SyntaxKind.MappedType: - return checkMappedType(node); + return checkMappedType(node as MappedTypeNode); case SyntaxKind.FunctionDeclaration: - return checkFunctionDeclaration(node); + return checkFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.Block: case SyntaxKind.ModuleBlock: - return checkBlock(node); + return checkBlock(node as Block); case SyntaxKind.VariableStatement: - return checkVariableStatement(node); + return checkVariableStatement(node as VariableStatement); case SyntaxKind.ExpressionStatement: - return checkExpressionStatement(node); + return checkExpressionStatement(node as ExpressionStatement); case SyntaxKind.IfStatement: - return checkIfStatement(node); + return checkIfStatement(node as IfStatement); case SyntaxKind.DoStatement: - return checkDoStatement(node); + return checkDoStatement(node as DoStatement); case SyntaxKind.WhileStatement: - return checkWhileStatement(node); + return checkWhileStatement(node as WhileStatement); case SyntaxKind.ForStatement: - return checkForStatement(node); + return checkForStatement(node as ForStatement); case SyntaxKind.ForInStatement: - return checkForInStatement(node); + return checkForInStatement(node as ForInStatement); case SyntaxKind.ForOfStatement: - return checkForOfStatement(node); + return checkForOfStatement(node as ForOfStatement); case SyntaxKind.ContinueStatement: case SyntaxKind.BreakStatement: - return checkBreakOrContinueStatement(node); + return checkBreakOrContinueStatement(node as BreakOrContinueStatement); case SyntaxKind.ReturnStatement: - return checkReturnStatement(node); + return checkReturnStatement(node as ReturnStatement); case SyntaxKind.WithStatement: - return checkWithStatement(node); + return checkWithStatement(node as WithStatement); case SyntaxKind.SwitchStatement: - return checkSwitchStatement(node); + return checkSwitchStatement(node as SwitchStatement); case SyntaxKind.LabeledStatement: - return checkLabeledStatement(node); + return checkLabeledStatement(node as LabeledStatement); case SyntaxKind.ThrowStatement: - return checkThrowStatement(node); + return checkThrowStatement(node as ThrowStatement); case SyntaxKind.TryStatement: - return checkTryStatement(node); + return checkTryStatement(node as TryStatement); case SyntaxKind.VariableDeclaration: - return checkVariableDeclaration(node); + return checkVariableDeclaration(node as VariableDeclaration); case SyntaxKind.BindingElement: - return checkBindingElement(node); + return checkBindingElement(node as BindingElement); case SyntaxKind.ClassDeclaration: - return checkClassDeclaration(node); + return checkClassDeclaration(node as ClassDeclaration); case SyntaxKind.InterfaceDeclaration: - return checkInterfaceDeclaration(node); + return checkInterfaceDeclaration(node as InterfaceDeclaration); case SyntaxKind.TypeAliasDeclaration: - return checkTypeAliasDeclaration(node); + return checkTypeAliasDeclaration(node as TypeAliasDeclaration); case SyntaxKind.EnumDeclaration: - return checkEnumDeclaration(node); + return checkEnumDeclaration(node as EnumDeclaration); case SyntaxKind.ModuleDeclaration: - return checkModuleDeclaration(node); + return checkModuleDeclaration(node as ModuleDeclaration); case SyntaxKind.ImportDeclaration: - return checkImportDeclaration(node); + return checkImportDeclaration(node as ImportDeclaration); case SyntaxKind.ImportEqualsDeclaration: - return checkImportEqualsDeclaration(node); + return checkImportEqualsDeclaration(node as ImportEqualsDeclaration); case SyntaxKind.ExportDeclaration: - return checkExportDeclaration(node); + return checkExportDeclaration(node as ExportDeclaration); case SyntaxKind.ExportAssignment: - return checkExportAssignment(node); + return checkExportAssignment(node as ExportAssignment); case SyntaxKind.EmptyStatement: case SyntaxKind.DebuggerStatement: checkGrammarStatementInAmbientContext(node); @@ -38836,20 +38844,20 @@ namespace ts { case SyntaxKind.ArrowFunction: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + checkFunctionExpressionOrObjectLiteralMethodDeferred(node as FunctionExpression); break; case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - checkAccessorDeclaration(node); + checkAccessorDeclaration(node as AccessorDeclaration); break; case SyntaxKind.ClassExpression: - checkClassExpressionDeferred(node); + checkClassExpressionDeferred(node as ClassExpression); break; case SyntaxKind.JsxSelfClosingElement: - checkJsxSelfClosingElementDeferred(node); + checkJsxSelfClosingElementDeferred(node as JsxSelfClosingElement); break; case SyntaxKind.JsxElement: - checkJsxElementDeferred(node); + checkJsxElementDeferred(node as JsxElement); break; } currentNode = saveCurrentNode; @@ -39027,7 +39035,7 @@ namespace ts { switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalModule(location)) break; + if (!isExternalModule(location as SourceFile)) break; // falls through case SyntaxKind.ModuleDeclaration: copyLocallyVisibleExportSymbols(getSymbolOfNode(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); @@ -39156,16 +39164,6 @@ namespace ts { return node.parent.kind === SyntaxKind.ExpressionWithTypeArguments; } - function getJSDocEntryNameReference(node: Identifier | PrivateIdentifier | PropertyAccessExpression | QualifiedName): JSDocNameReference | undefined { - while (node.parent.kind === SyntaxKind.QualifiedName) { - node = node.parent as QualifiedName; - } - while (node.parent.kind === SyntaxKind.PropertyAccessExpression) { - node = node.parent as PropertyAccessExpression; - } - return isJSDocNameReference(node.parent) ? node.parent : undefined; - } - function forEachEnclosingClass(node: Node, callback: (node: Node) => T | undefined): T | undefined { let result: T | undefined; @@ -39197,15 +39195,15 @@ namespace ts { function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide: EntityName): ImportEqualsDeclaration | ExportAssignment | undefined { while (nodeOnRightSide.parent.kind === SyntaxKind.QualifiedName) { - nodeOnRightSide = nodeOnRightSide.parent; + nodeOnRightSide = nodeOnRightSide.parent as QualifiedName; } if (nodeOnRightSide.parent.kind === SyntaxKind.ImportEqualsDeclaration) { - return (nodeOnRightSide.parent).moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + return (nodeOnRightSide.parent as ImportEqualsDeclaration).moduleReference === nodeOnRightSide ? nodeOnRightSide.parent as ImportEqualsDeclaration : undefined; } if (nodeOnRightSide.parent.kind === SyntaxKind.ExportAssignment) { - return (nodeOnRightSide.parent).expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; + return (nodeOnRightSide.parent as ExportAssignment).expression === nodeOnRightSide as Node ? nodeOnRightSide.parent as ExportAssignment : undefined; } return undefined; @@ -39240,7 +39238,7 @@ namespace ts { return undefined; } - function getSymbolOfNameOrPropertyAccessExpression(name: EntityName | PrivateIdentifier | PropertyAccessExpression): Symbol | undefined { + function getSymbolOfNameOrPropertyAccessExpression(name: EntityName | PrivateIdentifier | PropertyAccessExpression | JSDocMemberName): Symbol | undefined { if (isDeclarationName(name)) { return getSymbolOfNode(name.parent); } @@ -39249,7 +39247,7 @@ namespace ts { name.parent.kind === SyntaxKind.PropertyAccessExpression && name.parent === (name.parent.parent as BinaryExpression).left) { // Check if this is a special property assignment - if (!isPrivateIdentifier(name)) { + if (!isPrivateIdentifier(name) && !isJSDocMemberName(name)) { const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; @@ -39265,14 +39263,14 @@ namespace ts { return success; } } - else if (!isPropertyAccessExpression(name) && !isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { + else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import const importEqualsDeclaration = getAncestor(name, SyntaxKind.ImportEqualsDeclaration); Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } - if (!isPropertyAccessExpression(name) && !isPrivateIdentifier(name)) { + if (isEntityName(name)) { const possibleImportNode = isImportTypeQualifierPart(name); if (possibleImportNode) { getTypeFromTypeNode(possibleImportNode); @@ -39281,8 +39279,8 @@ namespace ts { } } - while (isRightSideOfQualifiedNameOrPropertyAccess(name)) { - name = name.parent; + while (isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) { + name = name.parent as QualifiedName | PropertyAccessEntityNameExpression | JSDocMemberName; } if (isHeritageClauseElementIdentifier(name)) { @@ -39323,12 +39321,14 @@ namespace ts { return undefined; } + const isJSDoc = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName)); + const meaning = isJSDoc ? SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value : SymbolFlags.Value; if (name.kind === SyntaxKind.Identifier) { if (isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) { - const symbol = getIntrinsicTagSymbol(name.parent); + const symbol = getIntrinsicTagSymbol(name.parent as JsxOpeningLikeElement); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(name, SymbolFlags.Value, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ !isJSDoc, getHostSignatureFromJSDoc(name)); } else if (name.kind === SyntaxKind.PropertyAccessExpression || name.kind === SyntaxKind.QualifiedName) { const links = getNodeLinks(name); @@ -39342,50 +39342,56 @@ namespace ts { else { checkQualifiedName(name, CheckMode.Normal); } + if (!links.resolvedSymbol && isJSDoc && isQualifiedName(name)) { + return resolveJSDocMemberName(name); + } return links.resolvedSymbol; } + else if (isJSDocMemberName(name)) { + return resolveJSDocMemberName(name); + } } - else if (isTypeReferenceIdentifier(name)) { + else if (isTypeReferenceIdentifier(name as EntityName)) { const meaning = name.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(name as EntityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + if (name.parent.kind === SyntaxKind.TypePredicate) { + return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable); } - const jsdocReference = getJSDocEntryNameReference(name); - if (jsdocReference || isJSDocLink(name.parent)) { - const meaning = SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value; - const symbol = resolveEntityName(name as EntityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, getHostSignatureFromJSDoc(name)); - if (symbol) { - return symbol; - } - else if (isQualifiedName(name) && isIdentifier(name.left)) { - // resolve C.m as a static member first - const links = getNodeLinks(name); - if (links.resolvedSymbol) { - return links.resolvedSymbol; - } - checkQualifiedName(name, CheckMode.Normal); - if (links.resolvedSymbol) { - return links.resolvedSymbol; - } + return undefined; + } - // then resolve it as an instance member - const s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); - if (s) { - const t = getDeclaredTypeOfSymbol(s); - return getPropertyOfType(t, name.right.escapedText); - } + /** + * Recursively resolve entity names and jsdoc instance references: + * 1. K#m as K.prototype.m for a class (or other value) K + * 2. K.m as K.prototype.m + * 3. I.m as I.m for a type I, or any other I.m that fails to resolve in (1) or (2) + */ + function resolveJSDocMemberName(name: EntityName | JSDocMemberName): Symbol | undefined { + if (isEntityName(name)) { + const symbol = resolveEntityName( + name, + SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value, + /*ignoreErrors*/ false, + /*dontResolveAlias*/ true, + getHostSignatureFromJSDoc(name)); + if (symbol || isIdentifier(name)) { + // can't recur on identifier, so just return when it's undefined + return symbol; } } - if (name.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(name, /*meaning*/ SymbolFlags.FunctionScopedVariable); + const left = resolveJSDocMemberName(name.left); + if (left) { + const proto = left.flags & SymbolFlags.Value && getPropertyOfType(getTypeOfSymbol(left), "prototype" as __String); + const t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left); + return getPropertyOfType(t, name.right.escapedText); } - - return undefined; } function getSymbolAtLocation(node: Node, ignoreErrors?: boolean): Symbol | undefined { if (node.kind === SyntaxKind.SourceFile) { - return isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + return isExternalModule(node as SourceFile) ? getMergedSymbol(node.symbol) : undefined; } const { parent } = node; const grandParent = parent.parent; @@ -39407,14 +39413,14 @@ namespace ts { } if (node.kind === SyntaxKind.Identifier) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfNameOrPropertyAccessExpression(node); + if (isInRightSideOfImportOrExportAssignment(node as Identifier)) { + return getSymbolOfNameOrPropertyAccessExpression(node as Identifier); } else if (parent.kind === SyntaxKind.BindingElement && grandParent.kind === SyntaxKind.ObjectBindingPattern && - node === (parent).propertyName) { + node === (parent as BindingElement).propertyName) { const typeOfPattern = getTypeOfNode(grandParent); - const propertyDeclaration = getPropertyOfType(typeOfPattern, (node).escapedText); + const propertyDeclaration = getPropertyOfType(typeOfPattern, (node as Identifier).escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -39427,7 +39433,7 @@ namespace ts { case SyntaxKind.PrivateIdentifier: case SyntaxKind.PropertyAccessExpression: case SyntaxKind.QualifiedName: - return getSymbolOfNameOrPropertyAccessExpression(node); + return getSymbolOfNameOrPropertyAccessExpression(node as EntityName | PrivateIdentifier | PropertyAccessExpression); case SyntaxKind.ThisKeyword: const container = getThisContainer(node, /*includeArrowFunctions*/ false); @@ -39452,7 +39458,7 @@ namespace ts { // constructor keyword for an overload, should take us to the definition if it exist const constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === SyntaxKind.Constructor) { - return (constructorDeclaration.parent).symbol; + return (constructorDeclaration.parent as ClassDeclaration).symbol; } return undefined; @@ -39463,11 +39469,11 @@ namespace ts { // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent).moduleSpecifier === node) || + ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent as ImportDeclaration).moduleSpecifier === node) || ((isInJSFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || (isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) ) { - return resolveExternalModuleName(node, node, ignoreErrors); + return resolveExternalModuleName(node, node as LiteralExpression, ignoreErrors); } if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { return getSymbolOfNode(parent); @@ -39501,7 +39507,7 @@ namespace ts { function getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined { if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { - return resolveEntityName((location).name, SymbolFlags.Value | SymbolFlags.Alias); + return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias); } return undefined; } @@ -39531,12 +39537,12 @@ namespace ts { const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (isPartOfTypeNode(node)) { - const typeFromTypeNode = getTypeFromTypeNode(node); + const typeFromTypeNode = getTypeFromTypeNode(node as TypeNode); return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (isExpressionNode(node)) { - return getRegularTypeOfExpression(node); + return getRegularTypeOfExpression(node as Expression); } if (classType && !classDecl!.isImplements) { @@ -39575,7 +39581,7 @@ namespace ts { return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } - if (isInRightSideOfImportOrExportAssignment(node)) { + if (isInRightSideOfImportOrExportAssignment(node as Identifier)) { const symbol = getSymbolAtLocation(node); if (symbol) { const declaredType = getDeclaredTypeOfSymbol(symbol); @@ -39598,13 +39604,13 @@ namespace ts { // for ( { a } of elems) { // } if (expr.parent.kind === SyntaxKind.ForOfStatement) { - const iteratedType = checkRightHandSideOfForOf(expr.parent); + const iteratedType = checkRightHandSideOfForOf(expr.parent as ForOfStatement); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } if (expr.parent.kind === SyntaxKind.BinaryExpression) { - const iteratedType = getTypeOfExpression((expr.parent).right); + const iteratedType = getTypeOfExpression((expr.parent as BinaryExpression).right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern @@ -39637,7 +39643,7 @@ namespace ts { function getRegularTypeOfExpression(expr: Expression): Type { if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; + expr = expr.parent as Expression; } return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } @@ -39788,7 +39794,7 @@ namespace ts { const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration?.kind === SyntaxKind.SourceFile) { - const symbolFile = parentSymbol.valueDeclaration; + const symbolFile = parentSymbol.valueDeclaration as SourceFile; const referenceFile = getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. const symbolIsUmdExport = symbolFile !== referenceFile; @@ -39910,13 +39916,13 @@ namespace ts { const symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); case SyntaxKind.ExportDeclaration: - const exportClause = (node).exportClause; + const exportClause = (node as ExportDeclaration).exportClause; return !!exportClause && ( isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration) ); case SyntaxKind.ExportAssignment: - return (node).expression && (node).expression.kind === SyntaxKind.Identifier ? + return (node as ExportAssignment).expression && (node as ExportAssignment).expression.kind === SyntaxKind.Identifier ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; } @@ -40241,7 +40247,7 @@ namespace ts { function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type, node, tracker); + return literalTypeToNode(type as FreshableType, node, tracker); } function getJsxFactoryEntity(location: Node): EntityName | undefined { @@ -40593,9 +40599,9 @@ namespace ts { autoArrayType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); } - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray" as __String, /*arity*/ 1) || globalArrayType; + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray" as __String, /*arity*/ 1) as GenericType || globalArrayType; anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType" as __String, /*arity*/ 1); + globalThisType = getGlobalTypeOrUndefined("ThisType" as __String, /*arity*/ 1) as GenericType; if (augmentations) { // merge _nonglobal_ module augmentations. @@ -40714,7 +40720,7 @@ namespace ts { return false; } if (!nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === SyntaxKind.MethodDeclaration && !nodeIsPresent((node).body)) { + if (node.kind === SyntaxKind.MethodDeclaration && !nodeIsPresent((node as MethodDeclaration).body)) { return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { @@ -40722,7 +40728,7 @@ namespace ts { } } else if (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor) { - const accessors = getAllAccessorDeclarations((node.parent).members, node); + const accessors = getAllAccessorDeclarations((node.parent as ClassDeclaration).members, node as AccessorDeclaration); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } @@ -40976,10 +40982,10 @@ namespace ts { else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && flags & ModifierFlags.Ambient) { return grammarErrorOnNode(lastDeclare!, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && isBindingPattern((node).name)) { + else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && isBindingPattern((node as ParameterDeclaration).name)) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && (node).dotDotDotToken) { + else if (node.kind === SyntaxKind.Parameter && (flags & ModifierFlags.ParameterPropertyModifier) && (node as ParameterDeclaration).dotDotDotToken) { return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & ModifierFlags.Async) { @@ -41334,8 +41340,8 @@ namespace ts { return false; } - const computedPropertyName = node; - if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && (computedPropertyName.expression).operatorToken.kind === SyntaxKind.CommaToken) { + const computedPropertyName = node as ComputedPropertyName; + if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && (computedPropertyName.expression as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken) { return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; @@ -41435,7 +41441,7 @@ namespace ts { currentKind = DeclarationMeaning.SetAccessor; break; default: - throw Debug.assertNever(prop, "Unexpected syntax kind:" + (prop).kind); + throw Debug.assertNever(prop, "Unexpected syntax kind:" + (prop as Node).kind); } if (!inDestructuring) { @@ -41566,7 +41572,7 @@ namespace ts { } if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - const variableList = forInOrOfStatement.initializer; + const variableList = forInOrOfStatement.initializer as VariableDeclarationList; if (!checkGrammarVariableDeclarationList(variableList)) { const declarations = variableList.declarations; @@ -41692,20 +41698,20 @@ namespace ts { return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); } if (!(decl.parent.flags & NodeFlags.Const)) { - return grammarErrorOnNode((parent).name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + return grammarErrorOnNode((parent as VariableDeclaration).name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; case SyntaxKind.PropertyDeclaration: if (!hasSyntacticModifier(parent, ModifierFlags.Static) || !hasEffectiveModifier(parent, ModifierFlags.Readonly)) { - return grammarErrorOnNode((parent).name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + return grammarErrorOnNode((parent as PropertyDeclaration).name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; case SyntaxKind.PropertySignature: if (!hasSyntacticModifier(parent, ModifierFlags.Readonly)) { - return grammarErrorOnNode((parent).name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + return grammarErrorOnNode((parent as PropertySignature).name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } break; @@ -41785,11 +41791,11 @@ namespace ts { switch (current.kind) { case SyntaxKind.LabeledStatement: - if (node.label && (current).label.escapedText === node.label.escapedText) { + if (node.label && (current as LabeledStatement).label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement - && !isIterationStatement((current).statement, /*lookInLabeledStatement*/ true); + && !isIterationStatement((current as LabeledStatement).statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -41851,14 +41857,14 @@ namespace ts { function isStringOrNumberLiteralExpression(expr: Expression) { return isStringOrNumericLiteralLike(expr) || - expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && - (expr).operand.kind === SyntaxKind.NumericLiteral; + expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && + (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.NumericLiteral; } function isBigIntLiteralExpression(expr: Expression) { return expr.kind === SyntaxKind.BigIntLiteral || - expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && - (expr).operand.kind === SyntaxKind.BigIntLiteral; + expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && + (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.BigIntLiteral; } function isSimpleLiteralEnumReference(expr: Expression) { @@ -42381,7 +42387,7 @@ namespace ts { // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source: Type, target: Type, isRelatedTo: (source: Type, target: Type) => Ternary, skipPartial?: boolean) { if (target.flags & TypeFlags.Union && source.flags & (TypeFlags.Intersection | TypeFlags.Object)) { - const match = getMatchingUnionConstituentForType(target, source); + const match = getMatchingUnionConstituentForType(target as UnionType, source); if (match) { return match; } @@ -42389,7 +42395,7 @@ namespace ts { if (sourceProperties) { const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo, /*defaultValue*/ undefined, skipPartial); + return discriminateTypeByDiscriminableItems(target as UnionType, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 253e38a5295b5..ffd43b9d7d51e 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1287,7 +1287,7 @@ namespace ts { case "string": return mapDefined(values, v => validateJsonOptionValue(opt.element, v || "", errors)); default: - return mapDefined(values, v => parseCustomTypeOption(opt.element, v, errors)); + return mapDefined(values, v => parseCustomTypeOption(opt.element as CommandLineOptionOfCustomType, v, errors)); } } @@ -1466,7 +1466,7 @@ namespace ts { break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: - options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + options[opt.name] = parseCustomTypeOption(opt as CommandLineOptionOfCustomType, args[i], errors); i++; break; } @@ -1570,7 +1570,7 @@ namespace ts { /* @internal */ export function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); - return diagnostic.messageText; + return diagnostic.messageText as string; } export type DiagnosticReporter = (diagnostic: Diagnostic) => void; @@ -1654,7 +1654,7 @@ namespace ts { */ export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile { const textOrDiagnostic = tryReadFile(fileName, readFile); - return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] }; + return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] } as TsConfigSourceFile; } /*@internal*/ @@ -1961,9 +1961,9 @@ namespace ts { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected)); } reportInvalidOptionValue(option && (isString(option.type) && option.type !== "string")); - const text = (valueExpression).text; + const text = (valueExpression as StringLiteral).text; if (option && !isString(option.type)) { - const customOption = option; + const customOption = option as CommandLineOptionOfCustomType; // Validate custom option type if (!customOption.type.has(text.toLowerCase())) { errors.push( @@ -1979,18 +1979,18 @@ namespace ts { case SyntaxKind.NumericLiteral: reportInvalidOptionValue(option && option.type !== "number"); - return validateValue(Number((valueExpression).text)); + return validateValue(Number((valueExpression as NumericLiteral).text)); case SyntaxKind.PrefixUnaryExpression: - if ((valueExpression).operator !== SyntaxKind.MinusToken || (valueExpression).operand.kind !== SyntaxKind.NumericLiteral) { + if ((valueExpression as PrefixUnaryExpression).operator !== SyntaxKind.MinusToken || (valueExpression as PrefixUnaryExpression).operand.kind !== SyntaxKind.NumericLiteral) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); - return validateValue(-Number(((valueExpression).operand).text)); + return validateValue(-Number(((valueExpression as PrefixUnaryExpression).operand as NumericLiteral).text)); case SyntaxKind.ObjectLiteralExpression: reportInvalidOptionValue(option && option.type !== "object"); - const objectLiteralExpression = valueExpression; + const objectLiteralExpression = valueExpression as ObjectLiteralExpression; // Currently having element option declaration in the tsconfig with type "object" // determines if it needs onSetValidOptionKeyValueInParent callback or not @@ -1999,7 +1999,7 @@ namespace ts { // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed if (option) { - const { elementOptions, extraKeyDiagnostics, name: optionName } = option; + const { elementOptions, extraKeyDiagnostics, name: optionName } = option as TsConfigOnlyOption; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName)); } @@ -2012,8 +2012,8 @@ namespace ts { case SyntaxKind.ArrayLiteralExpression: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson( - (valueExpression).elements, - option && (option).element)); + (valueExpression as ArrayLiteralExpression).elements, + option && (option as CommandLineOptionOfListType).element)); } // Not in expected format @@ -2172,7 +2172,7 @@ namespace ts { return getCustomTypeMapOfCommandLineOption(optionDefinition.element); } else { - return (optionDefinition).type; + return (optionDefinition as CommandLineOptionOfCustomType).type; } } @@ -2211,7 +2211,7 @@ namespace ts { if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) { continue; } - const value = options[name]; + const value = options[name] as CompilerOptionsValue; const optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); @@ -2782,7 +2782,7 @@ namespace ts { case "extends": const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; extendedConfigPath = getExtendsConfigPath( - value, + value as string, host, newBase, errors, @@ -2972,10 +2972,10 @@ namespace ts { if (isCompilerOptionsValue(opt, value)) { const optType = opt.type; if (optType === "list" && isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); + return convertJsonOptionOfListType(opt as CommandLineOptionOfListType, value, basePath, errors); } else if (!isString(optType)) { - return convertJsonOptionOfCustomType(opt, value, errors); + return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors); } const validatedValue = validateJsonOptionValue(opt, value, errors); return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue); @@ -2990,7 +2990,7 @@ namespace ts { if (option.type === "list") { const listOption = option; if (listOption.element.isFilePath || !isString(listOption.element.type)) { - return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v); + return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v) as CompilerOptionsValue; } return value; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index dafda8263ad89..0c95903cc2748 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1429,7 +1429,7 @@ namespace ts { const result: any = {}; for (const id in object) { if (hasOwnProperty.call(object, id)) { - result[id] = (object)[id]; + result[id] = (object as any)[id]; } } return result; @@ -1441,7 +1441,7 @@ namespace ts { * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. */ export function extend(first: T1, second: T2): T1 & T2 { - const result: T1 & T2 = {}; + const result: T1 & T2 = {} as any; for (const id in second) { if (hasOwnProperty.call(second, id)) { (result as any)[id] = (second as any)[id]; diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index adf968fe2c7bd..97cb4f3687f6d 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -112,8 +112,8 @@ namespace ts { export function fail(message?: string, stackCrawlMark?: AnyFunction): never { debugger; const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure."); - if ((Error).captureStackTrace) { - (Error).captureStackTrace(e, stackCrawlMark || fail); + if ((Error as any).captureStackTrace) { + (Error as any).captureStackTrace(e, stackCrawlMark || fail); } throw e; } @@ -288,7 +288,7 @@ namespace ts { return ""; } else if (func.hasOwnProperty("name")) { - return (func).name; + return (func as any).name; } else { const text = Function.prototype.toString.call(func); @@ -348,43 +348,43 @@ namespace ts { } export function formatSyntaxKind(kind: SyntaxKind | undefined): string { - return formatEnum(kind, (ts).SyntaxKind, /*isFlags*/ false); + return formatEnum(kind, (ts as any).SyntaxKind, /*isFlags*/ false); } export function formatNodeFlags(flags: NodeFlags | undefined): string { - return formatEnum(flags, (ts).NodeFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true); } export function formatModifierFlags(flags: ModifierFlags | undefined): string { - return formatEnum(flags, (ts).ModifierFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).ModifierFlags, /*isFlags*/ true); } export function formatTransformFlags(flags: TransformFlags | undefined): string { - return formatEnum(flags, (ts).TransformFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).TransformFlags, /*isFlags*/ true); } export function formatEmitFlags(flags: EmitFlags | undefined): string { - return formatEnum(flags, (ts).EmitFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).EmitFlags, /*isFlags*/ true); } export function formatSymbolFlags(flags: SymbolFlags | undefined): string { - return formatEnum(flags, (ts).SymbolFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).SymbolFlags, /*isFlags*/ true); } export function formatTypeFlags(flags: TypeFlags | undefined): string { - return formatEnum(flags, (ts).TypeFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).TypeFlags, /*isFlags*/ true); } export function formatSignatureFlags(flags: SignatureFlags | undefined): string { - return formatEnum(flags, (ts).SignatureFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).SignatureFlags, /*isFlags*/ true); } export function formatObjectFlags(flags: ObjectFlags | undefined): string { - return formatEnum(flags, (ts).ObjectFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).ObjectFlags, /*isFlags*/ true); } export function formatFlowFlags(flags: FlowFlags | undefined): string { - return formatEnum(flags, (ts).FlowFlags, /*isFlags*/ true); + return formatEnum(flags, (ts as any).FlowFlags, /*isFlags*/ true); } let isDebugInfoEnabled = false; @@ -570,7 +570,7 @@ namespace ts { } }, __debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((this).objectFlags) : ""; } }, + __debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((this as ObjectType).objectFlags) : ""; } }, __debugTypeToString: { value(this: Type) { // avoid recomputing diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 5c8810f5ea8ca..0c766fbde12c9 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -15,7 +15,7 @@ "category": "Error", "code": 1006 }, - "The parser expected to find a '{1}' to match the '{0}' token here.": { + "The parser expected to find a '}' to match the '{' token here.": { "category": "Error", "code": 1007 }, @@ -887,6 +887,10 @@ "category": "Error", "code": 1266 }, + "Property '{0}' cannot have an initializer because it is marked abstract.": { + "category": "Error", + "code": 1267 + }, "'with' statements are not allowed in an async function block.": { "category": "Error", @@ -6393,6 +6397,10 @@ "category": "Message", "code": 95163 }, + "Can only convert named export": { + "category": "Message", + "code": 95164 + }, "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": { "category": "Error", diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index a3007559f0dd9..7bb3d8f75770f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -959,9 +959,9 @@ namespace ts { break; } switch (node.kind) { - case SyntaxKind.SourceFile: return printFile(node); - case SyntaxKind.Bundle: return printBundle(node); - case SyntaxKind.UnparsedSource: return printUnparsedSource(node); + case SyntaxKind.SourceFile: return printFile(node as SourceFile); + case SyntaxKind.Bundle: return printBundle(node as Bundle); + case SyntaxKind.UnparsedSource: return printUnparsedSource(node as UnparsedSource); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -1317,11 +1317,11 @@ namespace ts { case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: case SyntaxKind.TemplateTail: - return emitLiteral(node, /*jsxAttributeEscape*/ false); + return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false); // Identifiers case SyntaxKind.Identifier: - return emitIdentifier(node); + return emitIdentifier(node as Identifier); // PrivateIdentifiers case SyntaxKind.PrivateIdentifier: @@ -1330,251 +1330,251 @@ namespace ts { // Parse tree nodes // Names case SyntaxKind.QualifiedName: - return emitQualifiedName(node); + return emitQualifiedName(node as QualifiedName); case SyntaxKind.ComputedPropertyName: - return emitComputedPropertyName(node); + return emitComputedPropertyName(node as ComputedPropertyName); // Signature elements case SyntaxKind.TypeParameter: - return emitTypeParameter(node); + return emitTypeParameter(node as TypeParameterDeclaration); case SyntaxKind.Parameter: - return emitParameter(node); + return emitParameter(node as ParameterDeclaration); case SyntaxKind.Decorator: - return emitDecorator(node); + return emitDecorator(node as Decorator); // Type members case SyntaxKind.PropertySignature: - return emitPropertySignature(node); + return emitPropertySignature(node as PropertySignature); case SyntaxKind.PropertyDeclaration: - return emitPropertyDeclaration(node); + return emitPropertyDeclaration(node as PropertyDeclaration); case SyntaxKind.MethodSignature: - return emitMethodSignature(node); + return emitMethodSignature(node as MethodSignature); case SyntaxKind.MethodDeclaration: - return emitMethodDeclaration(node); + return emitMethodDeclaration(node as MethodDeclaration); case SyntaxKind.Constructor: - return emitConstructor(node); + return emitConstructor(node as ConstructorDeclaration); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return emitAccessorDeclaration(node); + return emitAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.CallSignature: - return emitCallSignature(node); + return emitCallSignature(node as CallSignatureDeclaration); case SyntaxKind.ConstructSignature: - return emitConstructSignature(node); + return emitConstructSignature(node as ConstructSignatureDeclaration); case SyntaxKind.IndexSignature: - return emitIndexSignature(node); + return emitIndexSignature(node as IndexSignatureDeclaration); // Types case SyntaxKind.TypePredicate: - return emitTypePredicate(node); + return emitTypePredicate(node as TypePredicateNode); case SyntaxKind.TypeReference: - return emitTypeReference(node); + return emitTypeReference(node as TypeReferenceNode); case SyntaxKind.FunctionType: - return emitFunctionType(node); + return emitFunctionType(node as FunctionTypeNode); case SyntaxKind.ConstructorType: - return emitConstructorType(node); + return emitConstructorType(node as ConstructorTypeNode); case SyntaxKind.TypeQuery: - return emitTypeQuery(node); + return emitTypeQuery(node as TypeQueryNode); case SyntaxKind.TypeLiteral: - return emitTypeLiteral(node); + return emitTypeLiteral(node as TypeLiteralNode); case SyntaxKind.ArrayType: - return emitArrayType(node); + return emitArrayType(node as ArrayTypeNode); case SyntaxKind.TupleType: - return emitTupleType(node); + return emitTupleType(node as TupleTypeNode); case SyntaxKind.OptionalType: - return emitOptionalType(node); + return emitOptionalType(node as OptionalTypeNode); // SyntaxKind.RestType is handled below case SyntaxKind.UnionType: - return emitUnionType(node); + return emitUnionType(node as UnionTypeNode); case SyntaxKind.IntersectionType: - return emitIntersectionType(node); + return emitIntersectionType(node as IntersectionTypeNode); case SyntaxKind.ConditionalType: - return emitConditionalType(node); + return emitConditionalType(node as ConditionalTypeNode); case SyntaxKind.InferType: - return emitInferType(node); + return emitInferType(node as InferTypeNode); case SyntaxKind.ParenthesizedType: - return emitParenthesizedType(node); + return emitParenthesizedType(node as ParenthesizedTypeNode); case SyntaxKind.ExpressionWithTypeArguments: - return emitExpressionWithTypeArguments(node); + return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments); case SyntaxKind.ThisType: return emitThisType(); case SyntaxKind.TypeOperator: - return emitTypeOperator(node); + return emitTypeOperator(node as TypeOperatorNode); case SyntaxKind.IndexedAccessType: - return emitIndexedAccessType(node); + return emitIndexedAccessType(node as IndexedAccessTypeNode); case SyntaxKind.MappedType: - return emitMappedType(node); + return emitMappedType(node as MappedTypeNode); case SyntaxKind.LiteralType: - return emitLiteralType(node); + return emitLiteralType(node as LiteralTypeNode); case SyntaxKind.NamedTupleMember: return emitNamedTupleMember(node as NamedTupleMember); case SyntaxKind.TemplateLiteralType: - return emitTemplateType(node); + return emitTemplateType(node as TemplateLiteralTypeNode); case SyntaxKind.TemplateLiteralTypeSpan: - return emitTemplateTypeSpan(node); + return emitTemplateTypeSpan(node as TemplateLiteralTypeSpan); case SyntaxKind.ImportType: - return emitImportTypeNode(node); + return emitImportTypeNode(node as ImportTypeNode); // Binding patterns case SyntaxKind.ObjectBindingPattern: - return emitObjectBindingPattern(node); + return emitObjectBindingPattern(node as ObjectBindingPattern); case SyntaxKind.ArrayBindingPattern: - return emitArrayBindingPattern(node); + return emitArrayBindingPattern(node as ArrayBindingPattern); case SyntaxKind.BindingElement: - return emitBindingElement(node); + return emitBindingElement(node as BindingElement); // Misc case SyntaxKind.TemplateSpan: - return emitTemplateSpan(node); + return emitTemplateSpan(node as TemplateSpan); case SyntaxKind.SemicolonClassElement: return emitSemicolonClassElement(); // Statements case SyntaxKind.Block: - return emitBlock(node); + return emitBlock(node as Block); case SyntaxKind.VariableStatement: - return emitVariableStatement(node); + return emitVariableStatement(node as VariableStatement); case SyntaxKind.EmptyStatement: return emitEmptyStatement(/*isEmbeddedStatement*/ false); case SyntaxKind.ExpressionStatement: - return emitExpressionStatement(node); + return emitExpressionStatement(node as ExpressionStatement); case SyntaxKind.IfStatement: - return emitIfStatement(node); + return emitIfStatement(node as IfStatement); case SyntaxKind.DoStatement: - return emitDoStatement(node); + return emitDoStatement(node as DoStatement); case SyntaxKind.WhileStatement: - return emitWhileStatement(node); + return emitWhileStatement(node as WhileStatement); case SyntaxKind.ForStatement: - return emitForStatement(node); + return emitForStatement(node as ForStatement); case SyntaxKind.ForInStatement: - return emitForInStatement(node); + return emitForInStatement(node as ForInStatement); case SyntaxKind.ForOfStatement: - return emitForOfStatement(node); + return emitForOfStatement(node as ForOfStatement); case SyntaxKind.ContinueStatement: - return emitContinueStatement(node); + return emitContinueStatement(node as ContinueStatement); case SyntaxKind.BreakStatement: - return emitBreakStatement(node); + return emitBreakStatement(node as BreakStatement); case SyntaxKind.ReturnStatement: - return emitReturnStatement(node); + return emitReturnStatement(node as ReturnStatement); case SyntaxKind.WithStatement: - return emitWithStatement(node); + return emitWithStatement(node as WithStatement); case SyntaxKind.SwitchStatement: - return emitSwitchStatement(node); + return emitSwitchStatement(node as SwitchStatement); case SyntaxKind.LabeledStatement: - return emitLabeledStatement(node); + return emitLabeledStatement(node as LabeledStatement); case SyntaxKind.ThrowStatement: - return emitThrowStatement(node); + return emitThrowStatement(node as ThrowStatement); case SyntaxKind.TryStatement: - return emitTryStatement(node); + return emitTryStatement(node as TryStatement); case SyntaxKind.DebuggerStatement: - return emitDebuggerStatement(node); + return emitDebuggerStatement(node as DebuggerStatement); // Declarations case SyntaxKind.VariableDeclaration: - return emitVariableDeclaration(node); + return emitVariableDeclaration(node as VariableDeclaration); case SyntaxKind.VariableDeclarationList: - return emitVariableDeclarationList(node); + return emitVariableDeclarationList(node as VariableDeclarationList); case SyntaxKind.FunctionDeclaration: - return emitFunctionDeclaration(node); + return emitFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.ClassDeclaration: - return emitClassDeclaration(node); + return emitClassDeclaration(node as ClassDeclaration); case SyntaxKind.InterfaceDeclaration: - return emitInterfaceDeclaration(node); + return emitInterfaceDeclaration(node as InterfaceDeclaration); case SyntaxKind.TypeAliasDeclaration: - return emitTypeAliasDeclaration(node); + return emitTypeAliasDeclaration(node as TypeAliasDeclaration); case SyntaxKind.EnumDeclaration: - return emitEnumDeclaration(node); + return emitEnumDeclaration(node as EnumDeclaration); case SyntaxKind.ModuleDeclaration: - return emitModuleDeclaration(node); + return emitModuleDeclaration(node as ModuleDeclaration); case SyntaxKind.ModuleBlock: - return emitModuleBlock(node); + return emitModuleBlock(node as ModuleBlock); case SyntaxKind.CaseBlock: - return emitCaseBlock(node); + return emitCaseBlock(node as CaseBlock); case SyntaxKind.NamespaceExportDeclaration: - return emitNamespaceExportDeclaration(node); + return emitNamespaceExportDeclaration(node as NamespaceExportDeclaration); case SyntaxKind.ImportEqualsDeclaration: - return emitImportEqualsDeclaration(node); + return emitImportEqualsDeclaration(node as ImportEqualsDeclaration); case SyntaxKind.ImportDeclaration: - return emitImportDeclaration(node); + return emitImportDeclaration(node as ImportDeclaration); case SyntaxKind.ImportClause: - return emitImportClause(node); + return emitImportClause(node as ImportClause); case SyntaxKind.NamespaceImport: - return emitNamespaceImport(node); + return emitNamespaceImport(node as NamespaceImport); case SyntaxKind.NamespaceExport: - return emitNamespaceExport(node); + return emitNamespaceExport(node as NamespaceExport); case SyntaxKind.NamedImports: - return emitNamedImports(node); + return emitNamedImports(node as NamedImports); case SyntaxKind.ImportSpecifier: - return emitImportSpecifier(node); + return emitImportSpecifier(node as ImportSpecifier); case SyntaxKind.ExportAssignment: - return emitExportAssignment(node); + return emitExportAssignment(node as ExportAssignment); case SyntaxKind.ExportDeclaration: - return emitExportDeclaration(node); + return emitExportDeclaration(node as ExportDeclaration); case SyntaxKind.NamedExports: - return emitNamedExports(node); + return emitNamedExports(node as NamedExports); case SyntaxKind.ExportSpecifier: - return emitExportSpecifier(node); + return emitExportSpecifier(node as ExportSpecifier); case SyntaxKind.MissingDeclaration: return; // Module references case SyntaxKind.ExternalModuleReference: - return emitExternalModuleReference(node); + return emitExternalModuleReference(node as ExternalModuleReference); // JSX (non-expression) case SyntaxKind.JsxText: - return emitJsxText(node); + return emitJsxText(node as JsxText); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxOpeningFragment: - return emitJsxOpeningElementOrFragment(node); + return emitJsxOpeningElementOrFragment(node as JsxOpeningElement); case SyntaxKind.JsxClosingElement: case SyntaxKind.JsxClosingFragment: - return emitJsxClosingElementOrFragment(node); + return emitJsxClosingElementOrFragment(node as JsxClosingElement); case SyntaxKind.JsxAttribute: - return emitJsxAttribute(node); + return emitJsxAttribute(node as JsxAttribute); case SyntaxKind.JsxAttributes: - return emitJsxAttributes(node); + return emitJsxAttributes(node as JsxAttributes); case SyntaxKind.JsxSpreadAttribute: - return emitJsxSpreadAttribute(node); + return emitJsxSpreadAttribute(node as JsxSpreadAttribute); case SyntaxKind.JsxExpression: - return emitJsxExpression(node); + return emitJsxExpression(node as JsxExpression); // Clauses case SyntaxKind.CaseClause: - return emitCaseClause(node); + return emitCaseClause(node as CaseClause); case SyntaxKind.DefaultClause: - return emitDefaultClause(node); + return emitDefaultClause(node as DefaultClause); case SyntaxKind.HeritageClause: - return emitHeritageClause(node); + return emitHeritageClause(node as HeritageClause); case SyntaxKind.CatchClause: - return emitCatchClause(node); + return emitCatchClause(node as CatchClause); // Property assignments case SyntaxKind.PropertyAssignment: - return emitPropertyAssignment(node); + return emitPropertyAssignment(node as PropertyAssignment); case SyntaxKind.ShorthandPropertyAssignment: - return emitShorthandPropertyAssignment(node); + return emitShorthandPropertyAssignment(node as ShorthandPropertyAssignment); case SyntaxKind.SpreadAssignment: return emitSpreadAssignment(node as SpreadAssignment); // Enum case SyntaxKind.EnumMember: - return emitEnumMember(node); + return emitEnumMember(node as EnumMember); // Unparsed case SyntaxKind.UnparsedPrologue: - return writeUnparsedNode(node); + return writeUnparsedNode(node as UnparsedNode); case SyntaxKind.UnparsedSource: case SyntaxKind.UnparsedPrepend: - return emitUnparsedSourceOrPrepend(node); + return emitUnparsedSourceOrPrepend(node as UnparsedSource); case SyntaxKind.UnparsedText: case SyntaxKind.UnparsedInternalText: - return emitUnparsedTextLike(node); + return emitUnparsedTextLike(node as UnparsedTextLike); case SyntaxKind.UnparsedSyntheticReference: - return emitUnparsedSyntheticReference(node); + return emitUnparsedSyntheticReference(node as UnparsedSyntheticReference); // Top-level nodes case SyntaxKind.SourceFile: - return emitSourceFile(node); + return emitSourceFile(node as SourceFile); case SyntaxKind.Bundle: return Debug.fail("Bundles should be printed using printBundle"); // SyntaxKind.UnparsedSource (handled above) @@ -1668,82 +1668,82 @@ namespace ts { // Literals case SyntaxKind.NumericLiteral: case SyntaxKind.BigIntLiteral: - return emitNumericOrBigIntLiteral(node); + return emitNumericOrBigIntLiteral(node as NumericLiteral | BigIntLiteral); case SyntaxKind.StringLiteral: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: - return emitLiteral(node, /*jsxAttributeEscape*/ false); + return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false); // Identifiers case SyntaxKind.Identifier: - return emitIdentifier(node); + return emitIdentifier(node as Identifier); // Expressions case SyntaxKind.ArrayLiteralExpression: - return emitArrayLiteralExpression(node); + return emitArrayLiteralExpression(node as ArrayLiteralExpression); case SyntaxKind.ObjectLiteralExpression: - return emitObjectLiteralExpression(node); + return emitObjectLiteralExpression(node as ObjectLiteralExpression); case SyntaxKind.PropertyAccessExpression: - return emitPropertyAccessExpression(node); + return emitPropertyAccessExpression(node as PropertyAccessExpression); case SyntaxKind.ElementAccessExpression: - return emitElementAccessExpression(node); + return emitElementAccessExpression(node as ElementAccessExpression); case SyntaxKind.CallExpression: - return emitCallExpression(node); + return emitCallExpression(node as CallExpression); case SyntaxKind.NewExpression: - return emitNewExpression(node); + return emitNewExpression(node as NewExpression); case SyntaxKind.TaggedTemplateExpression: - return emitTaggedTemplateExpression(node); + return emitTaggedTemplateExpression(node as TaggedTemplateExpression); case SyntaxKind.TypeAssertionExpression: - return emitTypeAssertionExpression(node); + return emitTypeAssertionExpression(node as TypeAssertion); case SyntaxKind.ParenthesizedExpression: - return emitParenthesizedExpression(node); + return emitParenthesizedExpression(node as ParenthesizedExpression); case SyntaxKind.FunctionExpression: - return emitFunctionExpression(node); + return emitFunctionExpression(node as FunctionExpression); case SyntaxKind.ArrowFunction: - return emitArrowFunction(node); + return emitArrowFunction(node as ArrowFunction); case SyntaxKind.DeleteExpression: - return emitDeleteExpression(node); + return emitDeleteExpression(node as DeleteExpression); case SyntaxKind.TypeOfExpression: - return emitTypeOfExpression(node); + return emitTypeOfExpression(node as TypeOfExpression); case SyntaxKind.VoidExpression: - return emitVoidExpression(node); + return emitVoidExpression(node as VoidExpression); case SyntaxKind.AwaitExpression: - return emitAwaitExpression(node); + return emitAwaitExpression(node as AwaitExpression); case SyntaxKind.PrefixUnaryExpression: - return emitPrefixUnaryExpression(node); + return emitPrefixUnaryExpression(node as PrefixUnaryExpression); case SyntaxKind.PostfixUnaryExpression: - return emitPostfixUnaryExpression(node); + return emitPostfixUnaryExpression(node as PostfixUnaryExpression); case SyntaxKind.BinaryExpression: - return emitBinaryExpression(node); + return emitBinaryExpression(node as BinaryExpression); case SyntaxKind.ConditionalExpression: - return emitConditionalExpression(node); + return emitConditionalExpression(node as ConditionalExpression); case SyntaxKind.TemplateExpression: - return emitTemplateExpression(node); + return emitTemplateExpression(node as TemplateExpression); case SyntaxKind.YieldExpression: - return emitYieldExpression(node); + return emitYieldExpression(node as YieldExpression); case SyntaxKind.SpreadElement: - return emitSpreadElement(node); + return emitSpreadElement(node as SpreadElement); case SyntaxKind.ClassExpression: - return emitClassExpression(node); + return emitClassExpression(node as ClassExpression); case SyntaxKind.OmittedExpression: return; case SyntaxKind.AsExpression: - return emitAsExpression(node); + return emitAsExpression(node as AsExpression); case SyntaxKind.NonNullExpression: - return emitNonNullExpression(node); + return emitNonNullExpression(node as NonNullExpression); case SyntaxKind.MetaProperty: - return emitMetaProperty(node); + return emitMetaProperty(node as MetaProperty); case SyntaxKind.SyntheticExpression: return Debug.fail("SyntheticExpression should never be printed."); // JSX case SyntaxKind.JsxElement: - return emitJsxElement(node); + return emitJsxElement(node as JsxElement); case SyntaxKind.JsxSelfClosingElement: - return emitJsxSelfClosingElement(node); + return emitJsxSelfClosingElement(node as JsxSelfClosingElement); case SyntaxKind.JsxFragment: - return emitJsxFragment(node); + return emitJsxFragment(node as JsxFragment); // Synthesized list case SyntaxKind.SyntaxList: @@ -1753,9 +1753,9 @@ namespace ts { case SyntaxKind.NotEmittedStatement: return; case SyntaxKind.PartiallyEmittedExpression: - return emitPartiallyEmittedExpression(node); + return emitPartiallyEmittedExpression(node as PartiallyEmittedExpression); case SyntaxKind.CommaListExpression: - return emitCommaList(node); + return emitCommaList(node as CommaListExpression); case SyntaxKind.MergeDeclarationMarker: case SyntaxKind.EndOfDeclarationMarker: return; @@ -1807,7 +1807,7 @@ namespace ts { function emitHelpers(node: Node) { let helpersEmitted = false; - const bundle = node.kind === SyntaxKind.Bundle ? node : undefined; + const bundle = node.kind === SyntaxKind.Bundle ? node as Bundle : undefined; if (bundle && moduleKind === ModuleKind.None) { return; } @@ -2450,7 +2450,7 @@ namespace ts { expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false); + const text = getLiteralTextOfNode(expression as LiteralExpression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false); // If he number will be printed verbatim and it doesn't already contain a dot, add one // if the expression doesn't have any comments that will be emitted. return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!); @@ -2576,8 +2576,8 @@ namespace ts { // The same is true of minus of course. const operand = node.operand; return operand.kind === SyntaxKind.PrefixUnaryExpression - && ((node.operator === SyntaxKind.PlusToken && ((operand).operator === SyntaxKind.PlusToken || (operand).operator === SyntaxKind.PlusPlusToken)) - || (node.operator === SyntaxKind.MinusToken && ((operand).operator === SyntaxKind.MinusToken || (operand).operator === SyntaxKind.MinusMinusToken))); + && ((node.operator === SyntaxKind.PlusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.PlusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.PlusPlusToken)) + || (node.operator === SyntaxKind.MinusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.MinusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.MinusMinusToken))); } function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { @@ -3785,7 +3785,7 @@ namespace ts { emit(tagName); } - function emitJSDocComment(comment: string | NodeArray | undefined) { + function emitJSDocComment(comment: string | NodeArray | undefined) { const text = getTextOfJSDocComment(comment); if (text) { writeSpace(); @@ -4705,7 +4705,7 @@ namespace ts { function skipSynthesizedParentheses(node: Node) { while (node.kind === SyntaxKind.ParenthesizedExpression && nodeIsSynthesized(node)) { - node = (node).expression; + node = (node as ParenthesizedExpression).expression; } return node; @@ -4718,8 +4718,8 @@ namespace ts { else if ((isIdentifier(node) || isPrivateIdentifier(node)) && (nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && getSourceFileOfNode(node) !== getOriginalNode(currentSourceFile)))) { return idText(node); } - else if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { - return getTextOfNode((node).textSourceNode!, includeTrivia); + else if (node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).textSourceNode) { + return getTextOfNode((node as StringLiteral).textSourceNode!, includeTrivia); } else if (isLiteralExpression(node) && (nodeIsSynthesized(node) || !node.parent)) { return node.text; @@ -4729,8 +4729,8 @@ namespace ts { } function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean): string { - if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { - const textSourceNode = (node).textSourceNode!; + if (node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).textSourceNode) { + const textSourceNode = (node as StringLiteral).textSourceNode!; if (isIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode); return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : @@ -4784,84 +4784,84 @@ namespace ts { if (!node) return; switch (node.kind) { case SyntaxKind.Block: - forEach((node).statements, generateNames); + forEach((node as Block).statements, generateNames); break; case SyntaxKind.LabeledStatement: case SyntaxKind.WithStatement: case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - generateNames((node).statement); + generateNames((node as LabeledStatement | WithStatement | DoStatement | WhileStatement).statement); break; case SyntaxKind.IfStatement: - generateNames((node).thenStatement); - generateNames((node).elseStatement); + generateNames((node as IfStatement).thenStatement); + generateNames((node as IfStatement).elseStatement); break; case SyntaxKind.ForStatement: case SyntaxKind.ForOfStatement: case SyntaxKind.ForInStatement: - generateNames((node).initializer); - generateNames((node).statement); + generateNames((node as ForStatement | ForInOrOfStatement).initializer); + generateNames((node as ForStatement | ForInOrOfStatement).statement); break; case SyntaxKind.SwitchStatement: - generateNames((node).caseBlock); + generateNames((node as SwitchStatement).caseBlock); break; case SyntaxKind.CaseBlock: - forEach((node).clauses, generateNames); + forEach((node as CaseBlock).clauses, generateNames); break; case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: - forEach((node).statements, generateNames); + forEach((node as CaseOrDefaultClause).statements, generateNames); break; case SyntaxKind.TryStatement: - generateNames((node).tryBlock); - generateNames((node).catchClause); - generateNames((node).finallyBlock); + generateNames((node as TryStatement).tryBlock); + generateNames((node as TryStatement).catchClause); + generateNames((node as TryStatement).finallyBlock); break; case SyntaxKind.CatchClause: - generateNames((node).variableDeclaration); - generateNames((node).block); + generateNames((node as CatchClause).variableDeclaration); + generateNames((node as CatchClause).block); break; case SyntaxKind.VariableStatement: - generateNames((node).declarationList); + generateNames((node as VariableStatement).declarationList); break; case SyntaxKind.VariableDeclarationList: - forEach((node).declarations, generateNames); + forEach((node as VariableDeclarationList).declarations, generateNames); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: - generateNameIfNeeded((node).name); + generateNameIfNeeded((node as NamedDeclaration).name); break; case SyntaxKind.FunctionDeclaration: - generateNameIfNeeded((node).name); + generateNameIfNeeded((node as FunctionDeclaration).name); if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) { - forEach((node).parameters, generateNames); - generateNames((node).body); + forEach((node as FunctionDeclaration).parameters, generateNames); + generateNames((node as FunctionDeclaration).body); } break; case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: - forEach((node).elements, generateNames); + forEach((node as BindingPattern).elements, generateNames); break; case SyntaxKind.ImportDeclaration: - generateNames((node).importClause); + generateNames((node as ImportDeclaration).importClause); break; case SyntaxKind.ImportClause: - generateNameIfNeeded((node).name); - generateNames((node).namedBindings); + generateNameIfNeeded((node as ImportClause).name); + generateNames((node as ImportClause).namedBindings); break; case SyntaxKind.NamespaceImport: - generateNameIfNeeded((node).name); + generateNameIfNeeded((node as NamespaceImport).name); break; case SyntaxKind.NamespaceExport: - generateNameIfNeeded((node).name); + generateNameIfNeeded((node as NamespaceExport).name); break; case SyntaxKind.NamedImports: - forEach((node).elements, generateNames); + forEach((node as NamedImports).elements, generateNames); break; case SyntaxKind.ImportSpecifier: - generateNameIfNeeded((node).propertyName || (node).name); + generateNameIfNeeded((node as ImportSpecifier).propertyName || (node as ImportSpecifier).name); break; } } @@ -4875,7 +4875,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - generateNameIfNeeded((node).name); + generateNameIfNeeded((node as NamedDeclaration).name); break; } } @@ -5077,10 +5077,10 @@ namespace ts { ); case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: - return generateNameForModuleOrEnum(node); + return generateNameForModuleOrEnum(node as ModuleDeclaration | EnumDeclaration); case SyntaxKind.ImportDeclaration: case SyntaxKind.ExportDeclaration: - return generateNameForImportOrExportDeclaration(node); + return generateNameForImportOrExportDeclaration(node as ImportDeclaration | ExportDeclaration); case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.ExportAssignment: @@ -5090,7 +5090,7 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return generateNameForMethodOrAccessor(node); + return generateNameForMethodOrAccessor(node as MethodDeclaration | AccessorDeclaration); case SyntaxKind.ComputedPropertyName: return makeTempVariableName(TempFlags.Auto, /*reserveInNestedScopes*/ true); default: diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 0989a504e6e5b..4b75321a84ee2 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -34,10 +34,10 @@ namespace ts { const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => () => createJSDocPrimaryTypeWorker(kind)); const getJSDocUnaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => (type: T["type"]) => createJSDocUnaryTypeWorker(kind, type)); const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocUnaryTypeWorker(kind, node, type)); - const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray) => createJSDocSimpleTagWorker(kind, tagName, comment)); - const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); - const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); - const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray) => createJSDocSimpleTagWorker(kind, tagName, comment)); + const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); + const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); const factory: NodeFactory = { get parenthesizer() { return parenthesizerRules(); }, @@ -345,8 +345,14 @@ namespace ts { updateJSDocSeeTag, createJSDocNameReference, updateJSDocNameReference, + createJSDocMemberName, + updateJSDocMemberName, createJSDocLink, updateJSDocLink, + createJSDocLinkCode, + updateJSDocLinkCode, + createJSDocLinkPlain, + updateJSDocLinkPlain, // lazily load factory members for JSDoc tags with similar structure get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocTypeTag); }, get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocTypeTag); }, @@ -531,7 +537,7 @@ namespace ts { // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. const length = elements.length; - const array = >(length >= 1 && length <= 4 ? elements.slice() : elements); + const array = (length >= 1 && length <= 4 ? elements.slice() : elements) as MutableNodeArray; setTextRangePosEnd(array, -1, -1); array.hasTrailingComma = !!hasTrailingComma; aggregateChildrenFlags(array); @@ -1896,13 +1902,13 @@ namespace ts { function updateUnionOrIntersectionTypeNode(node: T, types: NodeArray): T { return node.types !== types - ? update(createUnionOrIntersectionTypeNode(node.kind, types), node) + ? update(createUnionOrIntersectionTypeNode(node.kind, types) as T, node) : node; } // @api function createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode { - return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types); + return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types) as UnionTypeNode; } // @api @@ -1912,7 +1918,7 @@ namespace ts { // @api function createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode { - return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types); + return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types) as IntersectionTypeNode; } // @api @@ -2849,22 +2855,22 @@ namespace ts { // @api function createTemplateHead(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateHead, text, rawText, templateFlags); + return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateHead, text, rawText, templateFlags) as TemplateHead; } // @api function createTemplateMiddle(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateMiddle, text, rawText, templateFlags); + return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateMiddle, text, rawText, templateFlags) as TemplateMiddle; } // @api function createTemplateTail(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateTail, text, rawText, templateFlags); + return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateTail, text, rawText, templateFlags) as TemplateTail; } // @api function createNoSubstitutionTemplateLiteral(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - return createTemplateLiteralLikeNodeChecked(SyntaxKind.NoSubstitutionTemplateLiteral, text, rawText, templateFlags); + return createTemplateLiteralLikeNodeChecked(SyntaxKind.NoSubstitutionTemplateLiteral, text, rawText, templateFlags) as NoSubstitutionTemplateLiteral; } // @api @@ -4244,7 +4250,7 @@ namespace ts { } // @api - function createBaseJSDocTag(kind: T["kind"], tagName: Identifier, comment: string | NodeArray | undefined) { + function createBaseJSDocTag(kind: T["kind"], tagName: Identifier, comment: string | NodeArray | undefined) { const node = createBaseNode(kind); node.tagName = tagName; node.comment = comment; @@ -4252,7 +4258,7 @@ namespace ts { } // @api - function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag { + function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTemplateTag, tagName ?? createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); @@ -4260,7 +4266,7 @@ namespace ts { } // @api - function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag { + function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag { return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters @@ -4270,7 +4276,7 @@ namespace ts { } // @api - function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag { + function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTypedefTag, tagName ?? createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; @@ -4279,7 +4285,7 @@ namespace ts { } // @api - function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag { + function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName @@ -4289,7 +4295,7 @@ namespace ts { } // @api - function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag { + function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag { const node = createBaseJSDocTag(SyntaxKind.JSDocParameterTag, tagName ?? createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; @@ -4299,7 +4305,7 @@ namespace ts { } // @api - function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag { + function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag { return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed @@ -4311,7 +4317,7 @@ namespace ts { } // @api - function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag { + function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag { const node = createBaseJSDocTag(SyntaxKind.JSDocPropertyTag, tagName ?? createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; @@ -4321,7 +4327,7 @@ namespace ts { } // @api - function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag { + function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag { return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed @@ -4333,7 +4339,7 @@ namespace ts { } // @api - function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag { + function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag { const node = createBaseJSDocTag(SyntaxKind.JSDocCallbackTag, tagName ?? createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; @@ -4342,7 +4348,7 @@ namespace ts { } // @api - function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag { + function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName @@ -4352,14 +4358,14 @@ namespace ts { } // @api - function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag { + function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag { const node = createBaseJSDocTag(SyntaxKind.JSDocAugmentsTag, tagName ?? createIdentifier("augments"), comment); node.class = className; return node; } // @api - function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag { + function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag { return node.tagName !== tagName || node.class !== className || node.comment !== comment @@ -4368,21 +4374,21 @@ namespace ts { } // @api - function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag { + function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag { const node = createBaseJSDocTag(SyntaxKind.JSDocImplementsTag, tagName ?? createIdentifier("implements"), comment); node.class = className; return node; } // @api - function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { + function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { const node = createBaseJSDocTag(SyntaxKind.JSDocSeeTag, tagName ?? createIdentifier("see"), comment); node.name = name; return node; } // @api - function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { + function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { return node.tagName !== tagName || node.name !== name || node.comment !== comment @@ -4391,21 +4397,40 @@ namespace ts { } // @api - function createJSDocNameReference(name: EntityName): JSDocNameReference { + function createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference { const node = createBaseNode(SyntaxKind.JSDocNameReference); node.name = name; return node; } // @api - function updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference { + function updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference { return node.name !== name ? update(createJSDocNameReference(name), node) : node; } // @api - function createJSDocLink(name: EntityName | undefined, text: string): JSDocLink { + function createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier) { + const node = createBaseNode(SyntaxKind.JSDocMemberName); + node.left = left; + node.right = right; + node.transformFlags |= + propagateChildFlags(node.left) | + propagateChildFlags(node.right); + return node; + } + + // @api + function updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier) { + return node.left !== left + || node.right !== right + ? update(createJSDocMemberName(left, right), node) + : node; + } + + // @api + function createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink { const node = createBaseNode(SyntaxKind.JSDocLink); node.name = name; node.text = text; @@ -4413,14 +4438,44 @@ namespace ts { } // @api - function updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink { + function updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink { return node.name !== name ? update(createJSDocLink(name, text), node) : node; } // @api - function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag { + function createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode { + const node = createBaseNode(SyntaxKind.JSDocLinkCode); + node.name = name; + node.text = text; + return node; + } + + // @api + function updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode { + return node.name !== name + ? update(createJSDocLinkCode(name, text), node) + : node; + } + + // @api + function createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain { + const node = createBaseNode(SyntaxKind.JSDocLinkPlain); + node.name = name; + node.text = text; + return node; + } + + // @api + function updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain { + return node.name !== name + ? update(createJSDocLinkPlain(name, text), node) + : node; + } + + // @api + function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag { return node.tagName !== tagName || node.class !== className || node.comment !== comment @@ -4436,7 +4491,7 @@ namespace ts { // createJSDocProtectedTag // createJSDocReadonlyTag // createJSDocDeprecatedTag - function createJSDocSimpleTagWorker(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray) { + function createJSDocSimpleTagWorker(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray) { const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); return node; } @@ -4449,7 +4504,7 @@ namespace ts { // updateJSDocProtectedTag // updateJSDocReadonlyTag // updateJSDocDeprecatedTag - function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray | undefined) { + function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray | undefined) { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : @@ -4461,7 +4516,7 @@ namespace ts { // createJSDocReturnTag // createJSDocThisTag // createJSDocEnumTag - function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { + function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); node.typeExpression = typeExpression; return node; @@ -4472,7 +4527,7 @@ namespace ts { // updateJSDocReturnTag // updateJSDocThisTag // updateJSDocEnumTag - function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { + function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment @@ -4481,13 +4536,13 @@ namespace ts { } // @api - function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag { + function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTag, tagName, comment); return node; } // @api - function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag { + function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) @@ -4509,7 +4564,7 @@ namespace ts { } // @api - function createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) { + function createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) { const node = createBaseNode(SyntaxKind.JSDocComment); node.comment = comment; node.tags = asNodeArray(tags); @@ -4517,7 +4572,7 @@ namespace ts { } // @api - function updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined) { + function updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined) { return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) @@ -5457,13 +5512,13 @@ namespace ts { case SyntaxKind.StringLiteral: return false; case SyntaxKind.ArrayLiteralExpression: - const elements = (target).elements; + const elements = (target as ArrayLiteralExpression).elements; if (elements.length === 0) { return false; } return true; case SyntaxKind.ObjectLiteralExpression: - return (target).properties.length > 0; + return (target as ObjectLiteralExpression).properties.length > 0; default: return true; } @@ -5481,7 +5536,7 @@ namespace ts { thisArg = createThis(); target = languageVersion !== undefined && languageVersion < ScriptTarget.ES2015 ? setTextRange(createIdentifier("_super"), callee) - : callee; + : callee as PrimaryExpression; } else if (getEmitFlags(callee) & EmitFlags.HelperName) { thisArg = createVoidZero(); @@ -5746,7 +5801,7 @@ namespace ts { */ function liftToBlock(nodes: readonly Node[]): Statement { Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block."); - return singleOrUndefined(nodes) || createBlock(nodes); + return singleOrUndefined(nodes) as Statement || createBlock(nodes as readonly Statement[]); } function findSpanEnd(array: readonly T[], test: (value: T) => boolean, start: number) { diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts index 64a88d32d099e..fbe8a1ccd69fa 100644 --- a/src/compiler/factory/nodeTests.ts +++ b/src/compiler/factory/nodeTests.ts @@ -770,10 +770,22 @@ namespace ts { return node.kind === SyntaxKind.JSDocNameReference; } + export function isJSDocMemberName(node: Node): node is JSDocMemberName { + return node.kind === SyntaxKind.JSDocMemberName; + } + export function isJSDocLink(node: Node): node is JSDocLink { return node.kind === SyntaxKind.JSDocLink; } + export function isJSDocLinkCode(node: Node): node is JSDocLinkCode { + return node.kind === SyntaxKind.JSDocLinkCode; + } + + export function isJSDocLinkPlain(node: Node): node is JSDocLinkPlain { + return node.kind === SyntaxKind.JSDocLinkPlain; + } + export function isJSDocAllType(node: Node): node is JSDocAllType { return node.kind === SyntaxKind.JSDocAllType; } diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index 89492f82bde48..782a0110aba33 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -190,18 +190,18 @@ namespace ts { return node.kind; } - if (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.PlusToken) { - if ((node).cachedLiteralKind !== undefined) { - return (node).cachedLiteralKind; + if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken) { + if ((node as BinaryPlusExpression).cachedLiteralKind !== undefined) { + return (node as BinaryPlusExpression).cachedLiteralKind; } - const leftKind = getLiteralKindOfBinaryPlusOperand((node).left); + const leftKind = getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).left); const literalKind = isLiteralKind(leftKind) - && leftKind === getLiteralKindOfBinaryPlusOperand((node).right) + && leftKind === getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).right) ? leftKind : SyntaxKind.Unknown; - (node).cachedLiteralKind = literalKind; + (node as BinaryPlusExpression).cachedLiteralKind = literalKind; return literalKind; } @@ -319,7 +319,7 @@ namespace ts { // const emittedExpression = skipPartiallyEmittedExpressions(expression); if (isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression).arguments)) { + && (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression as NewExpression).arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression as LeftHandSideExpression; } diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index 433f13c5c3e29..a8397d33f5407 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -351,7 +351,7 @@ namespace ts { } export function isCommaSequence(node: Expression): node is BinaryExpression & {operatorToken: Token} | CommaListExpression { - return node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.CommaToken || + return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken || node.kind === SyntaxKind.CommaListExpression; } @@ -594,7 +594,7 @@ namespace ts { if (isSpreadElement(bindingElement)) { // Recovery consistent with existing emit. - return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); + return getInitializerOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); } } @@ -635,7 +635,7 @@ namespace ts { // `b.c` in `({ a: b.c = 1 } = ...)` // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` - return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer as BindingOrAssignmentElement); case SyntaxKind.ShorthandPropertyAssignment: // `a` in `({ a } = ...)` @@ -644,7 +644,7 @@ namespace ts { case SyntaxKind.SpreadAssignment: // `a` in `({ ...a } = ...)` - return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); } // no target @@ -657,12 +657,12 @@ namespace ts { // `[a]` in `[[a] = 1] = ...` // `a.b` in `[a.b = 1] = ...` // `a[0]` in `[a[0] = 1] = ...` - return getTargetOfBindingOrAssignmentElement(bindingElement.left); + return getTargetOfBindingOrAssignmentElement(bindingElement.left as BindingOrAssignmentElement); } if (isSpreadElement(bindingElement)) { // `a` in `[...a] = ...` - return getTargetOfBindingOrAssignmentElement(bindingElement.expression); + return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); } // `a` in `[a] = ...` @@ -767,11 +767,11 @@ namespace ts { case SyntaxKind.ArrayLiteralExpression: // `a` in `{a}` // `a` in `[a]` - return name.elements; + return name.elements as readonly BindingOrAssignmentElement[]; case SyntaxKind.ObjectLiteralExpression: // `a` in `{a}` - return name.properties; + return name.properties as readonly BindingOrAssignmentElement[]; } } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b2de8a805e3d8..cf983ee5067ab 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -79,66 +79,66 @@ namespace ts { } switch (node.kind) { case SyntaxKind.QualifiedName: - return visitNode(cbNode, (node).left) || - visitNode(cbNode, (node).right); + return visitNode(cbNode, (node as QualifiedName).left) || + visitNode(cbNode, (node as QualifiedName).right); case SyntaxKind.TypeParameter: - return visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).constraint) || - visitNode(cbNode, (node).default) || - visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as TypeParameterDeclaration).name) || + visitNode(cbNode, (node as TypeParameterDeclaration).constraint) || + visitNode(cbNode, (node as TypeParameterDeclaration).default) || + visitNode(cbNode, (node as TypeParameterDeclaration).expression); case SyntaxKind.ShorthandPropertyAssignment: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).exclamationToken) || - visitNode(cbNode, (node).equalsToken) || - visitNode(cbNode, (node).objectAssignmentInitializer); + visitNode(cbNode, (node as ShorthandPropertyAssignment).name) || + visitNode(cbNode, (node as ShorthandPropertyAssignment).questionToken) || + visitNode(cbNode, (node as ShorthandPropertyAssignment).exclamationToken) || + visitNode(cbNode, (node as ShorthandPropertyAssignment).equalsToken) || + visitNode(cbNode, (node as ShorthandPropertyAssignment).objectAssignmentInitializer); case SyntaxKind.SpreadAssignment: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as SpreadAssignment).expression); case SyntaxKind.Parameter: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).dotDotDotToken) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as ParameterDeclaration).dotDotDotToken) || + visitNode(cbNode, (node as ParameterDeclaration).name) || + visitNode(cbNode, (node as ParameterDeclaration).questionToken) || + visitNode(cbNode, (node as ParameterDeclaration).type) || + visitNode(cbNode, (node as ParameterDeclaration).initializer); case SyntaxKind.PropertyDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).exclamationToken) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as PropertyDeclaration).name) || + visitNode(cbNode, (node as PropertyDeclaration).questionToken) || + visitNode(cbNode, (node as PropertyDeclaration).exclamationToken) || + visitNode(cbNode, (node as PropertyDeclaration).type) || + visitNode(cbNode, (node as PropertyDeclaration).initializer); case SyntaxKind.PropertySignature: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as PropertySignature).name) || + visitNode(cbNode, (node as PropertySignature).questionToken) || + visitNode(cbNode, (node as PropertySignature).type) || + visitNode(cbNode, (node as PropertySignature).initializer); case SyntaxKind.PropertyAssignment: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as PropertyAssignment).name) || + visitNode(cbNode, (node as PropertyAssignment).questionToken) || + visitNode(cbNode, (node as PropertyAssignment).initializer); case SyntaxKind.VariableDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).exclamationToken) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as VariableDeclaration).name) || + visitNode(cbNode, (node as VariableDeclaration).exclamationToken) || + visitNode(cbNode, (node as VariableDeclaration).type) || + visitNode(cbNode, (node as VariableDeclaration).initializer); case SyntaxKind.BindingElement: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).dotDotDotToken) || - visitNode(cbNode, (node).propertyName) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).initializer); + visitNode(cbNode, (node as BindingElement).dotDotDotToken) || + visitNode(cbNode, (node as BindingElement).propertyName) || + visitNode(cbNode, (node as BindingElement).name) || + visitNode(cbNode, (node as BindingElement).initializer); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.CallSignature: @@ -146,9 +146,9 @@ namespace ts { case SyntaxKind.IndexSignature: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - visitNodes(cbNode, cbNodes, (node).parameters) || - visitNode(cbNode, (node).type); + visitNodes(cbNode, cbNodes, (node as SignatureDeclaration).typeParameters) || + visitNodes(cbNode, cbNodes, (node as SignatureDeclaration).parameters) || + visitNode(cbNode, (node as SignatureDeclaration).type); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: @@ -159,315 +159,315 @@ namespace ts { case SyntaxKind.ArrowFunction: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).asteriskToken) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).exclamationToken) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - visitNodes(cbNode, cbNodes, (node).parameters) || - visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).equalsGreaterThanToken) || - visitNode(cbNode, (node).body); + visitNode(cbNode, (node as FunctionLikeDeclaration).asteriskToken) || + visitNode(cbNode, (node as FunctionLikeDeclaration).name) || + visitNode(cbNode, (node as FunctionLikeDeclaration).questionToken) || + visitNode(cbNode, (node as FunctionLikeDeclaration).exclamationToken) || + visitNodes(cbNode, cbNodes, (node as FunctionLikeDeclaration).typeParameters) || + visitNodes(cbNode, cbNodes, (node as FunctionLikeDeclaration).parameters) || + visitNode(cbNode, (node as FunctionLikeDeclaration).type) || + visitNode(cbNode, (node as ArrowFunction).equalsGreaterThanToken) || + visitNode(cbNode, (node as FunctionLikeDeclaration).body); case SyntaxKind.TypeReference: - return visitNode(cbNode, (node).typeName) || - visitNodes(cbNode, cbNodes, (node).typeArguments); + return visitNode(cbNode, (node as TypeReferenceNode).typeName) || + visitNodes(cbNode, cbNodes, (node as TypeReferenceNode).typeArguments); case SyntaxKind.TypePredicate: - return visitNode(cbNode, (node).assertsModifier) || - visitNode(cbNode, (node).parameterName) || - visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as TypePredicateNode).assertsModifier) || + visitNode(cbNode, (node as TypePredicateNode).parameterName) || + visitNode(cbNode, (node as TypePredicateNode).type); case SyntaxKind.TypeQuery: - return visitNode(cbNode, (node).exprName); + return visitNode(cbNode, (node as TypeQueryNode).exprName); case SyntaxKind.TypeLiteral: - return visitNodes(cbNode, cbNodes, (node).members); + return visitNodes(cbNode, cbNodes, (node as TypeLiteralNode).members); case SyntaxKind.ArrayType: - return visitNode(cbNode, (node).elementType); + return visitNode(cbNode, (node as ArrayTypeNode).elementType); case SyntaxKind.TupleType: - return visitNodes(cbNode, cbNodes, (node).elements); + return visitNodes(cbNode, cbNodes, (node as TupleTypeNode).elements); case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: - return visitNodes(cbNode, cbNodes, (node).types); + return visitNodes(cbNode, cbNodes, (node as UnionOrIntersectionTypeNode).types); case SyntaxKind.ConditionalType: - return visitNode(cbNode, (node).checkType) || - visitNode(cbNode, (node).extendsType) || - visitNode(cbNode, (node).trueType) || - visitNode(cbNode, (node).falseType); + return visitNode(cbNode, (node as ConditionalTypeNode).checkType) || + visitNode(cbNode, (node as ConditionalTypeNode).extendsType) || + visitNode(cbNode, (node as ConditionalTypeNode).trueType) || + visitNode(cbNode, (node as ConditionalTypeNode).falseType); case SyntaxKind.InferType: - return visitNode(cbNode, (node).typeParameter); + return visitNode(cbNode, (node as InferTypeNode).typeParameter); case SyntaxKind.ImportType: - return visitNode(cbNode, (node).argument) || - visitNode(cbNode, (node).qualifier) || - visitNodes(cbNode, cbNodes, (node).typeArguments); + return visitNode(cbNode, (node as ImportTypeNode).argument) || + visitNode(cbNode, (node as ImportTypeNode).qualifier) || + visitNodes(cbNode, cbNodes, (node as ImportTypeNode).typeArguments); case SyntaxKind.ParenthesizedType: case SyntaxKind.TypeOperator: - return visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as ParenthesizedTypeNode | TypeOperatorNode).type); case SyntaxKind.IndexedAccessType: - return visitNode(cbNode, (node).objectType) || - visitNode(cbNode, (node).indexType); + return visitNode(cbNode, (node as IndexedAccessTypeNode).objectType) || + visitNode(cbNode, (node as IndexedAccessTypeNode).indexType); case SyntaxKind.MappedType: - return visitNode(cbNode, (node).readonlyToken) || - visitNode(cbNode, (node).typeParameter) || - visitNode(cbNode, (node).nameType) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as MappedTypeNode).readonlyToken) || + visitNode(cbNode, (node as MappedTypeNode).typeParameter) || + visitNode(cbNode, (node as MappedTypeNode).nameType) || + visitNode(cbNode, (node as MappedTypeNode).questionToken) || + visitNode(cbNode, (node as MappedTypeNode).type); case SyntaxKind.LiteralType: - return visitNode(cbNode, (node).literal); + return visitNode(cbNode, (node as LiteralTypeNode).literal); case SyntaxKind.NamedTupleMember: - return visitNode(cbNode, (node).dotDotDotToken) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as NamedTupleMember).dotDotDotToken) || + visitNode(cbNode, (node as NamedTupleMember).name) || + visitNode(cbNode, (node as NamedTupleMember).questionToken) || + visitNode(cbNode, (node as NamedTupleMember).type); case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: - return visitNodes(cbNode, cbNodes, (node).elements); + return visitNodes(cbNode, cbNodes, (node as BindingPattern).elements); case SyntaxKind.ArrayLiteralExpression: - return visitNodes(cbNode, cbNodes, (node).elements); + return visitNodes(cbNode, cbNodes, (node as ArrayLiteralExpression).elements); case SyntaxKind.ObjectLiteralExpression: - return visitNodes(cbNode, cbNodes, (node).properties); + return visitNodes(cbNode, cbNodes, (node as ObjectLiteralExpression).properties); case SyntaxKind.PropertyAccessExpression: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).questionDotToken) || - visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as PropertyAccessExpression).expression) || + visitNode(cbNode, (node as PropertyAccessExpression).questionDotToken) || + visitNode(cbNode, (node as PropertyAccessExpression).name); case SyntaxKind.ElementAccessExpression: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).questionDotToken) || - visitNode(cbNode, (node).argumentExpression); + return visitNode(cbNode, (node as ElementAccessExpression).expression) || + visitNode(cbNode, (node as ElementAccessExpression).questionDotToken) || + visitNode(cbNode, (node as ElementAccessExpression).argumentExpression); case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).questionDotToken) || - visitNodes(cbNode, cbNodes, (node).typeArguments) || - visitNodes(cbNode, cbNodes, (node).arguments); + return visitNode(cbNode, (node as CallExpression).expression) || + visitNode(cbNode, (node as CallExpression).questionDotToken) || + visitNodes(cbNode, cbNodes, (node as CallExpression).typeArguments) || + visitNodes(cbNode, cbNodes, (node as CallExpression).arguments); case SyntaxKind.TaggedTemplateExpression: - return visitNode(cbNode, (node).tag) || - visitNode(cbNode, (node).questionDotToken) || - visitNodes(cbNode, cbNodes, (node).typeArguments) || - visitNode(cbNode, (node).template); + return visitNode(cbNode, (node as TaggedTemplateExpression).tag) || + visitNode(cbNode, (node as TaggedTemplateExpression).questionDotToken) || + visitNodes(cbNode, cbNodes, (node as TaggedTemplateExpression).typeArguments) || + visitNode(cbNode, (node as TaggedTemplateExpression).template); case SyntaxKind.TypeAssertionExpression: - return visitNode(cbNode, (node).type) || - visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as TypeAssertion).type) || + visitNode(cbNode, (node as TypeAssertion).expression); case SyntaxKind.ParenthesizedExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ParenthesizedExpression).expression); case SyntaxKind.DeleteExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as DeleteExpression).expression); case SyntaxKind.TypeOfExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as TypeOfExpression).expression); case SyntaxKind.VoidExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as VoidExpression).expression); case SyntaxKind.PrefixUnaryExpression: - return visitNode(cbNode, (node).operand); + return visitNode(cbNode, (node as PrefixUnaryExpression).operand); case SyntaxKind.YieldExpression: - return visitNode(cbNode, (node).asteriskToken) || - visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as YieldExpression).asteriskToken) || + visitNode(cbNode, (node as YieldExpression).expression); case SyntaxKind.AwaitExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as AwaitExpression).expression); case SyntaxKind.PostfixUnaryExpression: - return visitNode(cbNode, (node).operand); + return visitNode(cbNode, (node as PostfixUnaryExpression).operand); case SyntaxKind.BinaryExpression: - return visitNode(cbNode, (node).left) || - visitNode(cbNode, (node).operatorToken) || - visitNode(cbNode, (node).right); + return visitNode(cbNode, (node as BinaryExpression).left) || + visitNode(cbNode, (node as BinaryExpression).operatorToken) || + visitNode(cbNode, (node as BinaryExpression).right); case SyntaxKind.AsExpression: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as AsExpression).expression) || + visitNode(cbNode, (node as AsExpression).type); case SyntaxKind.NonNullExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as NonNullExpression).expression); case SyntaxKind.MetaProperty: - return visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as MetaProperty).name); case SyntaxKind.ConditionalExpression: - return visitNode(cbNode, (node).condition) || - visitNode(cbNode, (node).questionToken) || - visitNode(cbNode, (node).whenTrue) || - visitNode(cbNode, (node).colonToken) || - visitNode(cbNode, (node).whenFalse); + return visitNode(cbNode, (node as ConditionalExpression).condition) || + visitNode(cbNode, (node as ConditionalExpression).questionToken) || + visitNode(cbNode, (node as ConditionalExpression).whenTrue) || + visitNode(cbNode, (node as ConditionalExpression).colonToken) || + visitNode(cbNode, (node as ConditionalExpression).whenFalse); case SyntaxKind.SpreadElement: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as SpreadElement).expression); case SyntaxKind.Block: case SyntaxKind.ModuleBlock: - return visitNodes(cbNode, cbNodes, (node).statements); + return visitNodes(cbNode, cbNodes, (node as Block).statements); case SyntaxKind.SourceFile: - return visitNodes(cbNode, cbNodes, (node).statements) || - visitNode(cbNode, (node).endOfFileToken); + return visitNodes(cbNode, cbNodes, (node as SourceFile).statements) || + visitNode(cbNode, (node as SourceFile).endOfFileToken); case SyntaxKind.VariableStatement: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).declarationList); + visitNode(cbNode, (node as VariableStatement).declarationList); case SyntaxKind.VariableDeclarationList: - return visitNodes(cbNode, cbNodes, (node).declarations); + return visitNodes(cbNode, cbNodes, (node as VariableDeclarationList).declarations); case SyntaxKind.ExpressionStatement: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ExpressionStatement).expression); case SyntaxKind.IfStatement: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).thenStatement) || - visitNode(cbNode, (node).elseStatement); + return visitNode(cbNode, (node as IfStatement).expression) || + visitNode(cbNode, (node as IfStatement).thenStatement) || + visitNode(cbNode, (node as IfStatement).elseStatement); case SyntaxKind.DoStatement: - return visitNode(cbNode, (node).statement) || - visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as DoStatement).statement) || + visitNode(cbNode, (node as DoStatement).expression); case SyntaxKind.WhileStatement: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as WhileStatement).expression) || + visitNode(cbNode, (node as WhileStatement).statement); case SyntaxKind.ForStatement: - return visitNode(cbNode, (node).initializer) || - visitNode(cbNode, (node).condition) || - visitNode(cbNode, (node).incrementor) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as ForStatement).initializer) || + visitNode(cbNode, (node as ForStatement).condition) || + visitNode(cbNode, (node as ForStatement).incrementor) || + visitNode(cbNode, (node as ForStatement).statement); case SyntaxKind.ForInStatement: - return visitNode(cbNode, (node).initializer) || - visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as ForInStatement).initializer) || + visitNode(cbNode, (node as ForInStatement).expression) || + visitNode(cbNode, (node as ForInStatement).statement); case SyntaxKind.ForOfStatement: - return visitNode(cbNode, (node).awaitModifier) || - visitNode(cbNode, (node).initializer) || - visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as ForOfStatement).awaitModifier) || + visitNode(cbNode, (node as ForOfStatement).initializer) || + visitNode(cbNode, (node as ForOfStatement).expression) || + visitNode(cbNode, (node as ForOfStatement).statement); case SyntaxKind.ContinueStatement: case SyntaxKind.BreakStatement: - return visitNode(cbNode, (node).label); + return visitNode(cbNode, (node as BreakOrContinueStatement).label); case SyntaxKind.ReturnStatement: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ReturnStatement).expression); case SyntaxKind.WithStatement: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as WithStatement).expression) || + visitNode(cbNode, (node as WithStatement).statement); case SyntaxKind.SwitchStatement: - return visitNode(cbNode, (node).expression) || - visitNode(cbNode, (node).caseBlock); + return visitNode(cbNode, (node as SwitchStatement).expression) || + visitNode(cbNode, (node as SwitchStatement).caseBlock); case SyntaxKind.CaseBlock: - return visitNodes(cbNode, cbNodes, (node).clauses); + return visitNodes(cbNode, cbNodes, (node as CaseBlock).clauses); case SyntaxKind.CaseClause: - return visitNode(cbNode, (node).expression) || - visitNodes(cbNode, cbNodes, (node).statements); + return visitNode(cbNode, (node as CaseClause).expression) || + visitNodes(cbNode, cbNodes, (node as CaseClause).statements); case SyntaxKind.DefaultClause: - return visitNodes(cbNode, cbNodes, (node).statements); + return visitNodes(cbNode, cbNodes, (node as DefaultClause).statements); case SyntaxKind.LabeledStatement: - return visitNode(cbNode, (node).label) || - visitNode(cbNode, (node).statement); + return visitNode(cbNode, (node as LabeledStatement).label) || + visitNode(cbNode, (node as LabeledStatement).statement); case SyntaxKind.ThrowStatement: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ThrowStatement).expression); case SyntaxKind.TryStatement: - return visitNode(cbNode, (node).tryBlock) || - visitNode(cbNode, (node).catchClause) || - visitNode(cbNode, (node).finallyBlock); + return visitNode(cbNode, (node as TryStatement).tryBlock) || + visitNode(cbNode, (node as TryStatement).catchClause) || + visitNode(cbNode, (node as TryStatement).finallyBlock); case SyntaxKind.CatchClause: - return visitNode(cbNode, (node).variableDeclaration) || - visitNode(cbNode, (node).block); + return visitNode(cbNode, (node as CatchClause).variableDeclaration) || + visitNode(cbNode, (node as CatchClause).block); case SyntaxKind.Decorator: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as Decorator).expression); case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - visitNodes(cbNode, cbNodes, (node).heritageClauses) || - visitNodes(cbNode, cbNodes, (node).members); + visitNode(cbNode, (node as ClassLikeDeclaration).name) || + visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).typeParameters) || + visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).heritageClauses) || + visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).members); case SyntaxKind.InterfaceDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - visitNodes(cbNode, cbNodes, (node).heritageClauses) || - visitNodes(cbNode, cbNodes, (node).members); + visitNode(cbNode, (node as InterfaceDeclaration).name) || + visitNodes(cbNode, cbNodes, (node as InterfaceDeclaration).typeParameters) || + visitNodes(cbNode, cbNodes, (node as ClassDeclaration).heritageClauses) || + visitNodes(cbNode, cbNodes, (node as InterfaceDeclaration).members); case SyntaxKind.TypeAliasDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - visitNode(cbNode, (node).type); + visitNode(cbNode, (node as TypeAliasDeclaration).name) || + visitNodes(cbNode, cbNodes, (node as TypeAliasDeclaration).typeParameters) || + visitNode(cbNode, (node as TypeAliasDeclaration).type); case SyntaxKind.EnumDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNodes(cbNode, cbNodes, (node).members); + visitNode(cbNode, (node as EnumDeclaration).name) || + visitNodes(cbNode, cbNodes, (node as EnumDeclaration).members); case SyntaxKind.EnumMember: - return visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).initializer); + return visitNode(cbNode, (node as EnumMember).name) || + visitNode(cbNode, (node as EnumMember).initializer); case SyntaxKind.ModuleDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).body); + visitNode(cbNode, (node as ModuleDeclaration).name) || + visitNode(cbNode, (node as ModuleDeclaration).body); case SyntaxKind.ImportEqualsDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).moduleReference); + visitNode(cbNode, (node as ImportEqualsDeclaration).name) || + visitNode(cbNode, (node as ImportEqualsDeclaration).moduleReference); case SyntaxKind.ImportDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).importClause) || - visitNode(cbNode, (node).moduleSpecifier); + visitNode(cbNode, (node as ImportDeclaration).importClause) || + visitNode(cbNode, (node as ImportDeclaration).moduleSpecifier); case SyntaxKind.ImportClause: - return visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).namedBindings); + return visitNode(cbNode, (node as ImportClause).name) || + visitNode(cbNode, (node as ImportClause).namedBindings); case SyntaxKind.NamespaceExportDeclaration: - return visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as NamespaceExportDeclaration).name); case SyntaxKind.NamespaceImport: - return visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as NamespaceImport).name); case SyntaxKind.NamespaceExport: - return visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as NamespaceExport).name); case SyntaxKind.NamedImports: case SyntaxKind.NamedExports: - return visitNodes(cbNode, cbNodes, (node).elements); + return visitNodes(cbNode, cbNodes, (node as NamedImportsOrExports).elements); case SyntaxKind.ExportDeclaration: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).exportClause) || - visitNode(cbNode, (node).moduleSpecifier); + visitNode(cbNode, (node as ExportDeclaration).exportClause) || + visitNode(cbNode, (node as ExportDeclaration).moduleSpecifier); case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - return visitNode(cbNode, (node).propertyName) || - visitNode(cbNode, (node).name); + return visitNode(cbNode, (node as ImportOrExportSpecifier).propertyName) || + visitNode(cbNode, (node as ImportOrExportSpecifier).name); case SyntaxKind.ExportAssignment: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, (node).expression); + visitNode(cbNode, (node as ExportAssignment).expression); case SyntaxKind.TemplateExpression: - return visitNode(cbNode, (node).head) || visitNodes(cbNode, cbNodes, (node).templateSpans); + return visitNode(cbNode, (node as TemplateExpression).head) || visitNodes(cbNode, cbNodes, (node as TemplateExpression).templateSpans); case SyntaxKind.TemplateSpan: - return visitNode(cbNode, (node).expression) || visitNode(cbNode, (node).literal); + return visitNode(cbNode, (node as TemplateSpan).expression) || visitNode(cbNode, (node as TemplateSpan).literal); case SyntaxKind.TemplateLiteralType: - return visitNode(cbNode, (node).head) || visitNodes(cbNode, cbNodes, (node).templateSpans); + return visitNode(cbNode, (node as TemplateLiteralTypeNode).head) || visitNodes(cbNode, cbNodes, (node as TemplateLiteralTypeNode).templateSpans); case SyntaxKind.TemplateLiteralTypeSpan: - return visitNode(cbNode, (node).type) || visitNode(cbNode, (node).literal); + return visitNode(cbNode, (node as TemplateLiteralTypeSpan).type) || visitNode(cbNode, (node as TemplateLiteralTypeSpan).literal); case SyntaxKind.ComputedPropertyName: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ComputedPropertyName).expression); case SyntaxKind.HeritageClause: - return visitNodes(cbNode, cbNodes, (node).types); + return visitNodes(cbNode, cbNodes, (node as HeritageClause).types); case SyntaxKind.ExpressionWithTypeArguments: - return visitNode(cbNode, (node).expression) || - visitNodes(cbNode, cbNodes, (node).typeArguments); + return visitNode(cbNode, (node as ExpressionWithTypeArguments).expression) || + visitNodes(cbNode, cbNodes, (node as ExpressionWithTypeArguments).typeArguments); case SyntaxKind.ExternalModuleReference: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as ExternalModuleReference).expression); case SyntaxKind.MissingDeclaration: return visitNodes(cbNode, cbNodes, node.decorators); case SyntaxKind.CommaListExpression: - return visitNodes(cbNode, cbNodes, (node).elements); + return visitNodes(cbNode, cbNodes, (node as CommaListExpression).elements); case SyntaxKind.JsxElement: - return visitNode(cbNode, (node).openingElement) || - visitNodes(cbNode, cbNodes, (node).children) || - visitNode(cbNode, (node).closingElement); + return visitNode(cbNode, (node as JsxElement).openingElement) || + visitNodes(cbNode, cbNodes, (node as JsxElement).children) || + visitNode(cbNode, (node as JsxElement).closingElement); case SyntaxKind.JsxFragment: - return visitNode(cbNode, (node).openingFragment) || - visitNodes(cbNode, cbNodes, (node).children) || - visitNode(cbNode, (node).closingFragment); + return visitNode(cbNode, (node as JsxFragment).openingFragment) || + visitNodes(cbNode, cbNodes, (node as JsxFragment).children) || + visitNode(cbNode, (node as JsxFragment).closingFragment); case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxOpeningElement: - return visitNode(cbNode, (node).tagName) || - visitNodes(cbNode, cbNodes, (node).typeArguments) || - visitNode(cbNode, (node).attributes); + return visitNode(cbNode, (node as JsxOpeningLikeElement).tagName) || + visitNodes(cbNode, cbNodes, (node as JsxOpeningLikeElement).typeArguments) || + visitNode(cbNode, (node as JsxOpeningLikeElement).attributes); case SyntaxKind.JsxAttributes: - return visitNodes(cbNode, cbNodes, (node).properties); + return visitNodes(cbNode, cbNodes, (node as JsxAttributes).properties); case SyntaxKind.JsxAttribute: - return visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).initializer); + return visitNode(cbNode, (node as JsxAttribute).name) || + visitNode(cbNode, (node as JsxAttribute).initializer); case SyntaxKind.JsxSpreadAttribute: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as JsxSpreadAttribute).expression); case SyntaxKind.JsxExpression: return visitNode(cbNode, (node as JsxExpression).dotDotDotToken) || visitNode(cbNode, (node as JsxExpression).expression); case SyntaxKind.JsxClosingElement: - return visitNode(cbNode, (node).tagName); + return visitNode(cbNode, (node as JsxClosingElement).tagName); case SyntaxKind.OptionalType: case SyntaxKind.RestType: @@ -476,73 +476,78 @@ namespace ts { case SyntaxKind.JSDocNullableType: case SyntaxKind.JSDocOptionalType: case SyntaxKind.JSDocVariadicType: - return visitNode(cbNode, (node).type); + return visitNode(cbNode, (node as OptionalTypeNode | RestTypeNode | JSDocTypeExpression | JSDocTypeReferencingNode).type); case SyntaxKind.JSDocFunctionType: - return visitNodes(cbNode, cbNodes, (node).parameters) || - visitNode(cbNode, (node).type); + return visitNodes(cbNode, cbNodes, (node as JSDocFunctionType).parameters) || + visitNode(cbNode, (node as JSDocFunctionType).type); case SyntaxKind.JSDocComment: - return (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) + return (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) || visitNodes(cbNode, cbNodes, (node as JSDoc).tags); case SyntaxKind.JSDocSeeTag: return visitNode(cbNode, (node as JSDocSeeTag).tagName) || visitNode(cbNode, (node as JSDocSeeTag).name) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocNameReference: return visitNode(cbNode, (node as JSDocNameReference).name); + case SyntaxKind.JSDocMemberName: + return visitNode(cbNode, (node as JSDocMemberName).left) || + visitNode(cbNode, (node as JSDocMemberName).right); case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: return visitNode(cbNode, (node as JSDocTag).tagName) || ((node as JSDocPropertyLikeTag).isNameFirst - ? visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).typeExpression) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) - : visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).name)) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + ? visitNode(cbNode, (node as JSDocPropertyLikeTag).name) || + visitNode(cbNode, (node as JSDocPropertyLikeTag).typeExpression) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) + : visitNode(cbNode, (node as JSDocPropertyLikeTag).typeExpression) || + visitNode(cbNode, (node as JSDocPropertyLikeTag).name)) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocAuthorTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocImplementsTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).class) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + visitNode(cbNode, (node as JSDocImplementsTag).class) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocAugmentsTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).class) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + visitNode(cbNode, (node as JSDocAugmentsTag).class) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocTemplateTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).constraint) || - visitNodes(cbNode, cbNodes, (node).typeParameters) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + visitNode(cbNode, (node as JSDocTemplateTag).constraint) || + visitNodes(cbNode, cbNodes, (node as JSDocTemplateTag).typeParameters) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocTypedefTag: return visitNode(cbNode, (node as JSDocTag).tagName) || ((node as JSDocTypedefTag).typeExpression && (node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression - ? visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).fullName) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) - : visitNode(cbNode, (node).fullName) || - visitNode(cbNode, (node).typeExpression)) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + ? visitNode(cbNode, (node as JSDocTypedefTag).typeExpression) || + visitNode(cbNode, (node as JSDocTypedefTag).fullName) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) + : visitNode(cbNode, (node as JSDocTypedefTag).fullName) || + visitNode(cbNode, (node as JSDocTypedefTag).typeExpression)) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocCallbackTag: return visitNode(cbNode, (node as JSDocTag).tagName) || visitNode(cbNode, (node as JSDocCallbackTag).fullName) || visitNode(cbNode, (node as JSDocCallbackTag).typeExpression) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocReturnTag: case SyntaxKind.JSDocTypeTag: case SyntaxKind.JSDocThisTag: case SyntaxKind.JSDocEnumTag: return visitNode(cbNode, (node as JSDocTag).tagName) || visitNode(cbNode, (node as JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag).typeExpression) || - (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocSignature: - return forEach((node).typeParameters, cbNode) || - forEach((node).parameters, cbNode) || - visitNode(cbNode, (node).type); + return forEach((node as JSDocSignature).typeParameters, cbNode) || + forEach((node as JSDocSignature).parameters, cbNode) || + visitNode(cbNode, (node as JSDocSignature).type); case SyntaxKind.JSDocLink: - return visitNode(cbNode, (node as JSDocLink).name); + case SyntaxKind.JSDocLinkCode: + case SyntaxKind.JSDocLinkPlain: + return visitNode(cbNode, (node as JSDocLink | JSDocLinkCode | JSDocLinkPlain).name); case SyntaxKind.JSDocTypeLiteral: return forEach((node as JSDocTypeLiteral).jsDocPropertyTags, cbNode); case SyntaxKind.JSDocTag: @@ -553,9 +558,9 @@ namespace ts { case SyntaxKind.JSDocReadonlyTag: case SyntaxKind.JSDocDeprecatedTag: return visitNode(cbNode, (node as JSDocTag).tagName) - || (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); + || (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.PartiallyEmittedExpression: - return visitNode(cbNode, (node).expression); + return visitNode(cbNode, (node as PartiallyEmittedExpression).expression); } } @@ -1336,27 +1341,24 @@ namespace ts { return inContext(NodeFlags.AwaitContext); } - function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): DiagnosticWithDetachedLocation | undefined { - return parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); + function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } - function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): DiagnosticWithDetachedLocation | undefined { + function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): void { // Don't report another error if it would just be at the same position as the last error. const lastError = lastOrUndefined(parseDiagnostics); - let result: DiagnosticWithDetachedLocation | undefined; if (!lastError || start !== lastError.start) { - result = createDetachedDiagnostic(fileName, start, length, message, arg0); - parseDiagnostics.push(result); + parseDiagnostics.push(createDetachedDiagnostic(fileName, start, length, message, arg0)); } // Mark that we've encountered an error. We'll set an appropriate bit on the next // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; - return result; } - function parseErrorAt(start: number, end: number, message: DiagnosticMessage, arg0?: any): DiagnosticWithDetachedLocation | undefined { - return parseErrorAtPosition(start, end - start, message, arg0); + function parseErrorAt(start: number, end: number, message: DiagnosticMessage, arg0?: any): void { + parseErrorAtPosition(start, end - start, message, arg0); } function parseErrorAtRange(range: TextRange, message: DiagnosticMessage, arg0?: any): void { @@ -1427,6 +1429,10 @@ namespace ts { return currentToken = scanner.reScanLessThanToken(); } + function reScanHashToken(): SyntaxKind { + return currentToken = scanner.reScanHashToken(); + } + function scanJsxIdentifier(): SyntaxKind { return currentToken = scanner.scanJsxIdentifier(); } @@ -1546,20 +1552,6 @@ namespace ts { return false; } - function parseExpectedMatchingBrackets(openKind: SyntaxKind, closeKind: SyntaxKind, openPosition: number) { - if (token() === closeKind) { - nextToken(); - return; - } - const lastError = parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(closeKind)); - if (lastError) { - addRelatedInfo( - lastError, - createDetachedDiagnostic(fileName, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) - ); - } - } - function parseOptional(t: SyntaxKind): boolean { if (token() === t) { nextToken(); @@ -1600,14 +1592,14 @@ namespace ts { const pos = getNodePos(); const kind = token(); nextToken(); - return finishNode(factory.createToken(kind), pos); + return finishNode(factory.createToken(kind), pos) as T; } function parseTokenNodeJSDoc(): T { const pos = getNodePos(); const kind = token(); nextTokenJSDoc(); - return finishNode(factory.createToken(kind), pos); + return finishNode(factory.createToken(kind), pos) as T; } function canParseSemicolon() { @@ -1744,7 +1736,7 @@ namespace ts { function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName { if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) { - const node = parseLiteralNode(); + const node = parseLiteralNode() as StringLiteral | NumericLiteral; node.text = internIdentifier(node.text); return node; } @@ -2127,7 +2119,7 @@ namespace ts { function parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { const node = currentNode(parsingContext); if (node) { - return consumeNode(node); + return consumeNode(node) as T; } return parseElement(); @@ -2304,7 +2296,7 @@ namespace ts { // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. - const methodDeclaration = node; + const methodDeclaration = node as MethodDeclaration; const nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier && methodDeclaration.name.originalKeywordKind === SyntaxKind.ConstructorKeyword; @@ -2404,7 +2396,7 @@ namespace ts { // // In order to prevent this, we do not allow a variable declarator to be reused if it // has an initializer. - const variableDeclarator = node; + const variableDeclarator = node as VariableDeclaration; return variableDeclarator.initializer === undefined; } @@ -2414,7 +2406,7 @@ namespace ts { } // See the comment in isReusableVariableDeclaration for why we do this. - const parameter = node; + const parameter = node as ParameterDeclaration; return parameter.initializer === undefined; } @@ -2684,7 +2676,7 @@ namespace ts { } else { // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly? - return parseExpectedToken(SyntaxKind.TemplateTail, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken)); + return parseExpectedToken(SyntaxKind.TemplateTail, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken)) as TemplateTail; } } @@ -2700,7 +2692,7 @@ namespace ts { } function parseLiteralNode(): LiteralExpression { - return parseLiteralLikeNode(token()); + return parseLiteralLikeNode(token()) as LiteralExpression; } function parseTemplateHead(isTaggedTemplate: boolean): TemplateHead { @@ -2709,13 +2701,13 @@ namespace ts { } const fragment = parseLiteralLikeNode(token()); Debug.assert(fragment.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind"); - return fragment; + return fragment as TemplateHead; } function parseTemplateMiddleOrTemplateTail(): TemplateMiddle | TemplateTail { const fragment = parseLiteralLikeNode(token()); Debug.assert(fragment.kind === SyntaxKind.TemplateMiddle || fragment.kind === SyntaxKind.TemplateTail, "Template fragment has wrong token kind"); - return fragment; + return fragment as TemplateMiddle | TemplateTail; } function getTemplateLiteralRawText(kind: TemplateLiteralToken["kind"]) { @@ -4031,7 +4023,7 @@ namespace ts { // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. if (expr.kind === SyntaxKind.Identifier && token() === SyntaxKind.EqualsGreaterThanToken) { - return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined); + return parseSimpleArrowFunctionExpression(pos, expr as Identifier, /*asyncModifier*/ undefined); } // Now see if we might be in cases '2' or '3'. @@ -4307,7 +4299,7 @@ namespace ts { const pos = getNodePos(); const asyncModifier = parseModifiersForArrowFunction(); const expr = parseBinaryExpressionOrHigher(OperatorPrecedence.Lowest); - return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier); + return parseSimpleArrowFunctionExpression(pos, expr as Identifier, asyncModifier); } } return undefined; @@ -4545,7 +4537,7 @@ namespace ts { function parsePrefixUnaryExpression() { const pos = getNodePos(); - return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode(factory.createPrefixUnaryExpression(token() as PrefixUnaryOperator, nextTokenAnd(parseSimpleUnaryExpression)), pos); } function parseDeleteExpression() { @@ -4602,7 +4594,7 @@ namespace ts { const pos = getNodePos(); const updateExpression = parseUpdateExpression(); return token() === SyntaxKind.AsteriskAsteriskToken ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) : + parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) as BinaryExpression : updateExpression; } @@ -4723,7 +4715,7 @@ namespace ts { function parseUpdateExpression(): UpdateExpression { if (token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) { const pos = getNodePos(); - return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); + return finishNode(factory.createPrefixUnaryExpression(token() as PrefixUnaryOperator, nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); } else if (languageVariant === LanguageVariant.JSX && token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { // JSXElement is part of primaryExpression @@ -4734,7 +4726,7 @@ namespace ts { Debug.assert(isLeftHandSideExpression(expression)); if ((token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) { - const operator = token(); + const operator = token() as PostfixUnaryOperator; nextToken(); return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos); } @@ -4882,18 +4874,45 @@ namespace ts { return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos); } - function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext: boolean, topInvalidNodePosition?: number): JsxElement | JsxSelfClosingElement | JsxFragment { + function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext: boolean, topInvalidNodePosition?: number, openingTag?: JsxOpeningElement | JsxOpeningFragment): JsxElement | JsxSelfClosingElement | JsxFragment { const pos = getNodePos(); const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); let result: JsxElement | JsxSelfClosingElement | JsxFragment; if (opening.kind === SyntaxKind.JsxOpeningElement) { - const children = parseJsxChildren(opening); - const closingElement = parseJsxClosingElement(inExpressionContext); - - if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { - parseErrorAtRange(closingElement, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + let children = parseJsxChildren(opening); + let closingElement: JsxClosingElement; + + const lastChild: JsxChild | undefined = children[children.length - 1]; + if (lastChild?.kind === SyntaxKind.JsxElement + && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) + && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { + // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, + // restructure (

)) --> (
(...)
) + // (no need to error; the parent will error) + const end = lastChild.openingElement.end; // newly-created children and closing are both zero-width end/end + const newLast = finishNode(factory.createJsxElement( + lastChild.openingElement, + createNodeArray([], end, end), + finishNode(factory.createJsxClosingElement(finishNode(factory.createIdentifier(""), end, end)), end, end)), + lastChild.openingElement.pos, + end); + + children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end); + closingElement = lastChild.closingElement; + } + else { + closingElement = parseJsxClosingElement(opening, inExpressionContext); + if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { + if (openingTag && isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) { + // opening incorrectly matched with its parent's closing -- put error on opening + parseErrorAtRange(opening.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + } + else { + // other opening/closing mismatches -- put error on closing + parseErrorAtRange(closingElement.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + } + } } - result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } else if (opening.kind === SyntaxKind.JsxOpeningFragment) { @@ -4919,7 +4938,7 @@ namespace ts { const operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false); setTextRangePosWidth(operatorToken, invalidElement.pos, 0); parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element); - return finishNode(factory.createBinaryExpression(result, operatorToken as Token, invalidElement), pos); + return finishNode(factory.createBinaryExpression(result, operatorToken as Token, invalidElement), pos) as Node as JsxElement; } } @@ -4958,7 +4977,7 @@ namespace ts { case SyntaxKind.OpenBraceToken: return parseJsxExpression(/*inExpressionContext*/ false); case SyntaxKind.LessThanToken: - return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false, /*topInvalidNodePosition*/ undefined, openingTag); default: return Debug.assertNever(token); } @@ -4974,6 +4993,13 @@ namespace ts { const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); if (!child) break; list.push(child); + if (isJsxOpeningElement(openingTag) + && child?.kind === SyntaxKind.JsxElement + && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) + && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { + // stop after parsing a mismatched child like
...(
) in order to reattach the higher + break; + } } parsingContext = saveParsingContext; @@ -4995,7 +5021,6 @@ namespace ts { scanJsxText(); return finishNode(factory.createJsxOpeningFragment(), pos); } - const tagName = parseJsxElementName(); const typeArguments = (contextFlags & NodeFlags.JavaScriptFile) === 0 ? tryParseTypeArguments() : undefined; const attributes = parseJsxAttributes(); @@ -5011,12 +5036,14 @@ namespace ts { } else { parseExpected(SyntaxKind.SlashToken); - if (inExpressionContext) { - parseExpected(SyntaxKind.GreaterThanToken); - } - else { - parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); + if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) { + // manually advance the scanner in order to look for jsx text inside jsx + if (inExpressionContext) { + nextToken(); + } + else { + scanJsxText(); + } } node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes); } @@ -5094,16 +5121,18 @@ namespace ts { return finishNode(factory.createJsxSpreadAttribute(expression), pos); } - function parseJsxClosingElement(inExpressionContext: boolean): JsxClosingElement { + function parseJsxClosingElement(open: JsxOpeningElement, inExpressionContext: boolean): JsxClosingElement { const pos = getNodePos(); parseExpected(SyntaxKind.LessThanSlashToken); const tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(SyntaxKind.GreaterThanToken); - } - else { - parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); + if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) { + // manually advance the scanner in order to look for jsx text inside jsx + if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) { + nextToken(); + } + else { + scanJsxText(); + } } return finishNode(factory.createJsxClosingElement(tagName), pos); } @@ -5114,12 +5143,14 @@ namespace ts { if (tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } - if (inExpressionContext) { - parseExpected(SyntaxKind.GreaterThanToken); - } - else { - parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); + if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) { + // manually advance the scanner in order to look for jsx text inside jsx + if (inExpressionContext) { + nextToken(); + } + else { + scanJsxText(); + } } return finishNode(factory.createJsxJsxClosingFragment(), pos); } @@ -5234,7 +5265,7 @@ namespace ts { continue; } - return expression; + return expression as MemberExpression; } } @@ -5450,11 +5481,10 @@ namespace ts { function parseArrayLiteralExpression(): ArrayLiteralExpression { const pos = getNodePos(); - const openBracketPosition = scanner.getTokenPos(); parseExpected(SyntaxKind.OpenBracketToken); const multiLine = scanner.hasPrecedingLineBreak(); const elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement); - parseExpectedMatchingBrackets(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken, openBracketPosition); + parseExpected(SyntaxKind.CloseBracketToken); return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos); } @@ -5523,7 +5553,15 @@ namespace ts { parseExpected(SyntaxKind.OpenBraceToken); const multiLine = scanner.hasPrecedingLineBreak(); const properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBracePosition); + if (!parseExpected(SyntaxKind.CloseBraceToken)) { + const lastError = lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === Diagnostics._0_expected.code) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here) + ); + } + } return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos); } @@ -5609,7 +5647,15 @@ namespace ts { if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { const multiLine = scanner.hasPrecedingLineBreak(); const statements = parseList(ParsingContext.BlockStatements, parseStatement); - parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBracePosition); + if (!parseExpected(SyntaxKind.CloseBraceToken)) { + const lastError = lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === Diagnostics._0_expected.code) { + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here) + ); + } + } const result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); if (token() === SyntaxKind.EqualsToken) { parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); @@ -5665,10 +5711,9 @@ namespace ts { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.IfKeyword); - const openParenPosition = scanner.getTokenPos(); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenPosition); + parseExpected(SyntaxKind.CloseParenToken); const thenStatement = parseStatement(); const elseStatement = parseOptional(SyntaxKind.ElseKeyword) ? parseStatement() : undefined; return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); @@ -5680,10 +5725,9 @@ namespace ts { parseExpected(SyntaxKind.DoKeyword); const statement = parseStatement(); parseExpected(SyntaxKind.WhileKeyword); - const openParenPosition = scanner.getTokenPos(); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenPosition); + parseExpected(SyntaxKind.CloseParenToken); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in @@ -5697,10 +5741,9 @@ namespace ts { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.WhileKeyword); - const openParenPosition = scanner.getTokenPos(); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenPosition); + parseExpected(SyntaxKind.CloseParenToken); const statement = parseStatement(); return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } @@ -5776,10 +5819,9 @@ namespace ts { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.WithKeyword); - const openParenPosition = scanner.getTokenPos(); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenPosition); + parseExpected(SyntaxKind.CloseParenToken); const statement = doInsideOfContext(NodeFlags.InWithStatement, parseStatement); return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } @@ -6287,7 +6329,7 @@ namespace ts { let propertyName: PropertyName | undefined = parsePropertyName(); let name: BindingName; if (tokenIsIdentifier && token() !== SyntaxKind.ColonToken) { - name = propertyName; + name = propertyName as Identifier; propertyName = undefined; } else { @@ -6743,11 +6785,11 @@ namespace ts { } function parseClassExpression(): ClassExpression { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, SyntaxKind.ClassExpression); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, SyntaxKind.ClassExpression) as ClassExpression; } function parseClassDeclaration(pos: number, hasJSDoc: boolean, decorators: NodeArray | undefined, modifiers: NodeArray | undefined): ClassDeclaration { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, SyntaxKind.ClassDeclaration); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, SyntaxKind.ClassDeclaration) as ClassDeclaration; } function parseClassDeclarationOrExpression(pos: number, hasJSDoc: boolean, decorators: NodeArray | undefined, modifiers: NodeArray | undefined, kind: ClassLikeDeclaration["kind"]): ClassLikeDeclaration { @@ -6898,7 +6940,7 @@ namespace ts { const namespaceFlag = flags & NodeFlags.Namespace; const name = parseIdentifier(); const body = parseOptional(SyntaxKind.DotToken) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag) as NamespaceDeclaration : parseModuleBlock(); const node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -6913,7 +6955,7 @@ namespace ts { flags |= NodeFlags.GlobalAugmentation; } else { - name = parseLiteralNode(); + name = parseLiteralNode() as StringLiteral; name.text = internIdentifier(name.text); } let body: ModuleBlock | undefined; @@ -7305,7 +7347,13 @@ namespace ts { export function parseJSDocNameReference(): JSDocNameReference { const pos = getNodePos(); const hasBrace = parseOptional(SyntaxKind.OpenBraceToken); - const entityName = parseEntityName(/* allowReservedWords*/ false); + const p2 = getNodePos(); + let entityName: EntityName | JSDocMemberName = parseEntityName(/* allowReservedWords*/ false); + while (token() === SyntaxKind.PrivateIdentifier) { + reScanHashToken(); // rescan #id as # id + nextTokenJSDoc(); // then skip the # + entityName = finishNode(factory.createJSDocMemberName(entityName, parseIdentifier()), p2); + } if (hasBrace) { parseExpectedJSDoc(SyntaxKind.CloseBraceToken); } @@ -7319,7 +7367,7 @@ namespace ts { initializeState("", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); const jsDoc = doInsideOfContext(NodeFlags.JSDoc, () => parseJSDocCommentWorker(start, length)); - const sourceFile = { languageVariant: LanguageVariant.Standard, text: content }; + const sourceFile = { languageVariant: LanguageVariant.Standard, text: content } as SourceFile; const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); clearState(); @@ -7379,7 +7427,7 @@ namespace ts { let linkEnd: number; let commentsPos: number | undefined; let comments: string[] = []; - const parts: (JSDocLink | JSDocText)[] = []; + const parts: JSDocComment[] = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, () => { @@ -7635,10 +7683,10 @@ namespace ts { return parseTagComments(margin, indentText.slice(margin)); } - function parseTagComments(indent: number, initialMargin?: string): string | NodeArray | undefined { + function parseTagComments(indent: number, initialMargin?: string): string | NodeArray | undefined { const commentsPos = getNodePos(); let comments: string[] = []; - const parts: (JSDocLink | JSDocText)[] = []; + const parts: JSDocComment[] = []; let linkEnd; let state = JSDocState.BeginningOfLine; let previousWhitespace = true; @@ -7754,29 +7802,45 @@ namespace ts { } function parseJSDocLink(start: number) { - if (!tryParse(parseJSDocLinkPrefix)) { + const linkType = tryParse(parseJSDocLinkPrefix); + if (!linkType) { return undefined; } nextTokenJSDoc(); // start at token after link, then skip any whitespace skipWhitespace(); // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error - const name = tokenIsIdentifierOrKeyword(token()) + const p2 = getNodePos(); + let name: EntityName | JSDocMemberName | undefined = tokenIsIdentifierOrKeyword(token()) ? parseEntityName(/*allowReservedWords*/ true) : undefined; + if (name) { + while (token() === SyntaxKind.PrivateIdentifier) { + reScanHashToken(); // rescan #id as # id + nextTokenJSDoc(); // then skip the # + name = finishNode(factory.createJSDocMemberName(name, parseIdentifier()), p2); + } + } const text = []; while (token() !== SyntaxKind.CloseBraceToken && token() !== SyntaxKind.NewLineTrivia && token() !== SyntaxKind.EndOfFileToken) { text.push(scanner.getTokenText()); nextTokenJSDoc(); } - return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + const create = linkType === "link" ? factory.createJSDocLink + : linkType === "linkcode" ? factory.createJSDocLinkCode + : factory.createJSDocLinkPlain; + return finishNode(create(name, text.join("")), start, scanner.getTextPos()); } function parseJSDocLinkPrefix() { skipWhitespaceOrAsterisk(); - return token() === SyntaxKind.OpenBraceToken + if (token() === SyntaxKind.OpenBraceToken && nextTokenJSDoc() === SyntaxKind.AtToken - && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) - && scanner.getTokenValue() === "link"; + && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { + const kind = scanner.getTokenValue(); + if(kind === "link" || kind === "linkcode" || kind === "linkplain") { + return kind; + } + } } function parseUnknownTag(start: number, tagName: Identifier, indent: number, indentText: string) { @@ -7915,7 +7979,7 @@ namespace ts { commentEnd = scanner.getStartPos(); } const allParts = typeof comments !== "string" - ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments) as (JSDocText | JSDocLink)[], commentStart) // cast away readonly + ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments) as JSDocComment[], commentStart) // cast away readonly : textOnly.text + comments; return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } @@ -7976,7 +8040,7 @@ namespace ts { return node; } - function parseSimpleTag(start: number, createTag: (tagName: Identifier | undefined, comment?: string | NodeArray) => JSDocTag, tagName: Identifier, margin: number, indentText: string): JSDocTag { + function parseSimpleTag(start: number, createTag: (tagName: Identifier | undefined, comment?: string | NodeArray) => JSDocTag, tagName: Identifier, margin: number, indentText: string): JSDocTag { return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } @@ -8010,9 +8074,13 @@ namespace ts { hasChildren = true; if (child.kind === SyntaxKind.JSDocTypeTag) { if (childTypeTag) { - const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); + parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); + const lastError = lastOrUndefined(parseDiagnostics); if (lastError) { - addRelatedInfo(lastError, createDetachedDiagnostic(fileName, 0, 0, Diagnostics.The_tag_was_first_specified_here)); + addRelatedInfo( + lastError, + createDetachedDiagnostic(fileName, 0, 0, Diagnostics.The_tag_was_first_specified_here) + ); } break; } @@ -8290,7 +8358,7 @@ namespace ts { // This is because we do incremental parsing in-place. i.e. we take nodes from the old // tree and give them new positions and parents. From that point on, trusting the old // tree at all is not possible as far too much of it may violate invariants. - const incrementalSourceFile = sourceFile; + const incrementalSourceFile = sourceFile as Node as IncrementalNode; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; Parser.fixupParentReferences(incrementalSourceFile); @@ -8410,10 +8478,10 @@ namespace ts { function moveElementEntirelyPastChangeRange(element: IncrementalElement, isArray: boolean, delta: number, oldText: string, newText: string, aggressiveChecks: boolean) { if (isArray) { - visitArray(element); + visitArray(element as IncrementalNodeArray); } else { - visitNode(element); + visitNode(element as IncrementalNode); } return; @@ -8438,7 +8506,7 @@ namespace ts { forEachChild(node, visitNode, visitArray); if (hasJSDocNodes(node)) { for (const jsDocComment of node.jsDoc!) { - visitNode(jsDocComment); + visitNode(jsDocComment as Node as IncrementalNode); } } checkNodePositions(node, aggressiveChecks); @@ -8591,7 +8659,7 @@ namespace ts { forEachChild(child, visitNode, visitArray); if (hasJSDocNodes(child)) { for (const jsDocComment of child.jsDoc!) { - visitNode(jsDocComment); + visitNode(jsDocComment as Node as IncrementalNode); } } checkNodePositions(child, aggressiveChecks); @@ -8827,7 +8895,7 @@ namespace ts { // Either we don'd have a node, or we have a node at the position being asked for. Debug.assert(!current || current.pos === position); - return current; + return current as IncrementalNode; } }; @@ -9124,7 +9192,7 @@ namespace ts { } if (lhs.kind === SyntaxKind.Identifier) { - return lhs.escapedText === (rhs).escapedText; + return lhs.escapedText === (rhs as Identifier).escapedText; } if (lhs.kind === SyntaxKind.ThisKeyword) { @@ -9134,7 +9202,7 @@ namespace ts { // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return (lhs).name.escapedText === (rhs).name.escapedText && - tagNamesAreEquivalent((lhs).expression as JsxTagNameExpression, (rhs).expression as JsxTagNameExpression); + return (lhs as PropertyAccessExpression).name.escapedText === (rhs as PropertyAccessExpression).name.escapedText && + tagNamesAreEquivalent((lhs as PropertyAccessExpression).expression as JsxTagNameExpression, (rhs as PropertyAccessExpression).expression as JsxTagNameExpression); } } diff --git a/src/compiler/path.ts b/src/compiler/path.ts index 6a9374873b1a0..d09108d34c7f3 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -452,6 +452,11 @@ namespace ts { * Normalize path separators, converting `\` into `/`. */ export function normalizeSlashes(path: string): string { + const index = path.indexOf("\\"); + if (index === -1) { + return path; + } + backslashRegExp.lastIndex = index; // prime regex with known position return path.replace(backslashRegExp, directorySeparator); } @@ -547,6 +552,19 @@ namespace ts { export function normalizePath(path: string): string { path = normalizeSlashes(path); + // Most paths don't require normalization + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + // Some paths only require cleanup of `/./` or leading `./` + const simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); + if (simplified !== path) { + path = simplified; + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + } + // Other paths require full normalization const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; } @@ -564,7 +582,7 @@ namespace ts { const nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); + return getCanonicalFileName(nonCanonicalizedPath) as Path; } export function normalizePathAndParts(path: string): { path: string, parts: string[] } { @@ -658,7 +676,7 @@ namespace ts { //// Path Comparisons // check path for these segments: '', '.'. '..' - const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + const relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) { if (a === b) return Comparison.EqualTo; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index a50b60a3171b2..caf3ebb1c7d90 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1281,7 +1281,7 @@ namespace ts { let result: ResolvedModuleFull[] | undefined; let reusedNames: string[] | undefined; /** A transient placeholder used to mark predicted resolution in the result list. */ - const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = {}; + const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = {} as any; for (let i = 0; i < moduleNames.length; i++) { const moduleName = moduleNames[i]; @@ -2005,7 +2005,7 @@ namespace ts { case SyntaxKind.Parameter: case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: - if ((parent).questionToken === node) { + if ((parent as ParameterDeclaration | PropertyDeclaration | MethodDeclaration).questionToken === node) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } @@ -2019,7 +2019,7 @@ namespace ts { case SyntaxKind.ArrowFunction: case SyntaxKind.VariableDeclaration: // type annotation - if ((parent).type === node) { + if ((parent as FunctionLikeDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration).type === node) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -2042,13 +2042,13 @@ namespace ts { diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; case SyntaxKind.ExportAssignment: - if ((node).isExportEquals) { + if ((node as ExportAssignment).isExportEquals) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; case SyntaxKind.HeritageClause: - const heritageClause = node; + const heritageClause = node as HeritageClause; if (heritageClause.token === SyntaxKind.ImplementsKeyword) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; @@ -2098,7 +2098,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: // Check type parameters - if (nodes === (parent).typeParameters) { + if (nodes === (parent as DeclarationWithTypeParameterChildren).typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -2113,8 +2113,8 @@ namespace ts { break; case SyntaxKind.PropertyDeclaration: // Check modifiers of property declaration - if (nodes === (parent).modifiers) { - for (const modifier of >nodes) { + if (nodes === (parent as PropertyDeclaration).modifiers) { + for (const modifier of nodes as NodeArray) { if (modifier.kind !== SyntaxKind.StaticKeyword) { diagnostics.push(createDiagnosticForNode(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); } @@ -2124,7 +2124,7 @@ namespace ts { break; case SyntaxKind.Parameter: // Check modifiers of parameter declaration - if (nodes === (parent).modifiers) { + if (nodes === (parent as ParameterDeclaration).modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -2136,7 +2136,7 @@ namespace ts { case SyntaxKind.JsxOpeningElement: case SyntaxKind.TaggedTemplateExpression: // Check type arguments - if (nodes === (parent).typeArguments) { + if (nodes === (parent as NodeWithTypeArguments).typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -2348,7 +2348,7 @@ namespace ts { // Relative external module names are not permitted // NOTE: body of ambient module is always a module block, if it exists - const body = (node).body; + const body = (node as ModuleDeclaration).body as ModuleBlock; if (body) { for (const statement of body.statements) { collectModuleReferences(statement, /*inAmbientModule*/ true); diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index ba449e81b96e1..6e5e54d7a5211 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -42,6 +42,7 @@ namespace ts { reScanJsxAttributeValue(): SyntaxKind; reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; + reScanHashToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; @@ -220,7 +221,8 @@ namespace ts { "&&=": SyntaxKind.AmpersandAmpersandEqualsToken, "??=": SyntaxKind.QuestionQuestionEqualsToken, "@": SyntaxKind.AtToken, - "`": SyntaxKind.BacktickToken + "#": SyntaxKind.HashToken, + "`": SyntaxKind.BacktickToken, })); /* @@ -981,6 +983,7 @@ namespace ts { reScanJsxAttributeValue, reScanJsxToken, reScanLessThanToken, + reScanHashToken, reScanQuestionToken, reScanInvalidIdentifier, scanJsxToken, @@ -1610,7 +1613,7 @@ namespace ts { if (pos >= end) { return token = SyntaxKind.EndOfFileToken; } - let ch = codePointAt(text, pos); + const ch = codePointAt(text, pos); // Special handling for shebang if (ch === CharacterCodes.hash && pos === 0 && isShebangTrivia(text, pos)) { @@ -2044,18 +2047,7 @@ namespace ts { return token = SyntaxKind.Unknown; } pos++; - if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) { - pos++; - while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) pos++; - tokenValue = text.substring(tokenPos, pos); - if (ch === CharacterCodes.backslash) { - tokenValue += scanIdentifierParts(); - } - } - else { - tokenValue = "#"; - error(Diagnostics.Invalid_character); - } + scanIdentifier(codePointAt(text, pos), languageVersion); return token = SyntaxKind.PrivateIdentifier; default: const identifierKind = scanIdentifier(ch, languageVersion); @@ -2251,6 +2243,14 @@ namespace ts { return token; } + function reScanHashToken(): SyntaxKind { + if (token === SyntaxKind.PrivateIdentifier) { + pos = tokenPos + 1; + return token = SyntaxKind.HashToken; + } + return token; + } + function reScanQuestionToken(): SyntaxKind { Debug.assert(token === SyntaxKind.QuestionQuestionToken, "'reScanQuestionToken' should only be called on a '??'"); pos = tokenPos + 1; @@ -2437,6 +2437,8 @@ namespace ts { return token = SyntaxKind.DotToken; case CharacterCodes.backtick: return token = SyntaxKind.BacktickToken; + case CharacterCodes.hash: + return token = SyntaxKind.HashToken; case CharacterCodes.backslash: pos--; const extendedCookedChar = peekExtendedUnicodeEscape(); diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 0db89a5830fd2..6ca09906db47f 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -17,6 +17,7 @@ namespace ts { const names: string[] = []; let nameToNameIndexMap: ESMap | undefined; + const mappingCharCodes: number[] = []; let mappings = ""; // Last recorded and encoded mappings @@ -210,6 +211,15 @@ namespace ts { || lastNameIndex !== pendingNameIndex; } + function appendMappingCharCode(charCode: number) { + mappingCharCodes.push(charCode); + // String.fromCharCode accepts its arguments on the stack, so we have to chunk the input, + // otherwise we can get stack overflows for large source maps + if (mappingCharCodes.length >= 1024) { + flushMappingBuffer(); + } + } + function commitPendingMapping() { if (!hasPending || !shouldCommitMapping()) { return; @@ -221,40 +231,41 @@ namespace ts { if (lastGeneratedLine < pendingGeneratedLine) { // Emit line delimiters do { - mappings += ";"; + appendMappingCharCode(CharacterCodes.semicolon); lastGeneratedLine++; - lastGeneratedCharacter = 0; } while (lastGeneratedLine < pendingGeneratedLine); + // Only need to set this once + lastGeneratedCharacter = 0; } else { Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack"); // Emit comma to separate the entry if (hasLast) { - mappings += ","; + appendMappingCharCode(CharacterCodes.comma); } } // 1. Relative generated character - mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter); + appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter); lastGeneratedCharacter = pendingGeneratedCharacter; if (hasPendingSource) { // 2. Relative sourceIndex - mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex); + appendBase64VLQ(pendingSourceIndex - lastSourceIndex); lastSourceIndex = pendingSourceIndex; // 3. Relative source line - mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine); + appendBase64VLQ(pendingSourceLine - lastSourceLine); lastSourceLine = pendingSourceLine; // 4. Relative source character - mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter); + appendBase64VLQ(pendingSourceCharacter - lastSourceCharacter); lastSourceCharacter = pendingSourceCharacter; if (hasPendingName) { // 5. Relative nameIndex - mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex); + appendBase64VLQ(pendingNameIndex - lastNameIndex); lastNameIndex = pendingNameIndex; } } @@ -263,8 +274,16 @@ namespace ts { exit(); } + function flushMappingBuffer(): void { + if (mappingCharCodes.length > 0) { + mappings += String.fromCharCode.apply(undefined, mappingCharCodes); + mappingCharCodes.length = 0; + } + } + function toJSON(): RawSourceMap { commitPendingMapping(); + flushMappingBuffer(); return { version: 3, file, @@ -275,6 +294,31 @@ namespace ts { sourcesContent, }; } + + function appendBase64VLQ(inValue: number): void { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + + // Encode 5 bits at a time starting from least significant bits + do { + let currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + appendMappingCharCode(base64FormatEncode(currentDigit)); + } while (inValue > 0); + } } // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) @@ -544,34 +588,6 @@ namespace ts { -1; } - function base64VLQFormatEncode(inValue: number) { - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - - // Encode 5 bits at a time starting from least significant bits - let encodedStr = ""; - do { - let currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit)); - } while (inValue > 0); - - return encodedStr; - } - interface MappedPosition { generatedPosition: number; source: string | undefined; diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 37ea6450f7c1f..3366c444559b2 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -1370,7 +1370,7 @@ namespace ts { disableCPUProfiler, cpuProfilingEnabled: () => !!activeSession || contains(process.execArgv, "--cpu-prof") || contains(process.execArgv, "--prof"), realpath, - debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), + debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv as string[], arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)), tryEnableSourceMapsForHost() { try { require("source-map-support").install(); diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 407cff5d4bb5b..e820851dde949 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -658,13 +658,14 @@ namespace ts { } const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + let pendingPrivateStateAssignment: BinaryExpression | undefined; if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) { const temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); - getPendingExpressions().push(factory.createAssignment( + pendingPrivateStateAssignment = factory.createAssignment( temp, factory.getInternalName(node) - )); + ); } const extendsClauseElement = getEffectiveBaseTypeNode(node); @@ -682,6 +683,10 @@ namespace ts { ) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } + // Write any pending expressions from elided or moved computed property names if (some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 0e7eaac22c9af..64900c56a887a 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -114,9 +114,9 @@ namespace ts { function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) { Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression); const expression = createAssignmentCallback - ? createAssignmentCallback(target, value, location) + ? createAssignmentCallback(target as Identifier, value, location) : setTextRange( - context.factory.createAssignment(visitNode(target, visitor, isExpression), value), + context.factory.createAssignment(visitNode(target as Expression, visitor, isExpression), value), location ); expression.original = original; @@ -410,7 +410,7 @@ namespace ts { flattenContext.context.hoistVariableDeclaration(temp); } - restContainingElements = append(restContainingElements, <[Identifier, BindingOrAssignmentElement]>[temp, element]); + restContainingElements = append(restContainingElements, [temp, element] as [Identifier, BindingOrAssignmentElement]); bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); } else { @@ -518,7 +518,7 @@ namespace ts { function makeArrayBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { Debug.assertEachNode(elements, isArrayBindingElement); - return factory.createArrayBindingPattern(elements); + return factory.createArrayBindingPattern(elements as ArrayBindingElement[]); } function makeArrayAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { @@ -527,7 +527,7 @@ namespace ts { function makeObjectBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { Debug.assertEachNode(elements, isBindingElement); - return factory.createObjectBindingPattern(elements); + return factory.createObjectBindingPattern(elements as BindingElement[]); } function makeObjectAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 5cb0aa35498ec..8fa7abb198dbd 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -327,7 +327,7 @@ namespace ts { function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean { return (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper) !== 0 && node.kind === SyntaxKind.ReturnStatement - && !(node).expression; + && !(node as ReturnStatement).expression; } function isOrMayContainReturnCompletion(node: Node) { @@ -375,117 +375,117 @@ namespace ts { return undefined; // elide static keyword case SyntaxKind.ClassDeclaration: - return visitClassDeclaration(node); + return visitClassDeclaration(node as ClassDeclaration); case SyntaxKind.ClassExpression: - return visitClassExpression(node); + return visitClassExpression(node as ClassExpression); case SyntaxKind.Parameter: - return visitParameter(node); + return visitParameter(node as ParameterDeclaration); case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node); + return visitFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.ArrowFunction: - return visitArrowFunction(node); + return visitArrowFunction(node as ArrowFunction); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node); + return visitFunctionExpression(node as FunctionExpression); case SyntaxKind.VariableDeclaration: - return visitVariableDeclaration(node); + return visitVariableDeclaration(node as VariableDeclaration); case SyntaxKind.Identifier: - return visitIdentifier(node); + return visitIdentifier(node as Identifier); case SyntaxKind.VariableDeclarationList: - return visitVariableDeclarationList(node); + return visitVariableDeclarationList(node as VariableDeclarationList); case SyntaxKind.SwitchStatement: - return visitSwitchStatement(node); + return visitSwitchStatement(node as SwitchStatement); case SyntaxKind.CaseBlock: - return visitCaseBlock(node); + return visitCaseBlock(node as CaseBlock); case SyntaxKind.Block: - return visitBlock(node, /*isFunctionBody*/ false); + return visitBlock(node as Block, /*isFunctionBody*/ false); case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: - return visitBreakOrContinueStatement(node); + return visitBreakOrContinueStatement(node as BreakOrContinueStatement); case SyntaxKind.LabeledStatement: - return visitLabeledStatement(node); + return visitLabeledStatement(node as LabeledStatement); case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); + return visitDoOrWhileStatement(node as DoStatement | WhileStatement, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForStatement: - return visitForStatement(node, /*outermostLabeledStatement*/ undefined); + return visitForStatement(node as ForStatement, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForInStatement: - return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); + return visitForInStatement(node as ForInStatement, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForOfStatement: - return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); + return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ExpressionStatement: - return visitExpressionStatement(node); + return visitExpressionStatement(node as ExpressionStatement); case SyntaxKind.ObjectLiteralExpression: - return visitObjectLiteralExpression(node); + return visitObjectLiteralExpression(node as ObjectLiteralExpression); case SyntaxKind.CatchClause: - return visitCatchClause(node); + return visitCatchClause(node as CatchClause); case SyntaxKind.ShorthandPropertyAssignment: - return visitShorthandPropertyAssignment(node); + return visitShorthandPropertyAssignment(node as ShorthandPropertyAssignment); case SyntaxKind.ComputedPropertyName: - return visitComputedPropertyName(node); + return visitComputedPropertyName(node as ComputedPropertyName); case SyntaxKind.ArrayLiteralExpression: - return visitArrayLiteralExpression(node); + return visitArrayLiteralExpression(node as ArrayLiteralExpression); case SyntaxKind.CallExpression: - return visitCallExpression(node); + return visitCallExpression(node as CallExpression); case SyntaxKind.NewExpression: - return visitNewExpression(node); + return visitNewExpression(node as NewExpression); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node, expressionResultIsUnused); + return visitParenthesizedExpression(node as ParenthesizedExpression, expressionResultIsUnused); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node, expressionResultIsUnused); + return visitBinaryExpression(node as BinaryExpression, expressionResultIsUnused); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node, expressionResultIsUnused); + return visitCommaListExpression(node as CommaListExpression, expressionResultIsUnused); case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: case SyntaxKind.TemplateTail: - return visitTemplateLiteral(node); + return visitTemplateLiteral(node as LiteralExpression); case SyntaxKind.StringLiteral: - return visitStringLiteral(node); + return visitStringLiteral(node as StringLiteral); case SyntaxKind.NumericLiteral: - return visitNumericLiteral(node); + return visitNumericLiteral(node as NumericLiteral); case SyntaxKind.TaggedTemplateExpression: - return visitTaggedTemplateExpression(node); + return visitTaggedTemplateExpression(node as TaggedTemplateExpression); case SyntaxKind.TemplateExpression: - return visitTemplateExpression(node); + return visitTemplateExpression(node as TemplateExpression); case SyntaxKind.YieldExpression: - return visitYieldExpression(node); + return visitYieldExpression(node as YieldExpression); case SyntaxKind.SpreadElement: - return visitSpreadElement(node); + return visitSpreadElement(node as SpreadElement); case SyntaxKind.SuperKeyword: return visitSuperKeyword(/*isExpressionOfCall*/ false); @@ -494,20 +494,20 @@ namespace ts { return visitThisKeyword(node); case SyntaxKind.MetaProperty: - return visitMetaProperty(node); + return visitMetaProperty(node as MetaProperty); case SyntaxKind.MethodDeclaration: - return visitMethodDeclaration(node); + return visitMethodDeclaration(node as MethodDeclaration); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return visitAccessorDeclaration(node); + return visitAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.VariableStatement: - return visitVariableStatement(node); + return visitVariableStatement(node as VariableStatement); case SyntaxKind.ReturnStatement: - return visitReturnStatement(node); + return visitReturnStatement(node as ReturnStatement); case SyntaxKind.VoidExpression: return visitVoidExpression(node as VoidExpression); @@ -919,7 +919,7 @@ namespace ts { // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) - || []; + || [] as ParameterDeclaration[]; } function createDefaultConstructorBody(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) { @@ -1578,16 +1578,16 @@ namespace ts { for (const member of node.members) { switch (member.kind) { case SyntaxKind.SemicolonClassElement: - statements.push(transformSemicolonClassElementToStatement(member)); + statements.push(transformSemicolonClassElementToStatement(member as SemicolonClassElement)); break; case SyntaxKind.MethodDeclaration: - statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member as MethodDeclaration, node)); break; case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - const accessors = getAllAccessorDeclarations(node.members, member); + const accessors = getAllAccessorDeclarations(node.members, member as AccessorDeclaration); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } @@ -2274,13 +2274,13 @@ namespace ts { switch (node.kind) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - return visitDoOrWhileStatement(node, outermostLabeledStatement); + return visitDoOrWhileStatement(node as DoStatement | WhileStatement, outermostLabeledStatement); case SyntaxKind.ForStatement: - return visitForStatement(node, outermostLabeledStatement); + return visitForStatement(node as ForStatement, outermostLabeledStatement); case SyntaxKind.ForInStatement: - return visitForInStatement(node, outermostLabeledStatement); + return visitForInStatement(node as ForInStatement, outermostLabeledStatement); case SyntaxKind.ForOfStatement: - return visitForOfStatement(node, outermostLabeledStatement); + return visitForOfStatement(node as ForOfStatement, outermostLabeledStatement); } } @@ -2853,9 +2853,9 @@ namespace ts { case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - const initializer = (node).initializer; + const initializer = (node as ForStatement | ForInStatement | ForOfStatement).initializer; if (initializer && initializer.kind === SyntaxKind.VariableDeclarationList) { - loopInitializer = initializer; + loopInitializer = initializer as VariableDeclarationList; } break; } @@ -3243,7 +3243,7 @@ namespace ts { !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - const call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => p.name)); + const call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => p.name as Identifier)); const callResult = containsYield ? factory.createYieldExpression( factory.createToken(SyntaxKind.AsteriskToken), @@ -4250,8 +4250,8 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (node.parent).name === node - && resolver.isDeclarationWithCollidingName(node.parent); + return (node.parent as NamedDeclaration).name === node + && resolver.isDeclarationWithCollidingName(node.parent as Declaration); } return false; @@ -4265,10 +4265,10 @@ namespace ts { function substituteExpression(node: Node) { switch (node.kind) { case SyntaxKind.Identifier: - return substituteExpressionIdentifier(node); + return substituteExpressionIdentifier(node as Identifier); case SyntaxKind.ThisKeyword: - return substituteThisKeyword(node); + return substituteThisKeyword(node as PrimaryExpression); } return node; @@ -4347,22 +4347,22 @@ namespace ts { return false; } - const statementExpression = (statement).expression; + const statementExpression = (statement as ExpressionStatement).expression; if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== SyntaxKind.CallExpression) { return false; } - const callTarget = (statementExpression).expression; + const callTarget = (statementExpression as CallExpression).expression; if (!nodeIsSynthesized(callTarget) || callTarget.kind !== SyntaxKind.SuperKeyword) { return false; } - const callArgument = singleOrUndefined((statementExpression).arguments); + const callArgument = singleOrUndefined((statementExpression as CallExpression).arguments); if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) { return false; } - const expression = (callArgument).expression; + const expression = (callArgument as SpreadElement).expression; return isIdentifier(expression) && expression.escapedText === "arguments"; } } diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts index 653c66174d4ff..9da96caed3107 100644 --- a/src/compiler/transformers/es2016.ts +++ b/src/compiler/transformers/es2016.ts @@ -22,7 +22,7 @@ namespace ts { } switch (node.kind) { case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node); + return visitBinaryExpression(node as BinaryExpression); default: return visitEachChild(node, visitor, context); } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index a2d2985e75b55..ade1d41b010c8 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -113,19 +113,19 @@ namespace ts { return undefined; case SyntaxKind.AwaitExpression: - return visitAwaitExpression(node); + return visitAwaitExpression(node as AwaitExpression); case SyntaxKind.MethodDeclaration: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, node); + return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, node as MethodDeclaration); case SyntaxKind.FunctionDeclaration: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, node); + return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, node as FunctionDeclaration); case SyntaxKind.FunctionExpression: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, node); + return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, node as FunctionExpression); case SyntaxKind.ArrowFunction: - return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, node); + return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, node as ArrowFunction); case SyntaxKind.PropertyAccessExpression: if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { @@ -134,7 +134,7 @@ namespace ts { return visitEachChild(node, visitor, context); case SyntaxKind.ElementAccessExpression: - if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) { hasSuperElementAccess = true; } return visitEachChild(node, visitor, context); @@ -481,14 +481,14 @@ namespace ts { let result: ConciseBody; if (!isArrowFunction) { const statements: Statement[] = []; - const statementOffset = factory.copyPrologue((node.body).statements, statements, /*ensureUseStrict*/ false, visitor); + const statementOffset = factory.copyPrologue((node.body as Block).statements, statements, /*ensureUseStrict*/ false, visitor); statements.push( factory.createReturnStatement( emitHelpers().createAwaiterHelper( inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, - transformAsyncFunctionBodyWorker(node.body, statementOffset) + transformAsyncFunctionBodyWorker(node.body as Block, statementOffset) ) ) ); @@ -632,7 +632,7 @@ namespace ts { function onSubstituteNode(hint: EmitHint, node: Node) { node = previousOnSubstituteNode(hint, node); if (hint === EmitHint.Expression && enclosingSuperContainerFlags) { - return substituteExpression(node); + return substituteExpression(node as Expression); } return node; @@ -641,11 +641,11 @@ namespace ts { function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.PropertyAccessExpression: - return substitutePropertyAccessExpression(node); + return substitutePropertyAccessExpression(node as PropertyAccessExpression); case SyntaxKind.ElementAccessExpression: - return substituteElementAccessExpression(node); + return substituteElementAccessExpression(node as ElementAccessExpression); case SyntaxKind.CallExpression: - return substituteCallExpression(node); + return substituteCallExpression(node as CallExpression); } return node; } diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index b7b04f191cf62..846fd992ff21b 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -250,7 +250,7 @@ namespace ts { } return visitEachChild(node, visitor, context); case SyntaxKind.ElementAccessExpression: - if (capturedSuperProperties && (node).expression.kind === SyntaxKind.SuperKeyword) { + if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) { hasSuperElementAccess = true; } return visitEachChild(node, visitor, context); @@ -342,8 +342,8 @@ namespace ts { function visitLabeledStatement(node: LabeledStatement) { if (enclosingFunctionFlags & FunctionFlags.Async) { const statement = unwrapInnermostStatementOfLabel(node); - if (statement.kind === SyntaxKind.ForOfStatement && (statement).awaitModifier) { - return visitForOfStatement(statement, node); + if (statement.kind === SyntaxKind.ForOfStatement && (statement as ForOfStatement).awaitModifier) { + return visitForOfStatement(statement as ForOfStatement, node); } return factory.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory.liftToBlock), node); } @@ -1107,7 +1107,7 @@ namespace ts { function onSubstituteNode(hint: EmitHint, node: Node) { node = previousOnSubstituteNode(hint, node); if (hint === EmitHint.Expression && enclosingSuperContainerFlags) { - return substituteExpression(node); + return substituteExpression(node as Expression); } return node; } @@ -1115,11 +1115,11 @@ namespace ts { function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.PropertyAccessExpression: - return substitutePropertyAccessExpression(node); + return substitutePropertyAccessExpression(node as PropertyAccessExpression); case SyntaxKind.ElementAccessExpression: - return substituteElementAccessExpression(node); + return substituteElementAccessExpression(node as ElementAccessExpression); case SyntaxKind.CallExpression: - return substituteCallExpression(node); + return substituteCallExpression(node as CallExpression); } return node; } diff --git a/src/compiler/transformers/es2020.ts b/src/compiler/transformers/es2020.ts index 2434e36559be1..5e2311a2d27db 100644 --- a/src/compiler/transformers/es2020.ts +++ b/src/compiler/transformers/es2020.ts @@ -35,8 +35,8 @@ namespace ts { } return visitEachChild(node, visitor, context); case SyntaxKind.BinaryExpression: - if ((node).operatorToken.kind === SyntaxKind.QuestionQuestionToken) { - return transformNullishCoalescingExpression(node); + if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken) { + return transformNullishCoalescingExpression(node as BinaryExpression); } return visitEachChild(node, visitor, context); case SyntaxKind.DeleteExpression: diff --git a/src/compiler/transformers/es2021.ts b/src/compiler/transformers/es2021.ts index 271ee58e7f214..392846f7d3359 100644 --- a/src/compiler/transformers/es2021.ts +++ b/src/compiler/transformers/es2021.ts @@ -21,7 +21,7 @@ namespace ts { } switch (node.kind) { case SyntaxKind.BinaryExpression: - const binaryExpression = node; + const binaryExpression = node as BinaryExpression; if (isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); } diff --git a/src/compiler/transformers/es5.ts b/src/compiler/transformers/es5.ts index 74fff32a2644e..e82ba20cf5f9f 100644 --- a/src/compiler/transformers/es5.ts +++ b/src/compiler/transformers/es5.ts @@ -48,7 +48,7 @@ namespace ts { case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxClosingElement: case SyntaxKind.JsxSelfClosingElement: - const tagName = (node).tagName; + const tagName = (node as JsxOpeningElement | JsxClosingElement | JsxSelfClosingElement).tagName; noSubstitution[getOriginalNodeId(tagName)] = true; break; } diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index fca06a8ce22ca..73e35b4583d0e 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -337,13 +337,13 @@ namespace ts { function visitJavaScriptInStatementContainingYield(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.DoStatement: - return visitDoStatement(node); + return visitDoStatement(node as DoStatement); case SyntaxKind.WhileStatement: - return visitWhileStatement(node); + return visitWhileStatement(node as WhileStatement); case SyntaxKind.SwitchStatement: - return visitSwitchStatement(node); + return visitSwitchStatement(node as SwitchStatement); case SyntaxKind.LabeledStatement: - return visitLabeledStatement(node); + return visitLabeledStatement(node as LabeledStatement); default: return visitJavaScriptInGeneratorFunctionBody(node); } @@ -357,24 +357,24 @@ namespace ts { function visitJavaScriptInGeneratorFunctionBody(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node); + return visitFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node); + return visitFunctionExpression(node as FunctionExpression); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return visitAccessorDeclaration(node); + return visitAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.VariableStatement: - return visitVariableStatement(node); + return visitVariableStatement(node as VariableStatement); case SyntaxKind.ForStatement: - return visitForStatement(node); + return visitForStatement(node as ForStatement); case SyntaxKind.ForInStatement: - return visitForInStatement(node); + return visitForInStatement(node as ForInStatement); case SyntaxKind.BreakStatement: - return visitBreakStatement(node); + return visitBreakStatement(node as BreakStatement); case SyntaxKind.ContinueStatement: - return visitContinueStatement(node); + return visitContinueStatement(node as ContinueStatement); case SyntaxKind.ReturnStatement: - return visitReturnStatement(node); + return visitReturnStatement(node as ReturnStatement); default: if (node.transformFlags & TransformFlags.ContainsYield) { return visitJavaScriptContainingYield(node); @@ -396,23 +396,23 @@ namespace ts { function visitJavaScriptContainingYield(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node); + return visitBinaryExpression(node as BinaryExpression); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node); + return visitCommaListExpression(node as CommaListExpression); case SyntaxKind.ConditionalExpression: - return visitConditionalExpression(node); + return visitConditionalExpression(node as ConditionalExpression); case SyntaxKind.YieldExpression: - return visitYieldExpression(node); + return visitYieldExpression(node as YieldExpression); case SyntaxKind.ArrayLiteralExpression: - return visitArrayLiteralExpression(node); + return visitArrayLiteralExpression(node as ArrayLiteralExpression); case SyntaxKind.ObjectLiteralExpression: - return visitObjectLiteralExpression(node); + return visitObjectLiteralExpression(node as ObjectLiteralExpression); case SyntaxKind.ElementAccessExpression: - return visitElementAccessExpression(node); + return visitElementAccessExpression(node as ElementAccessExpression); case SyntaxKind.CallExpression: - return visitCallExpression(node); + return visitCallExpression(node as CallExpression); case SyntaxKind.NewExpression: - return visitNewExpression(node); + return visitNewExpression(node as NewExpression); default: return visitEachChild(node, visitor, context); } @@ -426,10 +426,10 @@ namespace ts { function visitGenerator(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node); + return visitFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node); + return visitFunctionExpression(node as FunctionExpression); default: return Debug.failBadSyntaxKind(node); @@ -632,7 +632,7 @@ namespace ts { } for (const variable of node.declarationList.declarations) { - hoistVariableDeclaration(variable.name); + hoistVariableDeclaration(variable.name as Identifier); } const variables = getInitializedVariables(node.declarationList); @@ -693,9 +693,9 @@ namespace ts { // _a.b = %sent%; target = factory.updatePropertyAccessExpression( - left, - cacheExpression(visitNode((left).expression, visitor, isLeftHandSideExpression)), - (left).name + left as PropertyAccessExpression, + cacheExpression(visitNode((left as PropertyAccessExpression).expression, visitor, isLeftHandSideExpression)), + (left as PropertyAccessExpression).name ); break; @@ -711,9 +711,9 @@ namespace ts { // .mark resumeLabel // _a[_b] = %sent%; - target = factory.updateElementAccessExpression(left, - cacheExpression(visitNode((left).expression, visitor, isLeftHandSideExpression)), - cacheExpression(visitNode((left).argumentExpression, visitor, isExpression)) + target = factory.updateElementAccessExpression(left as ElementAccessExpression, + cacheExpression(visitNode((left as ElementAccessExpression).expression, visitor, isLeftHandSideExpression)), + cacheExpression(visitNode((left as ElementAccessExpression).argumentExpression, visitor, isExpression)) ); break; @@ -1000,7 +1000,7 @@ namespace ts { leadingElement = undefined; } - const expressions = reduceLeft(elements, reduceElement, [], numInitialElements); + const expressions = reduceLeft(elements, reduceElement, [] as Expression[], numInitialElements); return temp ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange( @@ -1067,7 +1067,7 @@ namespace ts { ) ); - const expressions = reduceLeft(properties, reduceProperty, [], numInitialProperties); + const expressions = reduceLeft(properties, reduceProperty, [] as Expression[], numInitialProperties); // TODO(rbuckton): Does this need to be parented? expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp); return factory.inlineExpressions(expressions); @@ -1209,35 +1209,35 @@ namespace ts { function transformAndEmitStatementWorker(node: Statement): void { switch (node.kind) { case SyntaxKind.Block: - return transformAndEmitBlock(node); + return transformAndEmitBlock(node as Block); case SyntaxKind.ExpressionStatement: - return transformAndEmitExpressionStatement(node); + return transformAndEmitExpressionStatement(node as ExpressionStatement); case SyntaxKind.IfStatement: - return transformAndEmitIfStatement(node); + return transformAndEmitIfStatement(node as IfStatement); case SyntaxKind.DoStatement: - return transformAndEmitDoStatement(node); + return transformAndEmitDoStatement(node as DoStatement); case SyntaxKind.WhileStatement: - return transformAndEmitWhileStatement(node); + return transformAndEmitWhileStatement(node as WhileStatement); case SyntaxKind.ForStatement: - return transformAndEmitForStatement(node); + return transformAndEmitForStatement(node as ForStatement); case SyntaxKind.ForInStatement: - return transformAndEmitForInStatement(node); + return transformAndEmitForInStatement(node as ForInStatement); case SyntaxKind.ContinueStatement: - return transformAndEmitContinueStatement(node); + return transformAndEmitContinueStatement(node as ContinueStatement); case SyntaxKind.BreakStatement: - return transformAndEmitBreakStatement(node); + return transformAndEmitBreakStatement(node as BreakStatement); case SyntaxKind.ReturnStatement: - return transformAndEmitReturnStatement(node); + return transformAndEmitReturnStatement(node as ReturnStatement); case SyntaxKind.WithStatement: - return transformAndEmitWithStatement(node); + return transformAndEmitWithStatement(node as WithStatement); case SyntaxKind.SwitchStatement: - return transformAndEmitSwitchStatement(node); + return transformAndEmitSwitchStatement(node as SwitchStatement); case SyntaxKind.LabeledStatement: - return transformAndEmitLabeledStatement(node); + return transformAndEmitLabeledStatement(node as LabeledStatement); case SyntaxKind.ThrowStatement: - return transformAndEmitThrowStatement(node); + return transformAndEmitThrowStatement(node as ThrowStatement); case SyntaxKind.TryStatement: - return transformAndEmitTryStatement(node); + return transformAndEmitTryStatement(node as TryStatement); default: return emitStatement(visitNode(node, visitor, isStatement)); } @@ -1258,7 +1258,7 @@ namespace ts { function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList | undefined { for (const variable of node.declarations) { - const name = factory.cloneNode(variable.name); + const name = factory.cloneNode(variable.name as Identifier); setCommentRange(name, variable.name); hoistVariableDeclaration(name); } @@ -1290,7 +1290,7 @@ namespace ts { function transformInitializedVariable(node: InitializedVariableDeclaration) { return setSourceMapRange( factory.createAssignment( - setSourceMapRange(factory.cloneNode(node.name), node.name), + setSourceMapRange(factory.cloneNode(node.name) as Identifier, node.name), visitNode(node.initializer, visitor, isExpression) ), node @@ -1492,7 +1492,7 @@ namespace ts { const initializer = node.initializer; if (initializer && isVariableDeclarationList(initializer)) { for (const variable of initializer.declarations) { - hoistVariableDeclaration(variable.name); + hoistVariableDeclaration(variable.name as Identifier); } const variables = getInitializedVariables(initializer); @@ -1573,10 +1573,10 @@ namespace ts { let variable: Expression; if (isVariableDeclarationList(initializer)) { for (const variable of initializer.declarations) { - hoistVariableDeclaration(variable.name); + hoistVariableDeclaration(variable.name as Identifier); } - variable = factory.cloneNode(initializer.declarations[0].name); + variable = factory.cloneNode(initializer.declarations[0].name) as Identifier; } else { variable = visitNode(initializer, visitor, isExpression); @@ -1618,11 +1618,11 @@ namespace ts { const initializer = node.initializer; if (isVariableDeclarationList(initializer)) { for (const variable of initializer.declarations) { - hoistVariableDeclaration(variable.name); + hoistVariableDeclaration(variable.name as Identifier); } node = factory.updateForInStatement(node, - initializer.declarations[0].name, + initializer.declarations[0].name as Identifier, visitNode(node.expression, visitor, isExpression), visitNode(node.statement, visitor, isStatement, factory.liftToBlock) ); @@ -1951,7 +1951,7 @@ namespace ts { function onSubstituteNode(hint: EmitHint, node: Node): Node { node = previousOnSubstituteNode(hint, node); if (hint === EmitHint.Expression) { - return substituteExpression(node); + return substituteExpression(node as Expression); } return node; } @@ -1986,7 +1986,7 @@ namespace ts { function cacheExpression(node: Expression): Identifier { if (isGeneratedIdentifier(node) || getEmitFlags(node) & EmitFlags.HelperName) { - return node; + return node as Identifier; } const temp = factory.createTempVariable(hoistVariableDeclaration); @@ -2097,7 +2097,7 @@ namespace ts { */ function endWithBlock(): void { Debug.assert(peekBlockKind() === CodeBlockKind.With); - const block = endBlock(); + const block = endBlock() as WithBlock; markLabel(block.endLabel); } @@ -2133,7 +2133,7 @@ namespace ts { hoistVariableDeclaration(variable.name); } else { - const text = idText(variable.name); + const text = idText(variable.name as Identifier); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = new Map(); @@ -2145,7 +2145,7 @@ namespace ts { renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name; } - const exception = peekBlock(); + const exception = peekBlock() as ExceptionBlock; Debug.assert(exception.state < ExceptionBlockState.Catch); const endLabel = exception.endLabel; @@ -2167,7 +2167,7 @@ namespace ts { function beginFinallyBlock(): void { Debug.assert(peekBlockKind() === CodeBlockKind.Exception); - const exception = peekBlock(); + const exception = peekBlock() as ExceptionBlock; Debug.assert(exception.state < ExceptionBlockState.Finally); const endLabel = exception.endLabel; @@ -2184,7 +2184,7 @@ namespace ts { */ function endExceptionBlock(): void { Debug.assert(peekBlockKind() === CodeBlockKind.Exception); - const exception = endBlock(); + const exception = endBlock() as ExceptionBlock; const state = exception.state; if (state < ExceptionBlockState.Finally) { emitBreak(exception.endLabel); @@ -2238,7 +2238,7 @@ namespace ts { */ function endLoopBlock(): void { Debug.assert(peekBlockKind() === CodeBlockKind.Loop); - const block = endBlock(); + const block = endBlock() as SwitchBlock; const breakLabel = block.breakLabel; if (!block.isScript) { markLabel(breakLabel); @@ -2278,7 +2278,7 @@ namespace ts { */ function endSwitchBlock(): void { Debug.assert(peekBlockKind() === CodeBlockKind.Switch); - const block = endBlock(); + const block = endBlock() as SwitchBlock; const breakLabel = block.breakLabel; if (!block.isScript) { markLabel(breakLabel); @@ -2306,7 +2306,7 @@ namespace ts { function endLabeledBlock() { Debug.assert(peekBlockKind() === CodeBlockKind.Labeled); - const block = endBlock(); + const block = endBlock() as LabeledBlock; if (!block.isScript) { markLabel(block.breakLabel); } @@ -2945,27 +2945,27 @@ namespace ts { const args = operationArguments![operationIndex]!; if (opcode === OpCode.Statement) { - return writeStatement(args[0]); + return writeStatement(args[0] as Statement); } const location = operationLocations![operationIndex]; switch (opcode) { case OpCode.Assign: - return writeAssign(args[0], args[1], location); + return writeAssign(args[0] as Expression, args[1] as Expression, location); case OpCode.Break: - return writeBreak(
; - ~~~~ + ~ !!! error TS17002: Expected corresponding JSX closing tag for 'a'. ==== tests/cases/conformance/jsx/7.tsx (1 errors) ====
; + ~~ +!!! error TS1003: Identifier expected. + function noCloseAttrs() { } + var donkey =
+ bananas="please" + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. +
; + ~~ +!!! error TS1003: Identifier expected. + function noCloseTypeArgAttrs() { } + var donkey =
+ ; + ~~ +!!! error TS1005: '>' expected. + function noCloseBracket() { } + var donkey =
+ bananas="please"/ + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. +
; + ~~ +!!! error TS1005: '>' expected. + function noCloseBracketTypeArgAttrs() { } + var donkey =
+ + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. +
; + function noSelfclose() { } + var donkey =
+ bananas="please"> + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. +
; + function noSelfcloseTypeArgAttrs() { } + + var donkey =
+ < + + ~ +!!! error TS1003: Identifier expected. + ~~~~~ +!!! error TS2749: 'diddy' refers to a value, but is being used as a type here. Did you mean 'typeof diddy'? + ~ +!!! error TS1005: '>' expected. +
; + function noNameTrailingTag() { } + var donkey =
+ + ~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + ~~~~~ +!!! error TS2749: 'diddy' refers to a value, but is being used as a type here. Did you mean 'typeof diddy'? + ~ +!!! error TS1005: '>' expected. +
; + function noCloseTrailingTag() { } + var donkey =
+ + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + + ~ +!!! error TS1003: Identifier expected. +
; + function noCloseTypeArgTrailingTag() { } + var donkey =
+ + ~ +!!! error TS1003: Identifier expected. +
; + function noCloseAttrsTrailingTag() { } + var donkey =
+ bananas="please" + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + + ~ +!!! error TS1003: Identifier expected. +
; + function noCloseTypeArgAttrsTrailingTag() { } + var donkey =
+ + ~ +!!! error TS1005: '>' expected. +
; + function noCloseBracketTrailingTag() { } + var donkey =
+ bananas="please"/ + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + + ~ +!!! error TS1005: '>' expected. +
; + function noCloseBracketTypeArgAttrsTrailingTag() { } + var donkey =
+ + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. + +
; + function noSelfcloseTrailingTag() { } + var donkey =
+ bananas="please"> + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + +
; + function noSelfcloseTypeArgAttrsTrailingTag() { } + + var donkey =
+ < + Cranky Wrinkly Funky + ~~~~~~ +!!! error TS2304: Cannot find name 'Cranky'. +
; + ~~ +!!! error TS1003: Identifier expected. + function noNameTrailingText() { } + var donkey =
+ ; + ~~ +!!! error TS1003: Identifier expected. + function noCloseTrailingText() { } + var donkey =
+ + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + Cranky Wrinkly Funky +
; + ~~ +!!! error TS1003: Identifier expected. + function noCloseTypeArgTrailingText() { } + var donkey =
+ ; + ~~ +!!! error TS1003: Identifier expected. + function noCloseAttrsTrailingText() { } + var donkey =
+ bananas="please" + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + Cranky Wrinkly Funky +
; + ~~ +!!! error TS1003: Identifier expected. + function noCloseTypeArgAttrsTrailingText() { } + var donkey =
+ ' expected. +
; + function noCloseBracketTrailingText() { } + var donkey =
+ bananas="please"/ + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + Cranky Wrinkly Funky + ~~~~~~ +!!! error TS1005: '>' expected. +
; + function noCloseBracketTypeArgAttrsTrailingText() { } + var donkey =
+ + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. + Cranky Wrinkly Funky +
; + function noSelfcloseTrailingText() { } + var donkey =
+ bananas="please"> + ~~~~~ +!!! error TS17008: JSX element 'diddy' has no corresponding closing tag. + ~~~~~~~ +!!! error TS2558: Expected 0 type arguments, but got 1. + Cranky Wrinkly Funky +
; + function noSelfcloseTypeArgAttrsTrailingText() { } + \ No newline at end of file diff --git a/tests/baselines/reference/jsxUnclosedParserRecovery.js b/tests/baselines/reference/jsxUnclosedParserRecovery.js new file mode 100644 index 0000000000000..17cadbad9c28e --- /dev/null +++ b/tests/baselines/reference/jsxUnclosedParserRecovery.js @@ -0,0 +1,277 @@ +//// [jsxParserRecovery.tsx] +// should have no errors here; all these functions should parse and resolve +noName(); noClose(); noCloseTypeArg(); noCloseAttrs(); noCloseTypeArgAttrs(); noCloseBracket(); noCloseBracketTypeArgAttrs(); noSelfclose(); noSelfcloseTypeArgAttrs(); +noNameTrailingTag(); noCloseTrailingTag(); noCloseTypeArgTrailingTag(); noCloseAttrsTrailingTag(); noCloseTypeArgAttrsTrailingTag(); noCloseBracketTrailingTag(); noCloseBracketTypeArgAttrsTrailingTag(); // noSelfcloseTrailingTag(); noSelfcloseTypeArgAttrsTrailingTag(); +noNameTrailingText(); noCloseTrailingText(); noCloseTypeArgTrailingText(); noCloseAttrsTrailingText(); noCloseTypeArgAttrsTrailingText(); noCloseBracketTrailingText(); noCloseBracketTypeArgAttrsTrailingText(); // noSelfcloseTrailingText(); noSelfcloseTypeArgAttrsTrailingText(); + +function diddy() { + return null; +} + +var donkey =
+ < +
; +function noName() { } +var donkey =
+ ; +function noClose() { } +var donkey =
+ +
; +function noCloseTypeArg() { } +var donkey =
+ ; +function noCloseAttrs() { } +var donkey =
+ bananas="please" +
; +function noCloseTypeArgAttrs() { } +var donkey =
+ ; +function noCloseBracket() { } +var donkey =
+ bananas="please"/ +
; +function noCloseBracketTypeArgAttrs() { } +var donkey =
+ +
; +function noSelfclose() { } +var donkey =
+ bananas="please"> +
; +function noSelfcloseTypeArgAttrs() { } + +var donkey =
+ < + +
; +function noNameTrailingTag() { } +var donkey =
+ +
; +function noCloseTrailingTag() { } +var donkey =
+ + +
; +function noCloseTypeArgTrailingTag() { } +var donkey =
+ +
; +function noCloseAttrsTrailingTag() { } +var donkey =
+ bananas="please" + +
; +function noCloseTypeArgAttrsTrailingTag() { } +var donkey =
+ +
; +function noCloseBracketTrailingTag() { } +var donkey =
+ bananas="please"/ + +
; +function noCloseBracketTypeArgAttrsTrailingTag() { } +var donkey =
+ + +
; +function noSelfcloseTrailingTag() { } +var donkey =
+ bananas="please"> + +
; +function noSelfcloseTypeArgAttrsTrailingTag() { } + +var donkey =
+ < + Cranky Wrinkly Funky +
; +function noNameTrailingText() { } +var donkey =
+ ; +function noCloseTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noCloseTypeArgTrailingText() { } +var donkey =
+ ; +function noCloseAttrsTrailingText() { } +var donkey =
+ bananas="please" + Cranky Wrinkly Funky +
; +function noCloseTypeArgAttrsTrailingText() { } +var donkey =
+ ; +function noCloseBracketTrailingText() { } +var donkey =
+ bananas="please"/ + Cranky Wrinkly Funky +
; +function noCloseBracketTypeArgAttrsTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noSelfcloseTrailingText() { } +var donkey =
+ bananas="please"> + Cranky Wrinkly Funky +
; +function noSelfcloseTypeArgAttrsTrailingText() { } + + +//// [jsxParserRecovery.jsx] +// should have no errors here; all these functions should parse and resolve +noName(); +noClose(); +noCloseTypeArg(); +noCloseAttrs(); +noCloseTypeArgAttrs(); +noCloseBracket(); +noCloseBracketTypeArgAttrs(); +noSelfclose(); +noSelfcloseTypeArgAttrs(); +noNameTrailingTag(); +noCloseTrailingTag(); +noCloseTypeArgTrailingTag(); +noCloseAttrsTrailingTag(); +noCloseTypeArgAttrsTrailingTag(); +noCloseBracketTrailingTag(); +noCloseBracketTypeArgAttrsTrailingTag(); // noSelfcloseTrailingTag(); noSelfcloseTypeArgAttrsTrailingTag(); +noNameTrailingText(); +noCloseTrailingText(); +noCloseTypeArgTrailingText(); +noCloseAttrsTrailingText(); +noCloseTypeArgAttrsTrailingText(); +noCloseBracketTrailingText(); +noCloseBracketTypeArgAttrsTrailingText(); // noSelfcloseTrailingText(); noSelfcloseTypeArgAttrsTrailingText(); +function diddy() { + return null; +} +var donkey =
+ < /> +
; +function noName() { } +var donkey =
+ +
; +function noClose() { } +var donkey =
+ +
; +function noCloseTypeArg() { } +var donkey =
+ +
; +function noCloseAttrs() { } +var donkey =
+ +
; +function noCloseTypeArgAttrs() { } +var donkey =
+ +
; +function noCloseBracket() { } +var donkey =
+ +
; +function noCloseBracketTypeArgAttrs() { } +var donkey =
+
; +function noSelfclose() { } +var donkey =
+
; +function noSelfcloseTypeArgAttrs() { } +var donkey =
+ < /> +
; +function noNameTrailingTag() { } +var donkey =
+ +
; +function noCloseTrailingTag() { } +var donkey =
+ + +
; +function noCloseTypeArgTrailingTag() { } +var donkey =
+ + +
; +function noCloseAttrsTrailingTag() { } +var donkey =
+ + +
; +function noCloseTypeArgAttrsTrailingTag() { } +var donkey =
+ + +
; +function noCloseBracketTrailingTag() { } +var donkey =
+ + +
; +function noCloseBracketTypeArgAttrsTrailingTag() { } +var donkey =
+
; +function noSelfcloseTrailingTag() { } +var donkey =
+
; +function noSelfcloseTypeArgAttrsTrailingTag() { } +var donkey =
+ +
; +function noNameTrailingText() { } +var donkey =
+ +
; +function noCloseTrailingText() { } +var donkey =
+ +
; +function noCloseTypeArgTrailingText() { } +var donkey =
+ +
; +function noCloseAttrsTrailingText() { } +var donkey =
+ +
; +function noCloseTypeArgAttrsTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noCloseBracketTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noCloseBracketTypeArgAttrsTrailingText() { } +var donkey =
+
; +function noSelfcloseTrailingText() { } +var donkey =
+
; +function noSelfcloseTypeArgAttrsTrailingText() { } diff --git a/tests/baselines/reference/jsxUnclosedParserRecovery.symbols b/tests/baselines/reference/jsxUnclosedParserRecovery.symbols new file mode 100644 index 0000000000000..5aa92ab78b593 --- /dev/null +++ b/tests/baselines/reference/jsxUnclosedParserRecovery.symbols @@ -0,0 +1,314 @@ +=== tests/cases/conformance/jsx/jsxParserRecovery.tsx === +// should have no errors here; all these functions should parse and resolve +noName(); noClose(); noCloseTypeArg(); noCloseAttrs(); noCloseTypeArgAttrs(); noCloseBracket(); noCloseBracketTypeArgAttrs(); noSelfclose(); noSelfcloseTypeArgAttrs(); +>noName : Symbol(noName, Decl(jsxParserRecovery.tsx, 11, 7)) +>noClose : Symbol(noClose, Decl(jsxParserRecovery.tsx, 15, 7)) +>noCloseTypeArg : Symbol(noCloseTypeArg, Decl(jsxParserRecovery.tsx, 19, 7)) +>noCloseAttrs : Symbol(noCloseAttrs, Decl(jsxParserRecovery.tsx, 23, 7)) +>noCloseTypeArgAttrs : Symbol(noCloseTypeArgAttrs, Decl(jsxParserRecovery.tsx, 27, 7)) +>noCloseBracket : Symbol(noCloseBracket, Decl(jsxParserRecovery.tsx, 31, 7)) +>noCloseBracketTypeArgAttrs : Symbol(noCloseBracketTypeArgAttrs, Decl(jsxParserRecovery.tsx, 35, 7)) +>noSelfclose : Symbol(noSelfclose, Decl(jsxParserRecovery.tsx, 39, 7)) +>noSelfcloseTypeArgAttrs : Symbol(noSelfcloseTypeArgAttrs, Decl(jsxParserRecovery.tsx, 43, 7)) + +noNameTrailingTag(); noCloseTrailingTag(); noCloseTypeArgTrailingTag(); noCloseAttrsTrailingTag(); noCloseTypeArgAttrsTrailingTag(); noCloseBracketTrailingTag(); noCloseBracketTypeArgAttrsTrailingTag(); // noSelfcloseTrailingTag(); noSelfcloseTypeArgAttrsTrailingTag(); +>noNameTrailingTag : Symbol(noNameTrailingTag, Decl(jsxParserRecovery.tsx, 49, 7)) +>noCloseTrailingTag : Symbol(noCloseTrailingTag, Decl(jsxParserRecovery.tsx, 54, 7)) +>noCloseTypeArgTrailingTag : Symbol(noCloseTypeArgTrailingTag, Decl(jsxParserRecovery.tsx, 59, 7)) +>noCloseAttrsTrailingTag : Symbol(noCloseAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 64, 7)) +>noCloseTypeArgAttrsTrailingTag : Symbol(noCloseTypeArgAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 69, 7)) +>noCloseBracketTrailingTag : Symbol(noCloseBracketTrailingTag, Decl(jsxParserRecovery.tsx, 74, 7)) +>noCloseBracketTypeArgAttrsTrailingTag : Symbol(noCloseBracketTypeArgAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 79, 7)) + +noNameTrailingText(); noCloseTrailingText(); noCloseTypeArgTrailingText(); noCloseAttrsTrailingText(); noCloseTypeArgAttrsTrailingText(); noCloseBracketTrailingText(); noCloseBracketTypeArgAttrsTrailingText(); // noSelfcloseTrailingText(); noSelfcloseTypeArgAttrsTrailingText(); +>noNameTrailingText : Symbol(noNameTrailingText, Decl(jsxParserRecovery.tsx, 95, 7)) +>noCloseTrailingText : Symbol(noCloseTrailingText, Decl(jsxParserRecovery.tsx, 100, 7)) +>noCloseTypeArgTrailingText : Symbol(noCloseTypeArgTrailingText, Decl(jsxParserRecovery.tsx, 105, 7)) +>noCloseAttrsTrailingText : Symbol(noCloseAttrsTrailingText, Decl(jsxParserRecovery.tsx, 110, 7)) +>noCloseTypeArgAttrsTrailingText : Symbol(noCloseTypeArgAttrsTrailingText, Decl(jsxParserRecovery.tsx, 115, 7)) +>noCloseBracketTrailingText : Symbol(noCloseBracketTrailingText, Decl(jsxParserRecovery.tsx, 120, 7)) +>noCloseBracketTypeArgAttrsTrailingText : Symbol(noCloseBracketTypeArgAttrsTrailingText, Decl(jsxParserRecovery.tsx, 125, 7)) + +function diddy() { +>diddy : Symbol(diddy, Decl(jsxParserRecovery.tsx, 3, 209)) + + return null; +} + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + < +
; +function noName() { } +>noName : Symbol(noName, Decl(jsxParserRecovery.tsx, 11, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + ; +function noClose() { } +>noClose : Symbol(noClose, Decl(jsxParserRecovery.tsx, 15, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + +
; +function noCloseTypeArg() { } +>noCloseTypeArg : Symbol(noCloseTypeArg, Decl(jsxParserRecovery.tsx, 19, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 22, 10)) + +
; +function noCloseAttrs() { } +>noCloseAttrs : Symbol(noCloseAttrs, Decl(jsxParserRecovery.tsx, 23, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please" +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 26, 19)) + +
; +function noCloseTypeArgAttrs() { } +>noCloseTypeArgAttrs : Symbol(noCloseTypeArgAttrs, Decl(jsxParserRecovery.tsx, 27, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + ; +function noCloseBracket() { } +>noCloseBracket : Symbol(noCloseBracket, Decl(jsxParserRecovery.tsx, 31, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"/ +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 34, 19)) + +
; +function noCloseBracketTypeArgAttrs() { } +>noCloseBracketTypeArgAttrs : Symbol(noCloseBracketTypeArgAttrs, Decl(jsxParserRecovery.tsx, 35, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + +
; +function noSelfclose() { } +>noSelfclose : Symbol(noSelfclose, Decl(jsxParserRecovery.tsx, 39, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"> +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 42, 19)) + +
; +function noSelfcloseTypeArgAttrs() { } +>noSelfcloseTypeArgAttrs : Symbol(noSelfcloseTypeArgAttrs, Decl(jsxParserRecovery.tsx, 43, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + < + +
; +function noNameTrailingTag() { } +>noNameTrailingTag : Symbol(noNameTrailingTag, Decl(jsxParserRecovery.tsx, 49, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + +
; +function noCloseTrailingTag() { } +>noCloseTrailingTag : Symbol(noCloseTrailingTag, Decl(jsxParserRecovery.tsx, 54, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + + +
; +function noCloseTypeArgTrailingTag() { } +>noCloseTypeArgTrailingTag : Symbol(noCloseTypeArgTrailingTag, Decl(jsxParserRecovery.tsx, 59, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 62, 10)) + + +
; +function noCloseAttrsTrailingTag() { } +>noCloseAttrsTrailingTag : Symbol(noCloseAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 64, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please" +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 67, 19)) + + +
; +function noCloseTypeArgAttrsTrailingTag() { } +>noCloseTypeArgAttrsTrailingTag : Symbol(noCloseTypeArgAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 69, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + +
; +function noCloseBracketTrailingTag() { } +>noCloseBracketTrailingTag : Symbol(noCloseBracketTrailingTag, Decl(jsxParserRecovery.tsx, 74, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"/ +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 77, 19)) + + +
; +function noCloseBracketTypeArgAttrsTrailingTag() { } +>noCloseBracketTypeArgAttrsTrailingTag : Symbol(noCloseBracketTypeArgAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 79, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + + +
; +function noSelfcloseTrailingTag() { } +>noSelfcloseTrailingTag : Symbol(noSelfcloseTrailingTag, Decl(jsxParserRecovery.tsx, 84, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"> +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 87, 19)) + + +
; +function noSelfcloseTypeArgAttrsTrailingTag() { } +>noSelfcloseTypeArgAttrsTrailingTag : Symbol(noSelfcloseTypeArgAttrsTrailingTag, Decl(jsxParserRecovery.tsx, 89, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + < + Cranky Wrinkly Funky +>Wrinkly : Symbol(Wrinkly, Decl(jsxParserRecovery.tsx, 94, 10)) +>Funky : Symbol(Funky, Decl(jsxParserRecovery.tsx, 94, 18)) + +
; +function noNameTrailingText() { } +>noNameTrailingText : Symbol(noNameTrailingText, Decl(jsxParserRecovery.tsx, 95, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + Cranky : Symbol(Cranky, Decl(jsxParserRecovery.tsx, 98, 10)) +>Wrinkly : Symbol(Wrinkly, Decl(jsxParserRecovery.tsx, 99, 10)) +>Funky : Symbol(Funky, Decl(jsxParserRecovery.tsx, 99, 18)) + +
; +function noCloseTrailingText() { } +>noCloseTrailingText : Symbol(noCloseTrailingText, Decl(jsxParserRecovery.tsx, 100, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + + Cranky Wrinkly Funky +>Cranky : Symbol(Cranky, Decl(jsxParserRecovery.tsx, 103, 19)) +>Wrinkly : Symbol(Wrinkly, Decl(jsxParserRecovery.tsx, 104, 10)) +>Funky : Symbol(Funky, Decl(jsxParserRecovery.tsx, 104, 18)) + +
; +function noCloseTypeArgTrailingText() { } +>noCloseTypeArgTrailingText : Symbol(noCloseTypeArgTrailingText, Decl(jsxParserRecovery.tsx, 105, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 108, 10)) + + Cranky Wrinkly Funky +>Cranky : Symbol(Cranky, Decl(jsxParserRecovery.tsx, 108, 27)) +>Wrinkly : Symbol(Wrinkly, Decl(jsxParserRecovery.tsx, 109, 10)) +>Funky : Symbol(Funky, Decl(jsxParserRecovery.tsx, 109, 18)) + +
; +function noCloseAttrsTrailingText() { } +>noCloseAttrsTrailingText : Symbol(noCloseAttrsTrailingText, Decl(jsxParserRecovery.tsx, 110, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please" +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 113, 19)) + + Cranky Wrinkly Funky +>Cranky : Symbol(Cranky, Decl(jsxParserRecovery.tsx, 113, 36)) +>Wrinkly : Symbol(Wrinkly, Decl(jsxParserRecovery.tsx, 114, 10)) +>Funky : Symbol(Funky, Decl(jsxParserRecovery.tsx, 114, 18)) + +
; +function noCloseTypeArgAttrsTrailingText() { } +>noCloseTypeArgAttrsTrailingText : Symbol(noCloseTypeArgAttrsTrailingText, Decl(jsxParserRecovery.tsx, 115, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + ; +function noCloseBracketTrailingText() { } +>noCloseBracketTrailingText : Symbol(noCloseBracketTrailingText, Decl(jsxParserRecovery.tsx, 120, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"/ +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 123, 19)) + + Cranky Wrinkly Funky +
; +function noCloseBracketTypeArgAttrsTrailingText() { } +>noCloseBracketTypeArgAttrsTrailingText : Symbol(noCloseBracketTypeArgAttrsTrailingText, Decl(jsxParserRecovery.tsx, 125, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + + Cranky Wrinkly Funky +
; +function noSelfcloseTrailingText() { } +>noSelfcloseTrailingText : Symbol(noSelfcloseTrailingText, Decl(jsxParserRecovery.tsx, 130, 7)) + +var donkey =
+>donkey : Symbol(donkey, Decl(jsxParserRecovery.tsx, 9, 3), Decl(jsxParserRecovery.tsx, 13, 3), Decl(jsxParserRecovery.tsx, 17, 3), Decl(jsxParserRecovery.tsx, 21, 3), Decl(jsxParserRecovery.tsx, 25, 3) ... and 22 more) + + bananas="please"> +>bananas : Symbol(bananas, Decl(jsxParserRecovery.tsx, 133, 19)) + + Cranky Wrinkly Funky +
; +function noSelfcloseTypeArgAttrsTrailingText() { } +>noSelfcloseTypeArgAttrsTrailingText : Symbol(noSelfcloseTypeArgAttrsTrailingText, Decl(jsxParserRecovery.tsx, 135, 7)) + diff --git a/tests/baselines/reference/jsxUnclosedParserRecovery.types b/tests/baselines/reference/jsxUnclosedParserRecovery.types new file mode 100644 index 0000000000000..0c836329c7c40 --- /dev/null +++ b/tests/baselines/reference/jsxUnclosedParserRecovery.types @@ -0,0 +1,541 @@ +=== tests/cases/conformance/jsx/jsxParserRecovery.tsx === +// should have no errors here; all these functions should parse and resolve +noName(); noClose(); noCloseTypeArg(); noCloseAttrs(); noCloseTypeArgAttrs(); noCloseBracket(); noCloseBracketTypeArgAttrs(); noSelfclose(); noSelfcloseTypeArgAttrs(); +>noName() : void +>noName : () => void +>noClose() : void +>noClose : () => void +>noCloseTypeArg() : void +>noCloseTypeArg : () => void +>noCloseAttrs() : void +>noCloseAttrs : () => void +>noCloseTypeArgAttrs() : void +>noCloseTypeArgAttrs : () => void +>noCloseBracket() : void +>noCloseBracket : () => void +>noCloseBracketTypeArgAttrs() : void +>noCloseBracketTypeArgAttrs : () => void +>noSelfclose() : void +>noSelfclose : () => void +>noSelfcloseTypeArgAttrs() : void +>noSelfcloseTypeArgAttrs : () => void + +noNameTrailingTag(); noCloseTrailingTag(); noCloseTypeArgTrailingTag(); noCloseAttrsTrailingTag(); noCloseTypeArgAttrsTrailingTag(); noCloseBracketTrailingTag(); noCloseBracketTypeArgAttrsTrailingTag(); // noSelfcloseTrailingTag(); noSelfcloseTypeArgAttrsTrailingTag(); +>noNameTrailingTag() : void +>noNameTrailingTag : () => void +>noCloseTrailingTag() : void +>noCloseTrailingTag : () => void +>noCloseTypeArgTrailingTag() : void +>noCloseTypeArgTrailingTag : () => void +>noCloseAttrsTrailingTag() : void +>noCloseAttrsTrailingTag : () => void +>noCloseTypeArgAttrsTrailingTag() : void +>noCloseTypeArgAttrsTrailingTag : () => void +>noCloseBracketTrailingTag() : void +>noCloseBracketTrailingTag : () => void +>noCloseBracketTypeArgAttrsTrailingTag() : void +>noCloseBracketTypeArgAttrsTrailingTag : () => void + +noNameTrailingText(); noCloseTrailingText(); noCloseTypeArgTrailingText(); noCloseAttrsTrailingText(); noCloseTypeArgAttrsTrailingText(); noCloseBracketTrailingText(); noCloseBracketTypeArgAttrsTrailingText(); // noSelfcloseTrailingText(); noSelfcloseTypeArgAttrsTrailingText(); +>noNameTrailingText() : void +>noNameTrailingText : () => void +>noCloseTrailingText() : void +>noCloseTrailingText : () => void +>noCloseTypeArgTrailingText() : void +>noCloseTypeArgTrailingText : () => void +>noCloseAttrsTrailingText() : void +>noCloseAttrsTrailingText : () => void +>noCloseTypeArgAttrsTrailingText() : void +>noCloseTypeArgAttrsTrailingText : () => void +>noCloseBracketTrailingText() : void +>noCloseBracketTrailingText : () => void +>noCloseBracketTypeArgAttrsTrailingText() : void +>noCloseBracketTypeArgAttrsTrailingText : () => void + +function diddy() { +>diddy : () => any + + return null; +>null : null +} + +var donkey =
+>donkey : any +>
<
: any +>div : any + + < +>< : any + +
; +> : any +>div : any + +function noName() { } +>noName : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any + +
; +>div : any + +function noClose() { } +>noClose : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseTypeArg() { } +>noCloseTypeArg : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any +>bananas : string + +
; +>div : any + +function noCloseAttrs() { } +>noCloseAttrs : () => void + +var donkey =
+>donkey : any +>
bananas="please"
: any +>div : any + + bananas="please" +> bananas="please" : any +>diddy : () => any +>bananas : string + +
; +>div : any + +function noCloseTypeArgAttrs() { } +>noCloseTypeArgAttrs : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any + +
; +>div : any + +function noCloseBracket() { } +>noCloseBracket : () => void + +var donkey =
+>donkey : any +>
bananas="please"/
: any +>div : any + + bananas="please"/ +> bananas="please"/ : any +>diddy : () => any +>bananas : string + +
; +>div : any + +function noCloseBracketTypeArgAttrs() { } +>noCloseBracketTypeArgAttrs : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + +> : any +>diddy : () => any + +
; +> : any +>div : any + +function noSelfclose() { } +>noSelfclose : () => void + +var donkey =
+>donkey : any +>
bananas="please">
: any +>div : any + + bananas="please"> +> bananas="please"> : any +>diddy : () => any +>bananas : string + +
; +> : any +>div : any + +function noSelfcloseTypeArgAttrs() { } +>noSelfcloseTypeArgAttrs : () => void + +var donkey =
+>donkey : any +>
<
: any +>div : any + + < +>< : any + + +> : any + +
; +>div : any + +function noNameTrailingTag() { } +>noNameTrailingTag : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + : any +>diddy : () => any + + +
; +>div : any + +function noCloseTrailingTag() { } +>noCloseTrailingTag : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + +> : any +>diddy : () => any + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseTypeArgTrailingTag() { } +>noCloseTypeArgTrailingTag : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any +>bananas : string + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseAttrsTrailingTag() { } +>noCloseAttrsTrailingTag : () => void + +var donkey =
+>donkey : any +>
bananas="please"
: any +>div : any + + bananas="please" +> bananas="please" : any +>diddy : () => any +>bananas : string + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseTypeArgAttrsTrailingTag() { } +>noCloseTypeArgAttrsTrailingTag : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseBracketTrailingTag() { } +>noCloseBracketTrailingTag : () => void + +var donkey =
+>donkey : any +>
bananas="please"/
: any +>div : any + + bananas="please"/ +> bananas="please"/ : any +>diddy : () => any +>bananas : string + + +> : any +>diddy : () => any + +
; +>div : any + +function noCloseBracketTypeArgAttrsTrailingTag() { } +>noCloseBracketTypeArgAttrsTrailingTag : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + +> : any +>diddy : () => any + + +> : any + +
; +>div : any + +function noSelfcloseTrailingTag() { } +>noSelfcloseTrailingTag : () => void + +var donkey =
+>donkey : any +>
bananas="please">
: any +>div : any + + bananas="please"> +> bananas="please"> : any +>diddy : () => any +>bananas : string + + +> : any + +
; +>div : any + +function noSelfcloseTypeArgAttrsTrailingTag() { } +>noSelfcloseTypeArgAttrsTrailingTag : () => void + +var donkey =
+>donkey : any +>
< Cranky Wrinkly Funky
: any +>div : any + + < +>< Cranky Wrinkly Funky : any + + Cranky Wrinkly Funky +>Cranky : any +>Wrinkly : true +>Funky : true + +
; +>div : any + +function noNameTrailingText() { } +>noNameTrailingText : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any + + Cranky Wrinkly Funky +>Cranky : true +>Wrinkly : true +>Funky : true + +
; +>div : any + +function noCloseTrailingText() { } +>noCloseTrailingText : () => void + +var donkey =
+>donkey : any +>
Cranky Wrinkly Funky
: any +>div : any + + +> Cranky Wrinkly Funky : any +>diddy : () => any + + Cranky Wrinkly Funky +>Cranky : true +>Wrinkly : true +>Funky : true + +
; +>div : any + +function noCloseTypeArgTrailingText() { } +>noCloseTypeArgTrailingText : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any +>bananas : string + + Cranky Wrinkly Funky +>Cranky : true +>Wrinkly : true +>Funky : true + +
; +>div : any + +function noCloseAttrsTrailingText() { } +>noCloseAttrsTrailingText : () => void + +var donkey =
+>donkey : any +>
bananas="please" Cranky Wrinkly Funky
: any +>div : any + + bananas="please" +> bananas="please" Cranky Wrinkly Funky : any +>diddy : () => any +>bananas : string + + Cranky Wrinkly Funky +>Cranky : true +>Wrinkly : true +>Funky : true + +
; +>div : any + +function noCloseTypeArgAttrsTrailingText() { } +>noCloseTypeArgAttrsTrailingText : () => void + +var donkey =
+>donkey : any +>
: any +>div : any + + diddy : () => any + + Cranky Wrinkly Funky +
; +>div : any + +function noCloseBracketTrailingText() { } +>noCloseBracketTrailingText : () => void + +var donkey =
+>donkey : any +>
bananas="please"/ Cranky Wrinkly Funky
: any +>div : any + + bananas="please"/ +> bananas="please"/ : any +>diddy : () => any +>bananas : string + + Cranky Wrinkly Funky +
; +>div : any + +function noCloseBracketTypeArgAttrsTrailingText() { } +>noCloseBracketTypeArgAttrsTrailingText : () => void + +var donkey =
+>donkey : any +>
Cranky Wrinkly Funky
: any +>div : any + + +> : any +>diddy : () => any + + Cranky Wrinkly Funky +> : any + +
; +>div : any + +function noSelfcloseTrailingText() { } +>noSelfcloseTrailingText : () => void + +var donkey =
+>donkey : any +>
bananas="please"> Cranky Wrinkly Funky
: any +>div : any + + bananas="please"> +> bananas="please"> : any +>diddy : () => any +>bananas : string + + Cranky Wrinkly Funky +> : any + +
; +>div : any + +function noSelfcloseTypeArgAttrsTrailingText() { } +>noSelfcloseTypeArgAttrsTrailingText : () => void + diff --git a/tests/baselines/reference/mappedTypeAsClauses.errors.txt b/tests/baselines/reference/mappedTypeAsClauses.errors.txt new file mode 100644 index 0000000000000..61a7ed29067a7 --- /dev/null +++ b/tests/baselines/reference/mappedTypeAsClauses.errors.txt @@ -0,0 +1,158 @@ +tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts(130,3): error TS2345: Argument of type '"a"' is not assignable to parameter of type '"b"'. + + +==== tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts (1 errors) ==== + // Mapped type 'as N' clauses + + type Getters = { [P in keyof T & string as `get${Capitalize

}`]: () => T[P] }; + type TG1 = Getters<{ foo: string, bar: number, baz: { z: boolean } }>; + + // Mapped type with 'as N' clause has no constraint on 'in T' clause + + type PropDef = { name: K, type: T }; + + type TypeFromDefs> = { [P in T as P['name']]: P['type'] }; + + type TP1 = TypeFromDefs<{ name: 'a', type: string } | { name: 'b', type: number } | { name: 'a', type: boolean }>; + + // No array or tuple type mapping when 'as N' clause present + + type TA1 = Getters; + type TA2 = Getters<[number, boolean]>; + + // Filtering using 'as N' clause + + type Methods = { [P in keyof T as T[P] extends Function ? P : never]: T[P] }; + type TM1 = Methods<{ foo(): number, bar(x: string): boolean, baz: string | number }>; + + // Mapping to multiple names using 'as N' clause + + type DoubleProp = { [P in keyof T & string as `${P}1` | `${P}2`]: T[P] } + type TD1 = DoubleProp<{ a: string, b: number }>; // { a1: string, a2: string, b1: number, b2: number } + type TD2 = keyof TD1; // 'a1' | 'a2' | 'b1' | 'b2' + type TD3 = keyof DoubleProp; // `${keyof U & string}1` | `${keyof U & string}2` + + // Repro from #40619 + + type Lazyify = { + [K in keyof T as `get${Capitalize}`]: () => T[K] + }; + + interface Person { + readonly name: string; + age: number; + location?: string; + } + + type LazyPerson = Lazyify; + + // Repro from #40833 + + type Example = {foo: string, bar: number}; + + type PickByValueType = { + [K in keyof T as T[K] extends U ? K : never]: T[K] + }; + + type T1 = PickByValueType; + const e1: T1 = { + foo: "hello" + }; + type T2 = keyof T1; + const e2: T2 = "foo"; + + // Repro from #41133 + + interface Car { + name: string; + seats: number; + engine: Engine; + wheels: Wheel[]; + } + + interface Engine { + manufacturer: string; + horsepower: number; + } + + interface Wheel { + type: "summer" | "winter"; + radius: number; + } + + type Primitive = string | number | boolean; + type OnlyPrimitives = { [K in keyof T as T[K] extends Primitive ? K : never]: T[K] }; + + let primitiveCar: OnlyPrimitives; // { name: string; seats: number; } + let keys: keyof OnlyPrimitives; // "name" | "seats" + + type KeysOfPrimitives = keyof OnlyPrimitives; + + let carKeys: KeysOfPrimitives; // "name" | "seats" + + // Repro from #41453 + + type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; + + type If = Cond extends true ? Then : Else; + + type GetKey = keyof { [TP in keyof S as Equal extends true ? TP : never]: any }; + + type GetKeyWithIf = keyof { [TP in keyof S as If, TP, never>]: any }; + + type GetObjWithIf = { [TP in keyof S as If, TP, never>]: any }; + + type Task = { + isDone: boolean; + }; + + type Schema = { + root: { + title: string; + task: Task; + } + Task: Task; + }; + + type Res1 = GetKey; // "Task" + type Res2 = GetKeyWithIf; // "Task" + type Res3 = keyof GetObjWithIf; // "Task" + + // Repro from #44019 + + type KeysExtendedBy = keyof { [K in keyof T as U extends T[K] ? K : never] : T[K] }; + + interface M { + a: boolean; + b: number; + } + + function f(x: KeysExtendedBy) { + return x; + } + + f("a"); // Error, should allow only "b" + ~~~ +!!! error TS2345: Argument of type '"a"' is not assignable to parameter of type '"b"'. + + type NameMap = { 'a': 'x', 'b': 'y', 'c': 'z' }; + + // Distributive, will be simplified + + type TS0 = keyof { [P in keyof T as keyof Record]: string }; + type TS1 = keyof { [P in keyof T as Extract]: string }; + type TS2 = keyof { [P in keyof T as P & ('a' | 'b' | 'c')]: string }; + type TS3 = keyof { [P in keyof T as Exclude]: string }; + type TS4 = keyof { [P in keyof T as NameMap[P & keyof NameMap]]: string }; + type TS5 = keyof { [P in keyof T & keyof NameMap as NameMap[P]]: string }; + type TS6 = keyof { [ K in keyof T as V & (K extends U ? K : never)]: string }; + + // Non-distributive, won't be simplified + + type TN0 = keyof { [P in keyof T as T[P] extends number ? P : never]: string }; + type TN1 = keyof { [P in keyof T as number extends T[P] ? P : never]: string }; + type TN2 = keyof { [P in keyof T as 'a' extends P ? 'x' : 'y']: string }; + type TN3 = keyof { [P in keyof T as Exclude, 'b'>, 'a'>]: string }; + type TN4 = keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string }; + type TN5 = keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true }]: string }; + \ No newline at end of file diff --git a/tests/baselines/reference/mappedTypeAsClauses.js b/tests/baselines/reference/mappedTypeAsClauses.js index e5e15d8e6b243..3bd629f494cfc 100644 --- a/tests/baselines/reference/mappedTypeAsClauses.js +++ b/tests/baselines/reference/mappedTypeAsClauses.js @@ -114,6 +114,42 @@ type Schema = { type Res1 = GetKey; // "Task" type Res2 = GetKeyWithIf; // "Task" type Res3 = keyof GetObjWithIf; // "Task" + +// Repro from #44019 + +type KeysExtendedBy = keyof { [K in keyof T as U extends T[K] ? K : never] : T[K] }; + +interface M { + a: boolean; + b: number; +} + +function f(x: KeysExtendedBy) { + return x; +} + +f("a"); // Error, should allow only "b" + +type NameMap = { 'a': 'x', 'b': 'y', 'c': 'z' }; + +// Distributive, will be simplified + +type TS0 = keyof { [P in keyof T as keyof Record]: string }; +type TS1 = keyof { [P in keyof T as Extract]: string }; +type TS2 = keyof { [P in keyof T as P & ('a' | 'b' | 'c')]: string }; +type TS3 = keyof { [P in keyof T as Exclude]: string }; +type TS4 = keyof { [P in keyof T as NameMap[P & keyof NameMap]]: string }; +type TS5 = keyof { [P in keyof T & keyof NameMap as NameMap[P]]: string }; +type TS6 = keyof { [ K in keyof T as V & (K extends U ? K : never)]: string }; + +// Non-distributive, won't be simplified + +type TN0 = keyof { [P in keyof T as T[P] extends number ? P : never]: string }; +type TN1 = keyof { [P in keyof T as number extends T[P] ? P : never]: string }; +type TN2 = keyof { [P in keyof T as 'a' extends P ? 'x' : 'y']: string }; +type TN3 = keyof { [P in keyof T as Exclude, 'b'>, 'a'>]: string }; +type TN4 = keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string }; +type TN5 = keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true }]: string }; //// [mappedTypeAsClauses.js] @@ -126,6 +162,10 @@ var e2 = "foo"; var primitiveCar; // { name: string; seats: number; } var keys; // "name" | "seats" var carKeys; // "name" | "seats" +function f(x) { + return x; +} +f("a"); // Error, should allow only "b" //// [mappedTypeAsClauses.d.ts] @@ -241,3 +281,57 @@ declare type Schema = { declare type Res1 = GetKey; declare type Res2 = GetKeyWithIf; declare type Res3 = keyof GetObjWithIf; +declare type KeysExtendedBy = keyof { + [K in keyof T as U extends T[K] ? K : never]: T[K]; +}; +interface M { + a: boolean; + b: number; +} +declare function f(x: KeysExtendedBy): "b"; +declare type NameMap = { + 'a': 'x'; + 'b': 'y'; + 'c': 'z'; +}; +declare type TS0 = keyof { + [P in keyof T as keyof Record]: string; +}; +declare type TS1 = keyof { + [P in keyof T as Extract]: string; +}; +declare type TS2 = keyof { + [P in keyof T as P & ('a' | 'b' | 'c')]: string; +}; +declare type TS3 = keyof { + [P in keyof T as Exclude]: string; +}; +declare type TS4 = keyof { + [P in keyof T as NameMap[P & keyof NameMap]]: string; +}; +declare type TS5 = keyof { + [P in keyof T & keyof NameMap as NameMap[P]]: string; +}; +declare type TS6 = keyof { + [K in keyof T as V & (K extends U ? K : never)]: string; +}; +declare type TN0 = keyof { + [P in keyof T as T[P] extends number ? P : never]: string; +}; +declare type TN1 = keyof { + [P in keyof T as number extends T[P] ? P : never]: string; +}; +declare type TN2 = keyof { + [P in keyof T as 'a' extends P ? 'x' : 'y']: string; +}; +declare type TN3 = keyof { + [P in keyof T as Exclude, 'b'>, 'a'>]: string; +}; +declare type TN4 = keyof { + [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string; +}; +declare type TN5 = keyof { + [K in keyof T as keyof { + [P in K as T[P] extends U ? K : never]: true; + }]: string; +}; diff --git a/tests/baselines/reference/mappedTypeAsClauses.symbols b/tests/baselines/reference/mappedTypeAsClauses.symbols index 1de577a5fd514..834020f61eea8 100644 --- a/tests/baselines/reference/mappedTypeAsClauses.symbols +++ b/tests/baselines/reference/mappedTypeAsClauses.symbols @@ -369,3 +369,174 @@ type Res3 = keyof GetObjWithIf; // "Task" >Schema : Symbol(Schema, Decl(mappedTypeAsClauses.ts, 102, 2)) >Schema : Symbol(Schema, Decl(mappedTypeAsClauses.ts, 102, 2)) +// Repro from #44019 + +type KeysExtendedBy = keyof { [K in keyof T as U extends T[K] ? K : never] : T[K] }; +>KeysExtendedBy : Symbol(KeysExtendedBy, Decl(mappedTypeAsClauses.ts, 114, 63)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 118, 20)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 118, 22)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 118, 37)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 118, 20)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 118, 22)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 118, 20)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 118, 37)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 118, 37)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 118, 20)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 118, 37)) + +interface M { +>M : Symbol(M, Decl(mappedTypeAsClauses.ts, 118, 90)) + + a: boolean; +>a : Symbol(M.a, Decl(mappedTypeAsClauses.ts, 120, 13)) + + b: number; +>b : Symbol(M.b, Decl(mappedTypeAsClauses.ts, 121, 15)) +} + +function f(x: KeysExtendedBy) { +>f : Symbol(f, Decl(mappedTypeAsClauses.ts, 123, 1)) +>x : Symbol(x, Decl(mappedTypeAsClauses.ts, 125, 11)) +>KeysExtendedBy : Symbol(KeysExtendedBy, Decl(mappedTypeAsClauses.ts, 114, 63)) +>M : Symbol(M, Decl(mappedTypeAsClauses.ts, 118, 90)) + + return x; +>x : Symbol(x, Decl(mappedTypeAsClauses.ts, 125, 11)) +} + +f("a"); // Error, should allow only "b" +>f : Symbol(f, Decl(mappedTypeAsClauses.ts, 123, 1)) + +type NameMap = { 'a': 'x', 'b': 'y', 'c': 'z' }; +>NameMap : Symbol(NameMap, Decl(mappedTypeAsClauses.ts, 129, 7)) +>'a' : Symbol('a', Decl(mappedTypeAsClauses.ts, 131, 16)) +>'b' : Symbol('b', Decl(mappedTypeAsClauses.ts, 131, 26)) +>'c' : Symbol('c', Decl(mappedTypeAsClauses.ts, 131, 36)) + +// Distributive, will be simplified + +type TS0 = keyof { [P in keyof T as keyof Record]: string }; +>TS0 : Symbol(TS0, Decl(mappedTypeAsClauses.ts, 131, 48)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 135, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 135, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 135, 9)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 135, 23)) + +type TS1 = keyof { [P in keyof T as Extract]: string }; +>TS1 : Symbol(TS1, Decl(mappedTypeAsClauses.ts, 135, 74)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 136, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 136, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 136, 9)) +>Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 136, 23)) + +type TS2 = keyof { [P in keyof T as P & ('a' | 'b' | 'c')]: string }; +>TS2 : Symbol(TS2, Decl(mappedTypeAsClauses.ts, 136, 78)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 137, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 137, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 137, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 137, 23)) + +type TS3 = keyof { [P in keyof T as Exclude]: string }; +>TS3 : Symbol(TS3, Decl(mappedTypeAsClauses.ts, 137, 72)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 138, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 138, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 138, 9)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 138, 23)) + +type TS4 = keyof { [P in keyof T as NameMap[P & keyof NameMap]]: string }; +>TS4 : Symbol(TS4, Decl(mappedTypeAsClauses.ts, 138, 78)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 139, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 139, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 139, 9)) +>NameMap : Symbol(NameMap, Decl(mappedTypeAsClauses.ts, 129, 7)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 139, 23)) +>NameMap : Symbol(NameMap, Decl(mappedTypeAsClauses.ts, 129, 7)) + +type TS5 = keyof { [P in keyof T & keyof NameMap as NameMap[P]]: string }; +>TS5 : Symbol(TS5, Decl(mappedTypeAsClauses.ts, 139, 77)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 140, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 140, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 140, 9)) +>NameMap : Symbol(NameMap, Decl(mappedTypeAsClauses.ts, 129, 7)) +>NameMap : Symbol(NameMap, Decl(mappedTypeAsClauses.ts, 129, 7)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 140, 23)) + +type TS6 = keyof { [ K in keyof T as V & (K extends U ? K : never)]: string }; +>TS6 : Symbol(TS6, Decl(mappedTypeAsClauses.ts, 140, 77)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 141, 9)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 141, 11)) +>V : Symbol(V, Decl(mappedTypeAsClauses.ts, 141, 14)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 141, 29)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 141, 9)) +>V : Symbol(V, Decl(mappedTypeAsClauses.ts, 141, 14)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 141, 29)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 141, 11)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 141, 29)) + +// Non-distributive, won't be simplified + +type TN0 = keyof { [P in keyof T as T[P] extends number ? P : never]: string }; +>TN0 : Symbol(TN0, Decl(mappedTypeAsClauses.ts, 141, 87)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 145, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 145, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 145, 9)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 145, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 145, 23)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 145, 23)) + +type TN1 = keyof { [P in keyof T as number extends T[P] ? P : never]: string }; +>TN1 : Symbol(TN1, Decl(mappedTypeAsClauses.ts, 145, 82)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 146, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 146, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 146, 9)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 146, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 146, 23)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 146, 23)) + +type TN2 = keyof { [P in keyof T as 'a' extends P ? 'x' : 'y']: string }; +>TN2 : Symbol(TN2, Decl(mappedTypeAsClauses.ts, 146, 82)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 147, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 147, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 147, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 147, 23)) + +type TN3 = keyof { [P in keyof T as Exclude, 'b'>, 'a'>]: string }; +>TN3 : Symbol(TN3, Decl(mappedTypeAsClauses.ts, 147, 76)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 148, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 148, 23)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 148, 9)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 148, 23)) + +type TN4 = keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string }; +>TN4 : Symbol(TN4, Decl(mappedTypeAsClauses.ts, 148, 94)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 149, 9)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 149, 11)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 149, 26)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 149, 9)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 149, 26)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 149, 11)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 149, 9)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 149, 26)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 149, 9)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 149, 26)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 149, 26)) + +type TN5 = keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true }]: string }; +>TN5 : Symbol(TN5, Decl(mappedTypeAsClauses.ts, 149, 107)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 150, 9)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 150, 11)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 150, 26)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 150, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 150, 51)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 150, 26)) +>T : Symbol(T, Decl(mappedTypeAsClauses.ts, 150, 9)) +>P : Symbol(P, Decl(mappedTypeAsClauses.ts, 150, 51)) +>U : Symbol(U, Decl(mappedTypeAsClauses.ts, 150, 11)) +>K : Symbol(K, Decl(mappedTypeAsClauses.ts, 150, 26)) + diff --git a/tests/baselines/reference/mappedTypeAsClauses.types b/tests/baselines/reference/mappedTypeAsClauses.types index 260aebeb9f1a9..803fd0bef5a23 100644 --- a/tests/baselines/reference/mappedTypeAsClauses.types +++ b/tests/baselines/reference/mappedTypeAsClauses.types @@ -225,3 +225,79 @@ type Res2 = GetKeyWithIf; // "Task" type Res3 = keyof GetObjWithIf; // "Task" >Res3 : "Task" +// Repro from #44019 + +type KeysExtendedBy = keyof { [K in keyof T as U extends T[K] ? K : never] : T[K] }; +>KeysExtendedBy : keyof { [K in keyof T as U extends T[K] ? K : never]: T[K]; } + +interface M { + a: boolean; +>a : boolean + + b: number; +>b : number +} + +function f(x: KeysExtendedBy) { +>f : (x: KeysExtendedBy) => "b" +>x : "b" + + return x; +>x : "b" +} + +f("a"); // Error, should allow only "b" +>f("a") : "b" +>f : (x: "b") => "b" +>"a" : "a" + +type NameMap = { 'a': 'x', 'b': 'y', 'c': 'z' }; +>NameMap : NameMap +>'a' : "x" +>'b' : "y" +>'c' : "z" + +// Distributive, will be simplified + +type TS0 = keyof { [P in keyof T as keyof Record]: string }; +>TS0 : keyof T + +type TS1 = keyof { [P in keyof T as Extract]: string }; +>TS1 : Extract + +type TS2 = keyof { [P in keyof T as P & ('a' | 'b' | 'c')]: string }; +>TS2 : keyof T & ("a" | "b" | "c") + +type TS3 = keyof { [P in keyof T as Exclude]: string }; +>TS3 : Exclude + +type TS4 = keyof { [P in keyof T as NameMap[P & keyof NameMap]]: string }; +>TS4 : NameMap[keyof T & keyof NameMap] + +type TS5 = keyof { [P in keyof T & keyof NameMap as NameMap[P]]: string }; +>TS5 : NameMap[keyof T & "a"] | NameMap[keyof T & "b"] | NameMap[keyof T & "c"] + +type TS6 = keyof { [ K in keyof T as V & (K extends U ? K : never)]: string }; +>TS6 : V & (keyof T extends U ? U & keyof T : never) + +// Non-distributive, won't be simplified + +type TN0 = keyof { [P in keyof T as T[P] extends number ? P : never]: string }; +>TN0 : keyof { [P in keyof T as T[P] extends number ? P : never]: string; } + +type TN1 = keyof { [P in keyof T as number extends T[P] ? P : never]: string }; +>TN1 : keyof { [P in keyof T as number extends T[P] ? P : never]: string; } + +type TN2 = keyof { [P in keyof T as 'a' extends P ? 'x' : 'y']: string }; +>TN2 : keyof { [P in keyof T as "a" extends P ? "x" : "y"]: string; } + +type TN3 = keyof { [P in keyof T as Exclude, 'b'>, 'a'>]: string }; +>TN3 : keyof { [P in keyof T as Exclude, "b">, "a">]: string; } + +type TN4 = keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string }; +>TN4 : keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string; } + +type TN5 = keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true }]: string }; +>TN5 : keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true; }]: string; } +>true : true + diff --git a/tests/baselines/reference/missingCloseBracketInArray.errors.txt b/tests/baselines/reference/missingCloseBracketInArray.errors.txt deleted file mode 100644 index 26801c02812b4..0000000000000 --- a/tests/baselines/reference/missingCloseBracketInArray.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/compiler/missingCloseBracketInArray.ts(1,48): error TS1005: ']' expected. - - -==== tests/cases/compiler/missingCloseBracketInArray.ts (1 errors) ==== - var alphas:string[] = alphas = ["1","2","3","4" - -!!! error TS1005: ']' expected. -!!! related TS1007 tests/cases/compiler/missingCloseBracketInArray.ts:1:32: The parser expected to find a ']' to match the '[' token here. \ No newline at end of file diff --git a/tests/baselines/reference/missingCloseBracketInArray.js b/tests/baselines/reference/missingCloseBracketInArray.js deleted file mode 100644 index cb842d1cc7413..0000000000000 --- a/tests/baselines/reference/missingCloseBracketInArray.js +++ /dev/null @@ -1,5 +0,0 @@ -//// [missingCloseBracketInArray.ts] -var alphas:string[] = alphas = ["1","2","3","4" - -//// [missingCloseBracketInArray.js] -var alphas = alphas = ["1", "2", "3", "4"]; diff --git a/tests/baselines/reference/missingCloseBracketInArray.symbols b/tests/baselines/reference/missingCloseBracketInArray.symbols deleted file mode 100644 index 4d28f8945fd13..0000000000000 --- a/tests/baselines/reference/missingCloseBracketInArray.symbols +++ /dev/null @@ -1,5 +0,0 @@ -=== tests/cases/compiler/missingCloseBracketInArray.ts === -var alphas:string[] = alphas = ["1","2","3","4" ->alphas : Symbol(alphas, Decl(missingCloseBracketInArray.ts, 0, 3)) ->alphas : Symbol(alphas, Decl(missingCloseBracketInArray.ts, 0, 3)) - diff --git a/tests/baselines/reference/missingCloseBracketInArray.types b/tests/baselines/reference/missingCloseBracketInArray.types deleted file mode 100644 index 557a865827c2b..0000000000000 --- a/tests/baselines/reference/missingCloseBracketInArray.types +++ /dev/null @@ -1,11 +0,0 @@ -=== tests/cases/compiler/missingCloseBracketInArray.ts === -var alphas:string[] = alphas = ["1","2","3","4" ->alphas : string[] ->alphas = ["1","2","3","4" : string[] ->alphas : string[] ->["1","2","3","4" : string[] ->"1" : "1" ->"2" : "2" ->"3" : "3" ->"4" : "4" - diff --git a/tests/baselines/reference/missingCloseParenStatements.errors.txt b/tests/baselines/reference/missingCloseParenStatements.errors.txt deleted file mode 100644 index 3f49d5a036653..0000000000000 --- a/tests/baselines/reference/missingCloseParenStatements.errors.txt +++ /dev/null @@ -1,32 +0,0 @@ -tests/cases/compiler/missingCloseParenStatements.ts(2,26): error TS1005: ')' expected. -tests/cases/compiler/missingCloseParenStatements.ts(4,5): error TS1005: ')' expected. -tests/cases/compiler/missingCloseParenStatements.ts(8,39): error TS1005: ')' expected. -tests/cases/compiler/missingCloseParenStatements.ts(11,35): error TS1005: ')' expected. - - -==== tests/cases/compiler/missingCloseParenStatements.ts (4 errors) ==== - var a1, a2, a3 = 0; - if ( a1 && (a2 + a3 > 0) { - ~ -!!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/missingCloseParenStatements.ts:2:4: The parser expected to find a ')' to match the '(' token here. - while( (a2 > 0) && a1 - { - ~ -!!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/missingCloseParenStatements.ts:3:10: The parser expected to find a ')' to match the '(' token here. - do { - var i = i + 1; - a1 = a1 + i; - with ((a2 + a3 > 0) && a1 { - ~ -!!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/missingCloseParenStatements.ts:8:18: The parser expected to find a ')' to match the '(' token here. - console.log(x); - } - } while (i < 5 && (a1 > 5); - ~ -!!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/missingCloseParenStatements.ts:11:17: The parser expected to find a ')' to match the '(' token here. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/missingCloseParenStatements.js b/tests/baselines/reference/missingCloseParenStatements.js deleted file mode 100644 index 8ba56b6b88183..0000000000000 --- a/tests/baselines/reference/missingCloseParenStatements.js +++ /dev/null @@ -1,28 +0,0 @@ -//// [missingCloseParenStatements.ts] -var a1, a2, a3 = 0; -if ( a1 && (a2 + a3 > 0) { - while( (a2 > 0) && a1 - { - do { - var i = i + 1; - a1 = a1 + i; - with ((a2 + a3 > 0) && a1 { - console.log(x); - } - } while (i < 5 && (a1 > 5); - } -} - -//// [missingCloseParenStatements.js] -var a1, a2, a3 = 0; -if (a1 && (a2 + a3 > 0)) { - while ((a2 > 0) && a1) { - do { - var i = i + 1; - a1 = a1 + i; - with ((a2 + a3 > 0) && a1) { - console.log(x); - } - } while (i < 5 && (a1 > 5)); - } -} diff --git a/tests/baselines/reference/missingCloseParenStatements.symbols b/tests/baselines/reference/missingCloseParenStatements.symbols deleted file mode 100644 index e403570f8e832..0000000000000 --- a/tests/baselines/reference/missingCloseParenStatements.symbols +++ /dev/null @@ -1,37 +0,0 @@ -=== tests/cases/compiler/missingCloseParenStatements.ts === -var a1, a2, a3 = 0; ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) ->a2 : Symbol(a2, Decl(missingCloseParenStatements.ts, 0, 7)) ->a3 : Symbol(a3, Decl(missingCloseParenStatements.ts, 0, 11)) - -if ( a1 && (a2 + a3 > 0) { ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) ->a2 : Symbol(a2, Decl(missingCloseParenStatements.ts, 0, 7)) ->a3 : Symbol(a3, Decl(missingCloseParenStatements.ts, 0, 11)) - - while( (a2 > 0) && a1 ->a2 : Symbol(a2, Decl(missingCloseParenStatements.ts, 0, 7)) ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) - { - do { - var i = i + 1; ->i : Symbol(i, Decl(missingCloseParenStatements.ts, 5, 15)) ->i : Symbol(i, Decl(missingCloseParenStatements.ts, 5, 15)) - - a1 = a1 + i; ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) ->i : Symbol(i, Decl(missingCloseParenStatements.ts, 5, 15)) - - with ((a2 + a3 > 0) && a1 { ->a2 : Symbol(a2, Decl(missingCloseParenStatements.ts, 0, 7)) ->a3 : Symbol(a3, Decl(missingCloseParenStatements.ts, 0, 11)) ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) - - console.log(x); - } - } while (i < 5 && (a1 > 5); ->i : Symbol(i, Decl(missingCloseParenStatements.ts, 5, 15)) ->a1 : Symbol(a1, Decl(missingCloseParenStatements.ts, 0, 3)) - } -} diff --git a/tests/baselines/reference/missingCloseParenStatements.types b/tests/baselines/reference/missingCloseParenStatements.types deleted file mode 100644 index 0d1b7469f6073..0000000000000 --- a/tests/baselines/reference/missingCloseParenStatements.types +++ /dev/null @@ -1,67 +0,0 @@ -=== tests/cases/compiler/missingCloseParenStatements.ts === -var a1, a2, a3 = 0; ->a1 : any ->a2 : any ->a3 : number ->0 : 0 - -if ( a1 && (a2 + a3 > 0) { ->a1 && (a2 + a3 > 0) : boolean ->a1 : any ->(a2 + a3 > 0) : boolean ->a2 + a3 > 0 : boolean ->a2 + a3 : any ->a2 : any ->a3 : number ->0 : 0 - - while( (a2 > 0) && a1 ->(a2 > 0) && a1 : any ->(a2 > 0) : boolean ->a2 > 0 : boolean ->a2 : any ->0 : 0 ->a1 : any - { - do { - var i = i + 1; ->i : any ->i + 1 : any ->i : any ->1 : 1 - - a1 = a1 + i; ->a1 = a1 + i : any ->a1 : any ->a1 + i : any ->a1 : any ->i : any - - with ((a2 + a3 > 0) && a1 { ->(a2 + a3 > 0) && a1 : any ->(a2 + a3 > 0) : boolean ->a2 + a3 > 0 : boolean ->a2 + a3 : any ->a2 : any ->a3 : number ->0 : 0 ->a1 : any - - console.log(x); ->console.log(x) : any ->console.log : any ->console : any ->log : any ->x : any - } - } while (i < 5 && (a1 > 5); ->i < 5 && (a1 > 5) : boolean ->i < 5 : boolean ->i : any ->5 : 5 ->(a1 > 5) : boolean ->a1 > 5 : boolean ->a1 : any ->5 : 5 - } -} diff --git a/tests/baselines/reference/narrowingOfQualifiedNames.errors.txt b/tests/baselines/reference/narrowingOfQualifiedNames.errors.txt new file mode 100644 index 0000000000000..588ee1d5da11f --- /dev/null +++ b/tests/baselines/reference/narrowingOfQualifiedNames.errors.txt @@ -0,0 +1,74 @@ +tests/cases/compiler/narrowingOfQualifiedNames.ts(33,25): error TS2532: Object is possibly 'undefined'. +tests/cases/compiler/narrowingOfQualifiedNames.ts(38,29): error TS2532: Object is possibly 'undefined'. + + +==== tests/cases/compiler/narrowingOfQualifiedNames.ts (2 errors) ==== + // Repro from #43411 + + interface IProperties { + foo?: { + aaa: string + bbb: string + } + } + + function init(properties: IProperties) { + if (properties.foo) { + type FooOK = typeof properties.foo; + properties.foo; // type is { aaa: string; bbb: string; } + for (const x of [1, 2, 3]) { + properties.foo; // type is { aaa: string; bbb: string; } + type FooOrUndefined = typeof properties.foo; // type should be { aaa: string; bbb: string; } + } + } + } + + interface DeepOptional { + a?: { + b?: { + c?: string + } + } + } + + function init2(foo: DeepOptional) { + if (foo.a) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + ~~~~~~~ +!!! error TS2532: Object is possibly 'undefined'. + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + ~~~~~~~ +!!! error TS2532: Object is possibly 'undefined'. + + if (foo.a.b) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + if (foo.a.b.c) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + } + } + } + } + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/narrowingOfQualifiedNames.js b/tests/baselines/reference/narrowingOfQualifiedNames.js new file mode 100644 index 0000000000000..e3d2816849e13 --- /dev/null +++ b/tests/baselines/reference/narrowingOfQualifiedNames.js @@ -0,0 +1,96 @@ +//// [narrowingOfQualifiedNames.ts] +// Repro from #43411 + +interface IProperties { + foo?: { + aaa: string + bbb: string + } +} + +function init(properties: IProperties) { + if (properties.foo) { + type FooOK = typeof properties.foo; + properties.foo; // type is { aaa: string; bbb: string; } + for (const x of [1, 2, 3]) { + properties.foo; // type is { aaa: string; bbb: string; } + type FooOrUndefined = typeof properties.foo; // type should be { aaa: string; bbb: string; } + } + } +} + +interface DeepOptional { + a?: { + b?: { + c?: string + } + } +} + +function init2(foo: DeepOptional) { + if (foo.a) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + if (foo.a.b) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + if (foo.a.b.c) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + } + } + } + } + } + } +} + +//// [narrowingOfQualifiedNames.js] +"use strict"; +// Repro from #43411 +function init(properties) { + if (properties.foo) { + properties.foo; // type is { aaa: string; bbb: string; } + for (var _i = 0, _a = [1, 2, 3]; _i < _a.length; _i++) { + var x = _a[_i]; + properties.foo; // type is { aaa: string; bbb: string; } + } + } +} +function init2(foo) { + if (foo.a) { + for (var _i = 0, _a = [1]; _i < _a.length; _i++) { + var _ = _a[_i]; + if (foo.a.b) { + for (var _b = 0, _c = [1]; _b < _c.length; _b++) { + var _1 = _c[_b]; + if (foo.a.b.c) { + for (var _d = 0, _e = [1]; _d < _e.length; _d++) { + var _2 = _e[_d]; + } + } + } + } + } + } +} diff --git a/tests/baselines/reference/narrowingOfQualifiedNames.symbols b/tests/baselines/reference/narrowingOfQualifiedNames.symbols new file mode 100644 index 0000000000000..f7a4e26d71385 --- /dev/null +++ b/tests/baselines/reference/narrowingOfQualifiedNames.symbols @@ -0,0 +1,255 @@ +=== tests/cases/compiler/narrowingOfQualifiedNames.ts === +// Repro from #43411 + +interface IProperties { +>IProperties : Symbol(IProperties, Decl(narrowingOfQualifiedNames.ts, 0, 0)) + + foo?: { +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + + aaa: string +>aaa : Symbol(aaa, Decl(narrowingOfQualifiedNames.ts, 3, 11)) + + bbb: string +>bbb : Symbol(bbb, Decl(narrowingOfQualifiedNames.ts, 4, 19)) + } +} + +function init(properties: IProperties) { +>init : Symbol(init, Decl(narrowingOfQualifiedNames.ts, 7, 1)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>IProperties : Symbol(IProperties, Decl(narrowingOfQualifiedNames.ts, 0, 0)) + + if (properties.foo) { +>properties.foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + + type FooOK = typeof properties.foo; +>FooOK : Symbol(FooOK, Decl(narrowingOfQualifiedNames.ts, 10, 25)) +>properties.foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + + properties.foo; // type is { aaa: string; bbb: string; } +>properties.foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + + for (const x of [1, 2, 3]) { +>x : Symbol(x, Decl(narrowingOfQualifiedNames.ts, 13, 18)) + + properties.foo; // type is { aaa: string; bbb: string; } +>properties.foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + + type FooOrUndefined = typeof properties.foo; // type should be { aaa: string; bbb: string; } +>FooOrUndefined : Symbol(FooOrUndefined, Decl(narrowingOfQualifiedNames.ts, 14, 25)) +>properties.foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) +>properties : Symbol(properties, Decl(narrowingOfQualifiedNames.ts, 9, 14)) +>foo : Symbol(IProperties.foo, Decl(narrowingOfQualifiedNames.ts, 2, 23)) + } + } +} + +interface DeepOptional { +>DeepOptional : Symbol(DeepOptional, Decl(narrowingOfQualifiedNames.ts, 18, 1)) + + a?: { +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + b?: { +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + c?: string +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + } + } +} + +function init2(foo: DeepOptional) { +>init2 : Symbol(init2, Decl(narrowingOfQualifiedNames.ts, 26, 1)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>DeepOptional : Symbol(DeepOptional, Decl(narrowingOfQualifiedNames.ts, 18, 1)) + + if (foo.a) { +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 29, 16)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 30, 30)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 31, 32)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + for(const _ of [1]) { +>_ : Symbol(_, Decl(narrowingOfQualifiedNames.ts, 34, 17)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 34, 29)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 35, 34)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 36, 36)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + if (foo.a.b) { +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 39, 26)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 40, 38)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 41, 40)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + for(const _ of [1]) { +>_ : Symbol(_, Decl(narrowingOfQualifiedNames.ts, 44, 25)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 44, 37)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 45, 42)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 46, 44)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + if (foo.a.b.c) { +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 49, 36)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 50, 46)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 51, 48)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + + for(const _ of [1]) { +>_ : Symbol(_, Decl(narrowingOfQualifiedNames.ts, 54, 33)) + + type A = typeof foo.a; +>A : Symbol(A, Decl(narrowingOfQualifiedNames.ts, 54, 45)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) + + type B = typeof foo.a.b; +>B : Symbol(B, Decl(narrowingOfQualifiedNames.ts, 55, 50)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) + + type C = typeof foo.a.b.c; +>C : Symbol(C, Decl(narrowingOfQualifiedNames.ts, 56, 52)) +>foo.a.b.c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) +>foo.a.b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>foo.a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>foo : Symbol(foo, Decl(narrowingOfQualifiedNames.ts, 28, 15)) +>a : Symbol(DeepOptional.a, Decl(narrowingOfQualifiedNames.ts, 20, 24)) +>b : Symbol(b, Decl(narrowingOfQualifiedNames.ts, 21, 9)) +>c : Symbol(c, Decl(narrowingOfQualifiedNames.ts, 22, 13)) + } + } + } + } + } + } +} diff --git a/tests/baselines/reference/narrowingOfQualifiedNames.types b/tests/baselines/reference/narrowingOfQualifiedNames.types new file mode 100644 index 0000000000000..f9ec86f075ae8 --- /dev/null +++ b/tests/baselines/reference/narrowingOfQualifiedNames.types @@ -0,0 +1,259 @@ +=== tests/cases/compiler/narrowingOfQualifiedNames.ts === +// Repro from #43411 + +interface IProperties { + foo?: { +>foo : { aaa: string; bbb: string; } | undefined + + aaa: string +>aaa : string + + bbb: string +>bbb : string + } +} + +function init(properties: IProperties) { +>init : (properties: IProperties) => void +>properties : IProperties + + if (properties.foo) { +>properties.foo : { aaa: string; bbb: string; } | undefined +>properties : IProperties +>foo : { aaa: string; bbb: string; } | undefined + + type FooOK = typeof properties.foo; +>FooOK : { aaa: string; bbb: string; } +>properties.foo : { aaa: string; bbb: string; } +>properties : IProperties +>foo : { aaa: string; bbb: string; } + + properties.foo; // type is { aaa: string; bbb: string; } +>properties.foo : { aaa: string; bbb: string; } +>properties : IProperties +>foo : { aaa: string; bbb: string; } + + for (const x of [1, 2, 3]) { +>x : number +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + + properties.foo; // type is { aaa: string; bbb: string; } +>properties.foo : { aaa: string; bbb: string; } +>properties : IProperties +>foo : { aaa: string; bbb: string; } + + type FooOrUndefined = typeof properties.foo; // type should be { aaa: string; bbb: string; } +>FooOrUndefined : { aaa: string; bbb: string; } +>properties.foo : { aaa: string; bbb: string; } +>properties : IProperties +>foo : { aaa: string; bbb: string; } + } + } +} + +interface DeepOptional { + a?: { +>a : { b?: { c?: string | undefined; } | undefined; } | undefined + + b?: { +>b : { c?: string | undefined; } | undefined + + c?: string +>c : string | undefined + } + } +} + +function init2(foo: DeepOptional) { +>init2 : (foo: DeepOptional) => void +>foo : DeepOptional + + if (foo.a) { +>foo.a : { b?: { c?: string | undefined; } | undefined; } | undefined +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } | undefined + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } | undefined +>foo.a.b : { c?: string | undefined; } | undefined +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } | undefined + + type C = typeof foo.a.b.c; +>C : string | undefined +>foo.a.b.c : string | undefined +>foo.a.b : { c?: string | undefined; } | undefined +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } | undefined +>c : string | undefined + + for(const _ of [1]) { +>_ : number +>[1] : number[] +>1 : 1 + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } | undefined +>foo.a.b : { c?: string | undefined; } | undefined +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } | undefined + + type C = typeof foo.a.b.c; +>C : string | undefined +>foo.a.b.c : string | undefined +>foo.a.b : { c?: string | undefined; } | undefined +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } | undefined +>c : string | undefined + + if (foo.a.b) { +>foo.a.b : { c?: string | undefined; } | undefined +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } | undefined + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } + + type C = typeof foo.a.b.c; +>C : string | undefined +>foo.a.b.c : string | undefined +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } +>c : string | undefined + + for(const _ of [1]) { +>_ : number +>[1] : number[] +>1 : 1 + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } + + type C = typeof foo.a.b.c; +>C : string | undefined +>foo.a.b.c : string | undefined +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } +>c : string | undefined + + if (foo.a.b.c) { +>foo.a.b.c : string | undefined +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } +>c : string | undefined + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } + + type C = typeof foo.a.b.c; +>C : string +>foo.a.b.c : string +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } +>c : string + + for(const _ of [1]) { +>_ : number +>[1] : number[] +>1 : 1 + + type A = typeof foo.a; +>A : { b?: { c?: string | undefined; } | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } + + type B = typeof foo.a.b; +>B : { c?: string | undefined; } +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } + + type C = typeof foo.a.b.c; +>C : string +>foo.a.b.c : string +>foo.a.b : { c?: string | undefined; } +>foo.a : { b?: { c?: string | undefined; } | undefined; } +>foo : DeepOptional +>a : { b?: { c?: string | undefined; } | undefined; } +>b : { c?: string | undefined; } +>c : string + } + } + } + } + } + } +} diff --git a/tests/baselines/reference/nestedClassDeclaration.errors.txt b/tests/baselines/reference/nestedClassDeclaration.errors.txt index f897c38d68191..5540ee024378d 100644 --- a/tests/baselines/reference/nestedClassDeclaration.errors.txt +++ b/tests/baselines/reference/nestedClassDeclaration.errors.txt @@ -32,6 +32,7 @@ tests/cases/conformance/classes/nestedClassDeclaration.ts(17,1): error TS1128: D !!! error TS2304: Cannot find name 'C4'. ~ !!! error TS1005: ',' expected. +!!! related TS1007 tests/cases/conformance/classes/nestedClassDeclaration.ts:14:9: The parser expected to find a '}' to match the '{' token here. } } ~ diff --git a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt index 544bddafff278..651c0b66df75c 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt @@ -9,4 +9,5 @@ tests/cases/compiler/objectLiteralWithSemicolons4.ts(3,1): error TS1005: ',' exp !!! 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 +!!! error TS1005: ',' expected. +!!! related TS1007 tests/cases/compiler/objectLiteralWithSemicolons4.ts:1:9: The parser expected to find a '}' to match the '{' token here. \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadNegativeParse.errors.txt b/tests/baselines/reference/objectSpreadNegativeParse.errors.txt index b37200c4f0293..692fb7617da63 100644 --- a/tests/baselines/reference/objectSpreadNegativeParse.errors.txt +++ b/tests/baselines/reference/objectSpreadNegativeParse.errors.txt @@ -28,6 +28,7 @@ tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts(4,20): error T !!! error TS2304: Cannot find name 'matchMedia'. ~ !!! error TS1005: ',' expected. +!!! related TS1007 tests/cases/conformance/types/spread/objectSpreadNegativeParse.ts:3:10: The parser expected to find a '}' to match the '{' token here. ~ !!! error TS1128: Declaration or statement expected. let o10 = { ...get x() { return 12; }}; diff --git a/tests/baselines/reference/parseErrorIncorrectReturnToken.errors.txt b/tests/baselines/reference/parseErrorIncorrectReturnToken.errors.txt index 2cf728848e45e..bc43cd5b7763b 100644 --- a/tests/baselines/reference/parseErrorIncorrectReturnToken.errors.txt +++ b/tests/baselines/reference/parseErrorIncorrectReturnToken.errors.txt @@ -25,6 +25,7 @@ tests/cases/compiler/parseErrorIncorrectReturnToken.ts(12,1): error TS1128: Decl m(n: number) => string { ~~ !!! error TS1005: '{' expected. +!!! related TS1007 tests/cases/compiler/parseErrorIncorrectReturnToken.ts:8:9: The parser expected to find a '}' to match the '{' token here. ~~~~~~ !!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement2.errors.txt b/tests/baselines/reference/parserErrorRecoveryIfStatement2.errors.txt index b88c48182a27b..45dd9935a6229 100644 --- a/tests/baselines/reference/parserErrorRecoveryIfStatement2.errors.txt +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement2.errors.txt @@ -11,7 +11,6 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/IfStatements/parserErro } ~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/conformance/parser/ecmascript5/ErrorRecovery/IfStatements/parserErrorRecoveryIfStatement2.ts:3:8: The parser expected to find a ')' to match the '(' token here. f2() { } f3() { diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement3.errors.txt b/tests/baselines/reference/parserErrorRecoveryIfStatement3.errors.txt index cfd645e592542..631cdb08a90e4 100644 --- a/tests/baselines/reference/parserErrorRecoveryIfStatement3.errors.txt +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement3.errors.txt @@ -11,7 +11,6 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/IfStatements/parserErro } ~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/conformance/parser/ecmascript5/ErrorRecovery/IfStatements/parserErrorRecoveryIfStatement3.ts:3:8: The parser expected to find a ')' to match the '(' token here. f2() { } f3() { diff --git a/tests/baselines/reference/parserFuzz1.errors.txt b/tests/baselines/reference/parserFuzz1.errors.txt index e90dda55244e6..e11d25c48fa56 100644 --- a/tests/baselines/reference/parserFuzz1.errors.txt +++ b/tests/baselines/reference/parserFuzz1.errors.txt @@ -20,4 +20,5 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserFuzz1.ts(2,15): e ~~~~~~ !!! error TS1005: ';' expected. -!!! error TS1005: '{' expected. \ No newline at end of file +!!! error TS1005: '{' expected. +!!! related TS1007 tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserFuzz1.ts:1:9: The parser expected to find a '}' to match the '{' token here. \ No newline at end of file diff --git a/tests/baselines/reference/privateNameComputedPropertyName4(target=es2015).js b/tests/baselines/reference/privateNameComputedPropertyName4(target=es2015).js new file mode 100644 index 0000000000000..235d3b93987e2 --- /dev/null +++ b/tests/baselines/reference/privateNameComputedPropertyName4(target=es2015).js @@ -0,0 +1,39 @@ +//// [privateNameComputedPropertyName4.ts] +// https://github.com/microsoft/TypeScript/issues/44113 +class C1 { + static #qux = 42; + ["bar"] () {} +} +class C2 { + static #qux = 42; + static ["bar"] () {} +} +class C3 { + static #qux = 42; + static ["bar"] = "test"; +} + + +//// [privateNameComputedPropertyName4.js] +var _a, _C1_qux, _b, _C2_qux, _c, _C3_qux; +// https://github.com/microsoft/TypeScript/issues/44113 +class C1 { + ["bar"]() { } +} +_a = C1; +_C1_qux = { value: 42 }; +class C2 { + static ["bar"]() { } +} +_b = C2; +_C2_qux = { value: 42 }; +class C3 { +} +_c = C3; +_C3_qux = { value: 42 }; +Object.defineProperty(C3, "bar", { + enumerable: true, + configurable: true, + writable: true, + value: "test" +}); diff --git a/tests/baselines/reference/privateNameComputedPropertyName4(target=esnext).js b/tests/baselines/reference/privateNameComputedPropertyName4(target=esnext).js new file mode 100644 index 0000000000000..26190d3042c21 --- /dev/null +++ b/tests/baselines/reference/privateNameComputedPropertyName4(target=esnext).js @@ -0,0 +1,30 @@ +//// [privateNameComputedPropertyName4.ts] +// https://github.com/microsoft/TypeScript/issues/44113 +class C1 { + static #qux = 42; + ["bar"] () {} +} +class C2 { + static #qux = 42; + static ["bar"] () {} +} +class C3 { + static #qux = 42; + static ["bar"] = "test"; +} + + +//// [privateNameComputedPropertyName4.js] +// https://github.com/microsoft/TypeScript/issues/44113 +class C1 { + static #qux = 42; + ["bar"]() { } +} +class C2 { + static #qux = 42; + static ["bar"]() { } +} +class C3 { + static #qux = 42; + static ["bar"] = "test"; +} diff --git a/tests/baselines/reference/privateNamesIncompatibleModifiers.errors.txt b/tests/baselines/reference/privateNamesIncompatibleModifiers.errors.txt index f1f44a3d4f143..7f6a6b9faf62c 100644 --- a/tests/baselines/reference/privateNamesIncompatibleModifiers.errors.txt +++ b/tests/baselines/reference/privateNamesIncompatibleModifiers.errors.txt @@ -21,10 +21,11 @@ tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleMod tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts(27,5): error TS1042: 'async' modifier cannot be used here. tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts(28,5): error TS1042: 'async' modifier cannot be used here. tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts(32,5): error TS18019: 'abstract' modifier cannot be used with a private identifier. +tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts(32,14): error TS1267: Property '#quux' cannot have an initializer because it is marked abstract. !!! error TS2318: Cannot find global type 'AsyncIterableIterator'. -==== tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts (22 errors) ==== +==== tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleModifiers.ts (23 errors) ==== class A { public #foo = 3; // Error ~~~~~~ @@ -101,5 +102,7 @@ tests/cases/conformance/classes/members/privateNames/privateNamesIncompatibleMod abstract #quux = 3; // Error ~~~~~~~~ !!! error TS18019: 'abstract' modifier cannot be used with a private identifier. + ~~~~~ +!!! error TS1267: Property '#quux' cannot have an initializer because it is marked abstract. } \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoLinkCodePlain.baseline b/tests/baselines/reference/quickInfoLinkCodePlain.baseline new file mode 100644 index 0000000000000..bea69b5fc4bc6 --- /dev/null +++ b/tests/baselines/reference/quickInfoLinkCodePlain.baseline @@ -0,0 +1,111 @@ +[ + { + "marker": { + "fileName": "/tests/cases/fourslash/quickInfoLinkCodePlain.ts", + "position": 210, + "name": "" + }, + "quickInfo": { + "kind": "method", + "kindModifiers": "deprecated", + "textSpan": { + "start": 209, + "length": 1 + }, + "displayParts": [ + { + "text": "(", + "kind": "punctuation" + }, + { + "text": "method", + "kind": "text" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "C", + "kind": "className" + }, + { + "text": ".", + "kind": "punctuation" + }, + { + "text": "m", + "kind": "methodName" + }, + { + "text": "(", + "kind": "punctuation" + }, + { + "text": ")", + "kind": "punctuation" + }, + { + "text": ":", + "kind": "punctuation" + }, + { + "text": " ", + "kind": "space" + }, + { + "text": "void", + "kind": "keyword" + } + ], + "documentation": [], + "tags": [ + { + "name": "deprecated", + "text": [ + { + "text": "Use ", + "kind": "text" + }, + { + "text": "{@linkplain ", + "kind": "link" + }, + { + "text": "PerspectiveCamera#setFocalLength .setFocalLength()", + "kind": "linkText" + }, + { + "text": "}", + "kind": "link" + }, + { + "text": " and ", + "kind": "text" + }, + { + "text": "{@linkcode ", + "kind": "link" + }, + { + "text": "PerspectiveCamera#filmGauge .filmGauge", + "kind": "linkText" + }, + { + "text": "}", + "kind": "link" + }, + { + "text": " instead.", + "kind": "text" + } + ] + } + ] + } + } +] \ No newline at end of file diff --git a/tests/baselines/reference/reservedWords2.errors.txt b/tests/baselines/reference/reservedWords2.errors.txt index 6ecb9471631bd..599010b436872 100644 --- a/tests/baselines/reference/reservedWords2.errors.txt +++ b/tests/baselines/reference/reservedWords2.errors.txt @@ -45,7 +45,6 @@ tests/cases/compiler/reservedWords2.ts(12,17): error TS1138: Parameter declarati !!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`. ~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/reservedWords2.ts:1:14: The parser expected to find a ')' to match the '(' token here. import * as while from "foo" !!! error TS2300: Duplicate identifier '(Missing)'. @@ -59,7 +58,6 @@ tests/cases/compiler/reservedWords2.ts(12,17): error TS1138: Parameter declarati !!! error TS2304: Cannot find name 'from'. ~~~~~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/compiler/reservedWords2.ts:2:20: The parser expected to find a ')' to match the '(' token here. var typeof = 10; ~~~~~~ diff --git a/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors-with-incremental.js b/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors-with-incremental.js index 308daf394aea9..10d0e3770f161 100644 --- a/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors-with-incremental.js +++ b/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors-with-incremental.js @@ -47,6 +47,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. @@ -76,6 +81,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. diff --git a/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors.js b/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors.js index e9ea12ea0d3e4..4c55b9ce60f7f 100644 --- a/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors.js +++ b/tests/baselines/reference/tsbuild/noEmitOnError/initial-build/syntax-errors.js @@ -47,6 +47,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. @@ -76,6 +81,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. diff --git a/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error-with-incremental.js b/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error-with-incremental.js index 1b17fdb2ee462..4b96a48f8f60c 100644 --- a/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error-with-incremental.js +++ b/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error-with-incremental.js @@ -56,6 +56,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:35 AM] Found 1 error. Watching for file changes. @@ -108,6 +113,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:42 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error.js b/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error.js index 6af8477219c81..3e563e8f60930 100644 --- a/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error.js +++ b/tests/baselines/reference/tsbuild/watchMode/noEmitOnError/does-not-emit-any-files-on-error.js @@ -56,6 +56,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:35 AM] Found 1 error. Watching for file changes. @@ -108,6 +113,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:42 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tsc/incremental/initial-build/with-noEmitOnError-syntax-errors.js b/tests/baselines/reference/tsc/incremental/initial-build/with-noEmitOnError-syntax-errors.js index 6d8d5e1bd8330..ab70d95535c29 100644 --- a/tests/baselines/reference/tsc/incremental/initial-build/with-noEmitOnError-syntax-errors.js +++ b/tests/baselines/reference/tsc/incremental/initial-build/with-noEmitOnError-syntax-errors.js @@ -47,6 +47,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. @@ -155,6 +160,11 @@ Output:: 4 ;   ~ + src/src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + Found 1 error. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js index 01d3cecd1bedd..9b6b0c05fdfbb 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js index 16681988e8f32..17c877f6ac1a6 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -99,6 +104,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js index 60cee519a51fa..c74e95b44358d 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -176,6 +181,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js index bae815eebebfb..9c9b6f756c1bc 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -99,6 +104,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError-with-incremental.js index be4cbb2503da1..02366f1125102 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError-with-incremental.js @@ -49,6 +49,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -180,6 +185,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError.js index da78efc9fba32..fbb7a7ed57463 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/with-noEmitOnError.js @@ -49,6 +49,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -105,6 +110,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError-with-incremental.js index bf7e7e13c154d..07f84519690f9 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError.js index 3c0a5fcd89b5c..442f3d18610b8 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/defaultAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -99,6 +104,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js index 3347e57400a36..ec619eb4a7070 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js index 06c2ed70520e4..c463f068880d6 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependencies/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js index 6a1ef2230ca43..21dbc506c20db 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -176,6 +181,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js index 34366e53ebaa5..35e28f24cf7e8 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/assumeChangesOnlyAffectDirectDependenciesAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -176,6 +181,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError-with-incremental.js index ead341c0c24c2..354221d990443 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError-with-incremental.js @@ -49,6 +49,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -180,6 +185,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError.js index 63c9185d38bde..f3c5e03a4097d 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/default/with-noEmitOnError.js @@ -49,6 +49,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -180,6 +185,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError-with-incremental.js index 1b2e76b260800..5e2009b67b411 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError.js index 9e0103cd7fdc5..0b2f2feee3f16 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/defaultAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError-with-incremental.js index 878514fada7ae..b0cd5f57eb796 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -174,6 +179,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError.js index bdb72e4bede96..10e6adbf42082 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModules/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -174,6 +179,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError-with-incremental.js index f07286fecfbc6..3630b1ed77c64 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError.js index c88348bd5bc26..17038187ea58c 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/incremental/isolatedModulesAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError-with-incremental.js index 517e41b0e0111..63db0fe14a0f0 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -174,6 +179,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError.js index 48c8bcb5bd307..4093ad4830287 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModules/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -99,6 +104,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError-with-incremental.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError-with-incremental.js index 75cf59365fe80..975e40a6ec0a7 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError-with-incremental.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError-with-incremental.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. @@ -175,6 +180,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:44 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError.js b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError.js index 0969d50832bf8..659ad65715340 100644 --- a/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError.js +++ b/tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError.js @@ -43,6 +43,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:32 AM] Found 1 error. Watching for file changes. @@ -99,6 +104,11 @@ Output:: 4 ;   ~ + src/main.ts:2:11 + 2 const a = { +    ~ + The parser expected to find a '}' to match the '{' token here. + [12:00:37 AM] Found 1 error. Watching for file changes. diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index cf132a12d0262..9d10ec17fe95d 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -93,7 +93,6 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err !!! error TS2304: Cannot find name 'is'. ~~~~~~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts:44:3: The parser expected to find a ')' to match the '(' token here. ~~~~~~ !!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ @@ -109,7 +108,6 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err !!! error TS2749: 'numOrStr' refers to a value, but is being used as a type here. Did you mean 'typeof numOrStr'? ~~ !!! error TS1005: ')' expected. -!!! related TS1007 tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts:48:3: The parser expected to find a ')' to match the '(' token here. ~~ !!! error TS2304: Cannot find name 'is'. ~~~~~~ diff --git a/tests/cases/compiler/extendedUnicodePlaneIdentifiers.ts b/tests/cases/compiler/extendedUnicodePlaneIdentifiers.ts index 9210ee3b7c5f6..59baad082b5d9 100644 --- a/tests/cases/compiler/extendedUnicodePlaneIdentifiers.ts +++ b/tests/cases/compiler/extendedUnicodePlaneIdentifiers.ts @@ -3,6 +3,11 @@ const 𝑚 = 4; const 𝑀 = 5; console.log(𝑀 + 𝑚); // 9 +class K { + #𝑚 = 4; + #𝑀 = 5; +} + // lower 8 bits look like 'a' const ၡ = 6; console.log(ၡ ** ၡ); diff --git a/tests/cases/compiler/formatToPartsBigInt.ts b/tests/cases/compiler/formatToPartsBigInt.ts new file mode 100644 index 0000000000000..6b50e98b8b6ea --- /dev/null +++ b/tests/cases/compiler/formatToPartsBigInt.ts @@ -0,0 +1,7 @@ +// @target: esnext + +// Intl.NumberFormat.formatToParts should support bigInt + +// Test Intl methods with new parameter type +new Intl.NumberFormat("fr").formatToParts(3000n); +new Intl.NumberFormat("fr").formatToParts(BigInt(123)); diff --git a/tests/cases/compiler/missingCloseBracketInArray.ts b/tests/cases/compiler/missingCloseBracketInArray.ts deleted file mode 100644 index cb99f0d227757..0000000000000 --- a/tests/cases/compiler/missingCloseBracketInArray.ts +++ /dev/null @@ -1 +0,0 @@ -var alphas:string[] = alphas = ["1","2","3","4" \ No newline at end of file diff --git a/tests/cases/compiler/missingCloseParenStatements.ts b/tests/cases/compiler/missingCloseParenStatements.ts deleted file mode 100644 index 7ff34bdae6a16..0000000000000 --- a/tests/cases/compiler/missingCloseParenStatements.ts +++ /dev/null @@ -1,13 +0,0 @@ -var a1, a2, a3 = 0; -if ( a1 && (a2 + a3 > 0) { - while( (a2 > 0) && a1 - { - do { - var i = i + 1; - a1 = a1 + i; - with ((a2 + a3 > 0) && a1 { - console.log(x); - } - } while (i < 5 && (a1 > 5); - } -} \ No newline at end of file diff --git a/tests/cases/compiler/narrowingOfQualifiedNames.ts b/tests/cases/compiler/narrowingOfQualifiedNames.ts new file mode 100644 index 0000000000000..45dcf5e55c0df --- /dev/null +++ b/tests/cases/compiler/narrowingOfQualifiedNames.ts @@ -0,0 +1,67 @@ +// @strict: true + +// Repro from #43411 + +interface IProperties { + foo?: { + aaa: string + bbb: string + } +} + +function init(properties: IProperties) { + if (properties.foo) { + type FooOK = typeof properties.foo; + properties.foo; // type is { aaa: string; bbb: string; } + for (const x of [1, 2, 3]) { + properties.foo; // type is { aaa: string; bbb: string; } + type FooOrUndefined = typeof properties.foo; // type should be { aaa: string; bbb: string; } + } + } +} + +interface DeepOptional { + a?: { + b?: { + c?: string + } + } +} + +function init2(foo: DeepOptional) { + if (foo.a) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + if (foo.a.b) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + if (foo.a.b.c) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + + for(const _ of [1]) { + type A = typeof foo.a; + type B = typeof foo.a.b; + type C = typeof foo.a.b.c; + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests/cases/conformance/classes/members/privateNames/privateNameComputedPropertyName4.ts b/tests/cases/conformance/classes/members/privateNames/privateNameComputedPropertyName4.ts new file mode 100644 index 0000000000000..e20efa4646f8f --- /dev/null +++ b/tests/cases/conformance/classes/members/privateNames/privateNameComputedPropertyName4.ts @@ -0,0 +1,16 @@ +// @target: esnext, es2015 +// @useDefineForClassFields: true +// @noTypesAndSymbols: true +// https://github.com/microsoft/TypeScript/issues/44113 +class C1 { + static #qux = 42; + ["bar"] () {} +} +class C2 { + static #qux = 42; + static ["bar"] () {} +} +class C3 { + static #qux = 42; + static ["bar"] = "test"; +} diff --git a/tests/cases/conformance/classes/propertyMemberDeclarations/abstractPropertyInitializer.ts b/tests/cases/conformance/classes/propertyMemberDeclarations/abstractPropertyInitializer.ts new file mode 100644 index 0000000000000..42a0999748a7a --- /dev/null +++ b/tests/cases/conformance/classes/propertyMemberDeclarations/abstractPropertyInitializer.ts @@ -0,0 +1,5 @@ +// @strict: true +// @declaration: true +abstract class C { + abstract prop = 1 +} diff --git a/tests/cases/conformance/controlFlow/controlFlowGenericTypes.ts b/tests/cases/conformance/controlFlow/controlFlowGenericTypes.ts index 29ea2d6814a1b..21dbde8c33cb9 100644 --- a/tests/cases/conformance/controlFlow/controlFlowGenericTypes.ts +++ b/tests/cases/conformance/controlFlow/controlFlowGenericTypes.ts @@ -129,3 +129,13 @@ function get(key: K, obj: A): number { } return 0; }; + +// Repro from #44093 + +class EventEmitter { + off(...args: [K, number] | [unknown, string]):void {} +} +function once>(emittingObject: T, eventName: keyof ET): void { + emittingObject.off(eventName, 0); + emittingObject.off(eventName as typeof eventName, 0); +} diff --git a/tests/cases/conformance/jsx/jsxUnclosedParserRecovery.ts b/tests/cases/conformance/jsx/jsxUnclosedParserRecovery.ts new file mode 100644 index 0000000000000..08b6149d37d91 --- /dev/null +++ b/tests/cases/conformance/jsx/jsxUnclosedParserRecovery.ts @@ -0,0 +1,140 @@ +// @Filename: jsxParserRecovery.tsx +// @jsx: preserve + +// should have no errors here; all these functions should parse and resolve +noName(); noClose(); noCloseTypeArg(); noCloseAttrs(); noCloseTypeArgAttrs(); noCloseBracket(); noCloseBracketTypeArgAttrs(); noSelfclose(); noSelfcloseTypeArgAttrs(); +noNameTrailingTag(); noCloseTrailingTag(); noCloseTypeArgTrailingTag(); noCloseAttrsTrailingTag(); noCloseTypeArgAttrsTrailingTag(); noCloseBracketTrailingTag(); noCloseBracketTypeArgAttrsTrailingTag(); // noSelfcloseTrailingTag(); noSelfcloseTypeArgAttrsTrailingTag(); +noNameTrailingText(); noCloseTrailingText(); noCloseTypeArgTrailingText(); noCloseAttrsTrailingText(); noCloseTypeArgAttrsTrailingText(); noCloseBracketTrailingText(); noCloseBracketTypeArgAttrsTrailingText(); // noSelfcloseTrailingText(); noSelfcloseTypeArgAttrsTrailingText(); + +function diddy() { + return null; +} + +var donkey =

+ < +
; +function noName() { } +var donkey =
+ ; +function noClose() { } +var donkey =
+ +
; +function noCloseTypeArg() { } +var donkey =
+ ; +function noCloseAttrs() { } +var donkey =
+ bananas="please" +
; +function noCloseTypeArgAttrs() { } +var donkey =
+ ; +function noCloseBracket() { } +var donkey =
+ bananas="please"/ +
; +function noCloseBracketTypeArgAttrs() { } +var donkey =
+ +
; +function noSelfclose() { } +var donkey =
+ bananas="please"> +
; +function noSelfcloseTypeArgAttrs() { } + +var donkey =
+ < + +
; +function noNameTrailingTag() { } +var donkey =
+ +
; +function noCloseTrailingTag() { } +var donkey =
+ + +
; +function noCloseTypeArgTrailingTag() { } +var donkey =
+ +
; +function noCloseAttrsTrailingTag() { } +var donkey =
+ bananas="please" + +
; +function noCloseTypeArgAttrsTrailingTag() { } +var donkey =
+ +
; +function noCloseBracketTrailingTag() { } +var donkey =
+ bananas="please"/ + +
; +function noCloseBracketTypeArgAttrsTrailingTag() { } +var donkey =
+ + +
; +function noSelfcloseTrailingTag() { } +var donkey =
+ bananas="please"> + +
; +function noSelfcloseTypeArgAttrsTrailingTag() { } + +var donkey =
+ < + Cranky Wrinkly Funky +
; +function noNameTrailingText() { } +var donkey =
+ ; +function noCloseTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noCloseTypeArgTrailingText() { } +var donkey =
+ ; +function noCloseAttrsTrailingText() { } +var donkey =
+ bananas="please" + Cranky Wrinkly Funky +
; +function noCloseTypeArgAttrsTrailingText() { } +var donkey =
+ ; +function noCloseBracketTrailingText() { } +var donkey =
+ bananas="please"/ + Cranky Wrinkly Funky +
; +function noCloseBracketTypeArgAttrsTrailingText() { } +var donkey =
+ + Cranky Wrinkly Funky +
; +function noSelfcloseTrailingText() { } +var donkey =
+ bananas="please"> + Cranky Wrinkly Funky +
; +function noSelfcloseTypeArgAttrsTrailingText() { } diff --git a/tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrayLiteralExpressions/parserErrorRecoveryArrayLiteralExpression3.ts b/tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrayLiteralExpressions/parserErrorRecoveryArrayLiteralExpression3.ts index 18ed3b5ef5a50..58df0691d8e2c 100644 --- a/tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrayLiteralExpressions/parserErrorRecoveryArrayLiteralExpression3.ts +++ b/tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrayLiteralExpressions/parserErrorRecoveryArrayLiteralExpression3.ts @@ -1 +1,2 @@ + var texCoords = [2, 2, 0.5000001192092895, 0.8749999 ; 403953552, 0.5000001192092895, 0.8749999403953552]; diff --git a/tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts b/tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts index 6c13786d81dd6..ba0222660b860 100644 --- a/tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts +++ b/tests/cases/conformance/types/mapped/mappedTypeAsClauses.ts @@ -116,3 +116,39 @@ type Schema = { type Res1 = GetKey; // "Task" type Res2 = GetKeyWithIf; // "Task" type Res3 = keyof GetObjWithIf; // "Task" + +// Repro from #44019 + +type KeysExtendedBy = keyof { [K in keyof T as U extends T[K] ? K : never] : T[K] }; + +interface M { + a: boolean; + b: number; +} + +function f(x: KeysExtendedBy) { + return x; +} + +f("a"); // Error, should allow only "b" + +type NameMap = { 'a': 'x', 'b': 'y', 'c': 'z' }; + +// Distributive, will be simplified + +type TS0 = keyof { [P in keyof T as keyof Record]: string }; +type TS1 = keyof { [P in keyof T as Extract]: string }; +type TS2 = keyof { [P in keyof T as P & ('a' | 'b' | 'c')]: string }; +type TS3 = keyof { [P in keyof T as Exclude]: string }; +type TS4 = keyof { [P in keyof T as NameMap[P & keyof NameMap]]: string }; +type TS5 = keyof { [P in keyof T & keyof NameMap as NameMap[P]]: string }; +type TS6 = keyof { [ K in keyof T as V & (K extends U ? K : never)]: string }; + +// Non-distributive, won't be simplified + +type TN0 = keyof { [P in keyof T as T[P] extends number ? P : never]: string }; +type TN1 = keyof { [P in keyof T as number extends T[P] ? P : never]: string }; +type TN2 = keyof { [P in keyof T as 'a' extends P ? 'x' : 'y']: string }; +type TN3 = keyof { [P in keyof T as Exclude, 'b'>, 'a'>]: string }; +type TN4 = keyof { [K in keyof T as (K extends U ? T[K] : never) extends T[K] ? K : never]: string }; +type TN5 = keyof { [K in keyof T as keyof { [P in K as T[P] extends U ? K : never]: true }]: string }; diff --git a/tests/cases/fourslash/codeFixWrapJsxInFragment3.ts b/tests/cases/fourslash/codeFixWrapJsxInFragment3.ts new file mode 100644 index 0000000000000..a44b5780107a7 --- /dev/null +++ b/tests/cases/fourslash/codeFixWrapJsxInFragment3.ts @@ -0,0 +1,7 @@ +/// + +// @jsx: react-jsx +// @Filename: /a.tsx +////[||] + +verify.rangeAfterCodeFix(`<>`, /*includeWhiteSpace*/false, /*errorCode*/ undefined, /*index*/ 0); diff --git a/tests/cases/fourslash/codeFixWrapJsxInFragment4.ts b/tests/cases/fourslash/codeFixWrapJsxInFragment4.ts new file mode 100644 index 0000000000000..310d881c9042d --- /dev/null +++ b/tests/cases/fourslash/codeFixWrapJsxInFragment4.ts @@ -0,0 +1,7 @@ +/// + +// @jsx: react-jsxdev +// @Filename: /a.tsx +////[||] + +verify.rangeAfterCodeFix(`<>`, /*includeWhiteSpace*/false, /*errorCode*/ undefined, /*index*/ 0); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag1.ts b/tests/cases/fourslash/completionsWithDeprecatedTag1.ts index f3bd7e93d6a5e..1ce322b6a1c4c 100644 --- a/tests/cases/fourslash/completionsWithDeprecatedTag1.ts +++ b/tests/cases/fourslash/completionsWithDeprecatedTag1.ts @@ -25,27 +25,26 @@ verify.completions({ marker: "1", includes: [ - { name: "Foo", kind: "interface", kindModifiers: "deprecated" } + { name: "Foo", kind: "interface", kindModifiers: "deprecated", sortText: completion.SortText.DeprecatedLocationPriority } ] }, { marker: "2", includes: [ - { name: "bar", kind: "method", kindModifiers: "deprecated" } + { name: "bar", kind: "method", kindModifiers: "deprecated", sortText: completion.SortText.DeprecatedLocationPriority } ] }, { marker: "3", includes: [ - { name: "prop", kind: "property", kindModifiers: "deprecated" } + { name: "prop", kind: "property", kindModifiers: "deprecated", sortText: completion.SortText.DeprecatedLocationPriority } ] }, { marker: "4", includes: [ - { name: "foobar", kind: "function", kindModifiers: "export,deprecated" } + { name: "foobar", kind: "function", kindModifiers: "export,deprecated", sortText: completion.SortText.DeprecatedLocationPriority } ] }, { marker: "5", includes: [ - { name: "foobar", kind: "alias", kindModifiers: "export,deprecated" } + { name: "foobar", kind: "alias", kindModifiers: "export,deprecated", sortText: completion.SortText.DeprecatedLocationPriority } ] -} -); +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag10.ts b/tests/cases/fourslash/completionsWithDeprecatedTag10.ts new file mode 100644 index 0000000000000..f12e33feef458 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag10.ts @@ -0,0 +1,24 @@ +/// + +// @Filename: /foo.ts +/////** @deprecated foo */ +////export const foo = 0; + +// @Filename: /index.ts +/////**/ + +verify.completions({ + marker: "", + includes: [{ + name: "foo", + source: "/foo", + sourceDisplay: "./foo", + hasAction: true, + kind: "const", + kindModifiers: "export,deprecated", + sortText: completion.SortText.DeprecatedAutoImportSuggestions + }], + preferences: { + includeCompletionsForModuleExports: true, + }, +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag2.ts b/tests/cases/fourslash/completionsWithDeprecatedTag2.ts index a902c6b30eb8a..9561a9a56c502 100644 --- a/tests/cases/fourslash/completionsWithDeprecatedTag2.ts +++ b/tests/cases/fourslash/completionsWithDeprecatedTag2.ts @@ -9,7 +9,10 @@ verify.completions({ marker: "", - includes: [ - { name: "foo", kind: "function", kindModifiers: "deprecated,declare" } - ] + includes: [{ + name: "foo", + kind: "function", + kindModifiers: "deprecated,declare", + sortText: completion.SortText.DeprecatedLocationPriority + }] }); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag3.ts b/tests/cases/fourslash/completionsWithDeprecatedTag3.ts index 19e9d5c561b90..0be6a6f06a81e 100644 --- a/tests/cases/fourslash/completionsWithDeprecatedTag3.ts +++ b/tests/cases/fourslash/completionsWithDeprecatedTag3.ts @@ -9,7 +9,10 @@ verify.completions({ marker: "", - includes: [ - { name: "foo", kind: "function", kindModifiers: "declare" } - ] + includes: [{ + name: "foo", + kind: "function", + kindModifiers: "declare", + sortText: completion.SortText.LocationPriority + }] }); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag4.ts b/tests/cases/fourslash/completionsWithDeprecatedTag4.ts new file mode 100644 index 0000000000000..9df8bc60e91ba --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag4.ts @@ -0,0 +1,23 @@ +/// + +// @noLib: true + +////f({ +//// a/**/ +//// xyz: ``, +////}); +////declare function f(options: { +//// /** @deprecated abc */ +//// abc?: number, +//// xyz?: string +////}): void; + +verify.completions({ + marker: "", + exact: [{ + name: "abc", + kind: "property", + kindModifiers: "deprecated,declare,optional", + sortText: completion.SortText.DeprecatedOptionalMember + }], +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag5.ts b/tests/cases/fourslash/completionsWithDeprecatedTag5.ts new file mode 100644 index 0000000000000..bebad02f6bcc0 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag5.ts @@ -0,0 +1,24 @@ +/// + +////class Foo { +//// /** @deprecated m */ +//// static m() {} +////} +////Foo./**/ + +verify.completions({ + marker: "", + exact: [ + { + name: "prototype", + sortText: completion.SortText.LocationPriority + }, + { + name: "m", + kind: "method", + kindModifiers: "static,deprecated", + sortText: completion.SortText.DeprecatedLocalDeclarationPriority + }, + ...completion.functionMembers + ] +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag6.ts b/tests/cases/fourslash/completionsWithDeprecatedTag6.ts new file mode 100644 index 0000000000000..b174e97660378 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag6.ts @@ -0,0 +1,17 @@ +/// + +////module Foo { +//// /** @deprecated foo */ +//// export var foo: number; +////} +////Foo./**/ + +verify.completions({ + marker: "", + exact: [{ + name: "foo", + kind: "var", + kindModifiers: "export,deprecated", + sortText: completion.SortText.DeprecatedLocationPriority + }] +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag7.ts b/tests/cases/fourslash/completionsWithDeprecatedTag7.ts new file mode 100644 index 0000000000000..dc1bf9bdac521 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag7.ts @@ -0,0 +1,27 @@ +/// + +// @strict: true + +////interface I { +//// /** @deprecated a */ +//// a: number; +////} + +////const foo = { +//// a: 1 +////} + +////const i: I = { +//// ...foo, +//// /**/ +////} + +verify.completions({ + marker: "", + exact: [{ + name: "a", + sortText: completion.SortText.DeprecatedMemberDeclaredBySpreadAssignment, + kind: 'property', + kindModifiers: "deprecated" + }] +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag8.ts b/tests/cases/fourslash/completionsWithDeprecatedTag8.ts new file mode 100644 index 0000000000000..d326d0daf0931 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag8.ts @@ -0,0 +1,25 @@ +/// + +////class C { +//// /** @deprecated */ +//// p: number; +//// m() { +//// return (/**/) +//// } +////} + +verify.completions({ + marker: "", + includes: [{ + name: "p", + kind: "property", + kindModifiers: "deprecated", + insertText: "this.p", + sortText: completion.SortText.DeprecatedSuggestedClassMembers, + source: completion.CompletionSource.ThisProperty + }], + preferences: { + includeInsertTextCompletions: true + }, + isNewIdentifierLocation: true +}); diff --git a/tests/cases/fourslash/completionsWithDeprecatedTag9.ts b/tests/cases/fourslash/completionsWithDeprecatedTag9.ts new file mode 100644 index 0000000000000..819aeb1802587 --- /dev/null +++ b/tests/cases/fourslash/completionsWithDeprecatedTag9.ts @@ -0,0 +1,30 @@ +/// + +// @lib: dom +// @allowJs: true + +// @Filename: globals.d.ts +/////** @deprecated foo */ +////declare var foo: string; + +// @Filename: index.ts +////class Foo { +//// foo: number; +//// m() { +//// foo/**/ +//// } +////} + +verify.completions({ + marker: "", + includes: [{ + name: "foo", + kind: "var", + kindModifiers: "deprecated,declare", + sortText: completion.SortText.DeprecatedGlobalsOrKeywords + }] +}, { + preferences: { + includeInsertTextCompletions: true + } +}); diff --git a/tests/cases/fourslash/findAllReferencesLinkTag1.ts b/tests/cases/fourslash/findAllReferencesLinkTag1.ts index 323c03dd618d9..8558c0240f19b 100644 --- a/tests/cases/fourslash/findAllReferencesLinkTag1.ts +++ b/tests/cases/fourslash/findAllReferencesLinkTag1.ts @@ -1,5 +1,5 @@ /// -//// class C { +//// class C/*7*/ { //// m/*1*/() { } //// n/*2*/ = 1 //// static s/*3*/() { } @@ -34,7 +34,7 @@ //// r() { } //// } //// -//// interface I { +//// interface I/*8*/ { //// a/*4*/() //// b/*5*/: 1 //// /** @@ -42,6 +42,8 @@ //// * @see {a} //// * {@link I.a} //// * @see {I.a} +//// * {@link I#a} +//// * @see {I#a} //// */ //// c() //// /** @@ -61,4 +63,4 @@ //// function r2/*6*/() { } //// } -verify.baselineFindAllReferences('1', '2', '3', '4', '5', '6') +verify.baselineFindAllReferences('1', '2', '3', '4', '5', '6', '7', '8') diff --git a/tests/cases/fourslash/findAllReferencesLinkTag2.ts b/tests/cases/fourslash/findAllReferencesLinkTag2.ts new file mode 100644 index 0000000000000..6afdafb3db17c --- /dev/null +++ b/tests/cases/fourslash/findAllReferencesLinkTag2.ts @@ -0,0 +1,28 @@ +/// +//// namespace NPR/*5*/ { +//// export class Consider/*4*/ { +//// This/*3*/ = class { +//// show/*2*/() { } +//// } +//// m/*1*/() { } +//// } +//// /** +//// * @see {Consider.prototype.m} +//// * {@link Consider#m} +//// * @see {Consider#This#show} +//// * {@link Consider.This.show} +//// * @see {NPR.Consider#This#show} +//// * {@link NPR.Consider.This#show} +//// * @see {NPR.Consider#This.show} # doesn't parse trailing . +//// * @see {NPR.Consider.This.show} +//// */ +//// export function ref() { } +//// } +//// /** +//// * {@link NPR.Consider#This#show hello hello} +//// * {@link NPR.Consider.This#show} +//// * @see {NPR.Consider#This.show} # doesn't parse trailing . +//// * @see {NPR.Consider.This.show} +//// */ +//// export function outerref() { } +verify.baselineFindAllReferences('1', '2', '3', '4', '5') diff --git a/tests/cases/fourslash/findAllReferencesLinkTag3.ts b/tests/cases/fourslash/findAllReferencesLinkTag3.ts new file mode 100644 index 0000000000000..1783e07a104c8 --- /dev/null +++ b/tests/cases/fourslash/findAllReferencesLinkTag3.ts @@ -0,0 +1,28 @@ +/// +//// namespace NPR/*5*/ { +//// export class Consider/*4*/ { +//// This/*3*/ = class { +//// show/*2*/() { } +//// } +//// m/*1*/() { } +//// } +//// /** +//// * {@linkcode Consider.prototype.m} +//// * {@linkplain Consider#m} +//// * {@linkcode Consider#This#show} +//// * {@linkplain Consider.This.show} +//// * {@linkcode NPR.Consider#This#show} +//// * {@linkplain NPR.Consider.This#show} +//// * {@linkcode NPR.Consider#This.show} # doesn't parse trailing . +//// * {@linkcode NPR.Consider.This.show} +//// */ +//// export function ref() { } +//// } +//// /** +//// * {@linkplain NPR.Consider#This#show hello hello} +//// * {@linkplain NPR.Consider.This#show} +//// * {@linkcode NPR.Consider#This.show} # doesn't parse trailing . +//// * {@linkcode NPR.Consider.This.show} +//// */ +//// export function outerref() { } +verify.baselineFindAllReferences('1', '2', '3', '4', '5') diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 01b2710f91240..2ceb0eb0897ab 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -798,7 +798,14 @@ declare namespace completion { SuggestedClassMembers = "4", GlobalsOrKeywords = "5", AutoImportSuggestions = "6", - JavascriptIdentifiers = "7" + JavascriptIdentifiers = "7", + DeprecatedLocalDeclarationPriority = "8", + DeprecatedLocationPriority = "9", + DeprecatedOptionalMember = "10", + DeprecatedMemberDeclaredBySpreadAssignment = "11", + DeprecatedSuggestedClassMembers = "12", + DeprecatedGlobalsOrKeywords = "13", + DeprecatedAutoImportSuggestions = "14" } export const enum CompletionSource { ThisProperty = "ThisProperty/" diff --git a/tests/cases/fourslash/importStatementCompletions1.ts b/tests/cases/fourslash/importStatementCompletions1.ts index c9f991339314d..c28aa81c7922b 100644 --- a/tests/cases/fourslash/importStatementCompletions1.ts +++ b/tests/cases/fourslash/importStatementCompletions1.ts @@ -73,3 +73,29 @@ } }); }); + +// @Filename: /index13.ts +//// import {} /*13*/ + +// @Filename: /index14.ts +//// import {} f/*14*/ + +// @Filename: /index15.ts +//// import * as foo /*15*/ + +// @Filename: /index16.ts +//// import * as foo f/*16*/ + +[13, 14, 15, 16].forEach(marker => { + verify.completions({ + marker: "" + marker, + exact: { + name: "from", + sortText: completion.SortText.GlobalsOrKeywords, + }, + preferences: { + includeCompletionsForImportStatements: true, + includeInsertTextCompletions: true, + } + }); +}); diff --git a/tests/cases/fourslash/jsDocSee4.ts b/tests/cases/fourslash/jsDocSee4.ts index 344060464a467..124826068a464 100644 --- a/tests/cases/fourslash/jsDocSee4.ts +++ b/tests/cases/fourslash/jsDocSee4.ts @@ -24,4 +24,4 @@ goTo.marker("use2"); verify.goToDefinitionIs(["def2"]); goTo.marker("use3"); -verify.goToDefinitionIs([]); \ No newline at end of file +verify.goToDefinitionIs(["def2"]); diff --git a/tests/cases/fourslash/jsSignature-41059.ts b/tests/cases/fourslash/jsSignature-41059.ts new file mode 100644 index 0000000000000..35e550aaa899f --- /dev/null +++ b/tests/cases/fourslash/jsSignature-41059.ts @@ -0,0 +1,10 @@ +/// + +// @lib: esnext +// @allowNonTsExtensions: true + +// @Filename: Foo.js +//// a.next(/**/); + +goTo.marker(); +verify.signatureHelp({ overloadsCount: 2, text: "Generator.next(): IteratorResult" }); diff --git a/tests/cases/fourslash/quickInfoLinkCodePlain.ts b/tests/cases/fourslash/quickInfoLinkCodePlain.ts new file mode 100644 index 0000000000000..f9f0da678f199 --- /dev/null +++ b/tests/cases/fourslash/quickInfoLinkCodePlain.ts @@ -0,0 +1,12 @@ +/// + +//// export class C { +//// /** +//// * @deprecated Use {@linkplain PerspectiveCamera#setFocalLength .setFocalLength()} and {@linkcode PerspectiveCamera#filmGauge .filmGauge} instead. +//// */ +//// m() { } +//// } +//// new C().m/**/ + +verify.noErrors() +verify.baselineQuickInfo(); diff --git a/tests/cases/fourslash/refactorConvertExport_onlyValidIdentifiers.ts b/tests/cases/fourslash/refactorConvertExport_onlyValidIdentifiers.ts new file mode 100644 index 0000000000000..630d95e72603a --- /dev/null +++ b/tests/cases/fourslash/refactorConvertExport_onlyValidIdentifiers.ts @@ -0,0 +1,25 @@ +/// + +// @allowJs: true + +// @Filename: /a.js +/////*[| |]*/ /** x */ export default 1; + +// @Filename: /b.js +/////*[| |]*/ /** x */ export default (1); + +// @Filename: /c.js +/////*[| |]*/ /** x */ export default x; + +goTo.eachRange(r => { + goTo.selectRange(r); + verify.not.refactorAvailable("Convert export"); +}); + +// goTo.selectRange(test.ranges()[0]); +// edit.applyRefactor({ +// refactorName: "Convert export", +// actionName: "Convert default export to named export", +// actionDescription: "Convert default export to named export", +// newContent: { "/a.js": `...` }, +// });