From 82cb50fa4543725d24dc6a6a549c1142f80d3e8c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 17 May 2021 11:13:30 -0700 Subject: [PATCH 01/31] Simplify codeql github action (#44124) The current action is failing with an error that recommends removing the `git checkout HEAD^2` step. --- .github/workflows/codeql.yml | 5 ----- 1 file changed, 5 deletions(-) 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 From 271e069af34e8259a15dce6d667c31247059c21d Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 17 May 2021 17:48:15 -0700 Subject: [PATCH 02/31] =?UTF-8?q?Don=E2=80=99t=20offer=20import=20statemen?= =?UTF-8?q?t=20completions=20at=20`from`=20position=20(#44125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Don’t offer import statement completions at `from` position * Set isGlobalCompletion to false, use indexOf lookup --- src/services/completions.ts | 47 +++++++++++++++---- .../fourslash/importStatementCompletions1.ts | 26 ++++++++++ 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 98d5add6fe0a4..5ed1608fbcdcb 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -174,6 +174,8 @@ namespace ts.Completions { return jsdocCompletionInfo(JsDoc.getJSDocTagCompletions()); case CompletionDataKind.JsDocParameterName: return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case CompletionDataKind.Keywords: + return specificKeywordCompletionInfo(completionData.keywords); default: return Debug.assertNever(completionData); } @@ -183,6 +185,20 @@ namespace ts.Completions { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; } + function specificKeywordCompletionInfo(keywords: readonly SyntaxKind[]): CompletionInfo { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(k => ({ + name: tokenToString(k)!, + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + sortText: SortText.GlobalsOrKeywords, + })), + }; + } + function getOptionalReplacementSpan(location: Node | undefined) { // StringLiteralLike locations are handled separately in stringCompletions.ts return location?.kind === SyntaxKind.Identifier ? createTextSpanFromNode(location) : undefined; @@ -802,6 +818,8 @@ namespace ts.Completions { return JsDoc.getJSDocTagCompletionDetails(name); case CompletionDataKind.JsDocParameterName: return JsDoc.getJSDocParameterNameCompletionDetails(name); + case CompletionDataKind.Keywords: + return request.keywords.indexOf(stringToToken(name)!) > -1 ? createSimpleDetails(name, ScriptElementKind.keyword, SymbolDisplayPartKind.keyword) : undefined; default: return Debug.assertNever(request); } @@ -893,7 +911,7 @@ namespace ts.Completions { return completion.type === "symbol" ? completion.symbol : undefined; } - const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName } + const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName, Keywords } /** true: after the `=` sign but no identifier has been typed yet. Else is the Identifier after the initializer. */ type IsJsxInitializer = boolean | Identifier; interface CompletionData { @@ -918,7 +936,10 @@ namespace ts.Completions { readonly isJsxIdentifierExpected: boolean; readonly importCompletionNode?: Node; } - type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; + type Request = + | { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } + | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag } + | { readonly kind: CompletionDataKind.Keywords, keywords: readonly SyntaxKind[] }; export const enum CompletionKind { ObjectPropertyDeclaration, @@ -1101,13 +1122,17 @@ namespace ts.Completions { let location = getTouchingPropertyName(sourceFile, position); if (contextToken) { + const importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === SyntaxKind.FromKeyword) { + return { kind: CompletionDataKind.Keywords, keywords: [SyntaxKind.FromKeyword] }; + } // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients // to opt in with the `includeCompletionsForImportStatements` user preference. - importCompletionNode = preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText - ? getImportCompletionNode(contextToken) - : undefined; + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -3041,7 +3066,7 @@ namespace ts.Completions { function getImportCompletionNode(contextToken: Node) { const candidate = getCandidate(); - return candidate && rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + return candidate === SyntaxKind.FromKeyword || candidate && rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; function getCandidate() { const parent = contextToken.parent; @@ -3049,9 +3074,13 @@ namespace ts.Completions { return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; } if (isNamedImports(parent) || isNamespaceImport(parent)) { - return isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name - ? parent.parent.parent - : undefined; + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === SyntaxKind.CloseBraceToken || contextToken.kind === SyntaxKind.Identifier + ? SyntaxKind.FromKeyword + : parent.parent.parent; + } + return undefined; } if (isImportKeyword(contextToken) && isSourceFile(parent)) { // A lone import keyword with nothing following it does not parse as a statement at all 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, + } + }); +}); From 9136bb13fe505d909c8d0e2db4c298c41f184ae8 Mon Sep 17 00:00:00 2001 From: David Michon Date: Mon, 17 May 2021 18:16:32 -0700 Subject: [PATCH 03/31] Generate SourceMap mappings string using array of character codes and fewer String.fromCharCode calls (#44031) * Test normal char code array for source mappings * Limit buffer size, minor performance tweaks * Always commit at exactly chunk size Co-authored-by: David Michon --- src/compiler/sourcemap.ts | 88 +++++++++++++++++++++++---------------- 1 file changed, 52 insertions(+), 36 deletions(-) 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; From 1c12eeecb81befc109e71866a127767babe8d35b Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 18 May 2021 06:06:26 +0000 Subject: [PATCH 04/31] Update package-lock.json --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index df19d4464e882..47b5c5b797bd6 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", From fc07ee2ad7b41b1afd3a14eeee56cd371198a76d Mon Sep 17 00:00:00 2001 From: Eli Barzilay Date: Sat, 15 May 2021 07:15:42 -0400 Subject: [PATCH 05/31] `skipParenthesesUp()` is exactly the same as `walkUpParenthesizedExpressions()` Remove the former since the latter is based on the generel `walkUp()`. --- src/compiler/utilities.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 6dfdc7b3138eb..0b2d044aa21e1 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2853,13 +2853,6 @@ namespace ts { return skipOuterExpressions(node, OuterExpressionKinds.Parentheses); } - function skipParenthesesUp(node: Node): Node { - while (node.kind === SyntaxKind.ParenthesizedExpression) { - node = node.parent; - } - return node; - } - // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped export function isDeleteTarget(node: Node): boolean { if (node.kind !== SyntaxKind.PropertyAccessExpression && node.kind !== SyntaxKind.ElementAccessExpression) { @@ -5397,7 +5390,7 @@ namespace ts { function writeOrReadWrite(): AccessKind { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && skipParenthesesUp(parent.parent).kind === SyntaxKind.ExpressionStatement ? AccessKind.Write : AccessKind.ReadWrite; + return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === SyntaxKind.ExpressionStatement ? AccessKind.Write : AccessKind.ReadWrite; } } function reverseAccessKind(a: AccessKind): AccessKind { From db01e84700023a4b728fd6e38878264160c43fbf Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Tue, 18 May 2021 16:20:57 +0300 Subject: [PATCH 06/31] feat(eslint): consistent-type-assertions (#43556) --- .eslintrc.json | 1 + scripts/buildProtocol.ts | 10 +- src/compiler/binder.ts | 214 +- src/compiler/checker.ts | 2094 ++++++++--------- src/compiler/commandLineParser.ts | 38 +- src/compiler/core.ts | 4 +- src/compiler/debug.ts | 28 +- src/compiler/emitter.ts | 360 +-- src/compiler/factory/nodeFactory.ts | 24 +- src/compiler/factory/parenthesizerRules.ts | 14 +- src/compiler/factory/utilities.ts | 16 +- src/compiler/parser.ts | 546 ++--- src/compiler/path.ts | 2 +- src/compiler/program.ts | 22 +- src/compiler/sys.ts | 2 +- src/compiler/transformers/destructuring.ts | 10 +- src/compiler/transformers/es2015.ts | 122 +- src/compiler/transformers/es2016.ts | 2 +- src/compiler/transformers/es2017.ts | 24 +- src/compiler/transformers/es2018.ts | 14 +- src/compiler/transformers/es2020.ts | 4 +- src/compiler/transformers/es2021.ts | 2 +- src/compiler/transformers/es5.ts | 2 +- src/compiler/transformers/generators.ts | 148 +- src/compiler/transformers/jsx.ts | 8 +- .../transformers/module/esnextAnd2015.ts | 2 +- src/compiler/transformers/module/module.ts | 30 +- src/compiler/transformers/module/system.ts | 62 +- src/compiler/transformers/ts.ts | 106 +- src/compiler/transformers/utilities.ts | 34 +- src/compiler/utilities.ts | 192 +- src/compiler/utilitiesPublic.ts | 10 +- src/compiler/visitorPublic.ts | 6 +- src/compiler/watch.ts | 2 +- src/executeCommandLine/executeCommandLine.ts | 4 +- src/harness/client.ts | 6 +- src/harness/evaluatorImpl.ts | 2 +- src/harness/fourslashImpl.ts | 6 +- src/harness/harnessIO.ts | 4 +- src/harness/harnessLanguageService.ts | 2 +- src/harness/harnessUtils.ts | 40 +- src/harness/loggedIO.ts | 20 +- src/harness/vfsUtil.ts | 10 +- src/harness/virtualFileSystemWithWatch.ts | 12 +- src/server/editorServices.ts | 16 +- src/server/project.ts | 2 +- src/server/scriptVersionCache.ts | 30 +- src/server/session.ts | 26 +- src/server/utilitiesPublic.ts | 6 +- src/services/breakpoints.ts | 104 +- src/services/classifier.ts | 28 +- src/services/classifier2020.ts | 2 +- .../codefixes/convertToMappedObjectType.ts | 2 +- .../fixAddModuleReferTypeMissingTypeof.ts | 2 +- src/services/codefixes/fixUnusedIdentifier.ts | 4 +- src/services/codefixes/generateAccessors.ts | 8 +- src/services/codefixes/helpers.ts | 2 +- src/services/codefixes/inferFromUsage.ts | 24 +- src/services/codefixes/returnValueCorrect.ts | 2 +- src/services/codefixes/wrapJsxInFragment.ts | 2 +- src/services/completions.ts | 16 +- src/services/documentHighlights.ts | 10 +- src/services/findAllReferences.ts | 20 +- src/services/formatting/formatting.ts | 22 +- src/services/formatting/rules.ts | 4 +- src/services/formatting/smartIndenter.ts | 24 +- src/services/goToDefinition.ts | 2 +- src/services/jsDoc.ts | 6 +- src/services/navigateTo.ts | 2 +- src/services/navigationBar.ts | 58 +- src/services/outliningElementsCollector.ts | 14 +- .../convertParamsToDestructuredObject.ts | 2 +- src/services/refactors/extractSymbol.ts | 12 +- src/services/services.ts | 20 +- src/services/shims.ts | 22 +- src/services/signatureHelp.ts | 4 +- src/services/stringCompletions.ts | 2 +- src/services/symbolDisplay.ts | 18 +- src/services/textChanges.ts | 8 +- src/services/transpile.ts | 4 +- src/services/utilities.ts | 90 +- src/testRunner/projectsRunner.ts | 4 +- src/testRunner/runner.ts | 6 +- .../config/convertTypeAcquisitionFromJson.ts | 14 +- src/testRunner/unittests/config/matchFiles.ts | 6 +- src/testRunner/unittests/customTransforms.ts | 4 +- .../unittests/reuseProgramStructure.ts | 12 +- .../unittests/services/extract/ranges.ts | 2 +- .../unittests/services/preProcessFile.ts | 26 +- .../unittests/services/textChanges.ts | 4 +- .../unittests/services/transpile.ts | 8 +- src/testRunner/unittests/tsbuild/publicApi.ts | 4 +- src/testRunner/unittests/tscWatch/helpers.ts | 2 +- .../tsserver/cachingFileSystemInformation.ts | 8 +- .../unittests/tsserver/cancellationToken.ts | 76 +- .../unittests/tsserver/compileOnSave.ts | 30 +- .../unittests/tsserver/configuredProjects.ts | 8 +- .../events/projectLanguageServiceState.ts | 4 +- .../tsserver/events/projectLoading.ts | 4 +- .../events/projectUpdatedInBackground.ts | 4 +- .../unittests/tsserver/externalProjects.ts | 36 +- src/testRunner/unittests/tsserver/helpers.ts | 4 +- .../unittests/tsserver/inferredProjects.ts | 32 +- .../unittests/tsserver/projectErrors.ts | 36 +- src/testRunner/unittests/tsserver/projects.ts | 12 +- src/testRunner/unittests/tsserver/reload.ts | 44 +- src/testRunner/unittests/tsserver/session.ts | 12 +- .../unittests/tsserver/skipLibCheck.ts | 20 +- .../unittests/tsserver/typingsInstaller.ts | 18 +- .../unittests/tsserver/watchEnvironment.ts | 8 +- src/tsserver/nodeServer.ts | 2 +- src/tsserver/server.ts | 2 +- src/typingsInstaller/nodeTypingsInstaller.ts | 10 +- src/typingsInstallerCore/typingsInstaller.ts | 10 +- src/webServer/webServer.ts | 6 +- 115 files changed, 2680 insertions(+), 2679 deletions(-) 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/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..1bc85ef66410f 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,7 +2516,7 @@ 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) { node.flowNode = currentFlow; @@ -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 576c055762f85..8c62ab84799d0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -781,7 +781,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 +792,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 +1152,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 +1326,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 +1402,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 +1578,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 +1640,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 +1744,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 +1754,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 +1773,7 @@ namespace ts { useResult = lastLocation.kind === SyntaxKind.Parameter || ( - lastLocation === (location).type && + lastLocation === (location as FunctionLikeDeclaration).type && !!findAncestor(result.valueDeclaration, isParameter) ); } @@ -1782,7 +1782,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 +1796,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 +1886,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 +1895,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 +1947,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 +2012,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 +2104,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 +2148,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 +2252,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 +2284,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 +2496,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 +2727,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 +2923,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 +3082,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 +3106,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 +3815,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 +3836,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 +3867,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 +3901,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 +3946,7 @@ namespace ts { } switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location)) { + if (!isExternalOrCommonJsModule(location as SourceFile)) { break; } // falls through @@ -4275,11 +4275,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 +4622,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 +4698,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 +4717,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 +4739,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 +4759,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 +4802,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 +4875,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 +4948,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 +5032,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 +5158,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 +5263,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 +5540,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 +6018,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 +6028,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 +7761,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 +7835,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 +7845,7 @@ namespace ts { return name; } if (nameType.flags & TypeFlags.UniqueESSymbol) { - return `[${getNameOfSymbolAsWritten((nameType).symbol, context)}]`; + return `[${getNameOfSymbolAsWritten((nameType as UniqueESSymbolType).symbol, context)}]`; } } } @@ -7890,7 +7890,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 +8017,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 +8041,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 +8097,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 +8147,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 +8254,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,7 +8315,7 @@ 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); type = getFlowTypeOfDestructuring(declaration, declaredType); @@ -8332,7 +8332,7 @@ 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)) { @@ -8366,12 +8366,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 +8397,7 @@ namespace ts { } if (isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); + return getTypeForBindingElement(declaration as BindingElement); } const isOptional = includeOptionality && ( @@ -8428,7 +8428,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 +8508,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 +8849,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 +8888,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 +9038,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 +9323,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 +9331,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 +9397,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 +9409,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 +9469,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 +9516,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 +9581,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 +9598,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 +9636,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 +9656,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 +9746,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 +9766,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 +9816,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 +9843,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 +9856,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 +9906,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 +9922,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 +9942,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 +9971,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 +10062,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 +10111,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 +10147,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 +10220,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 +10405,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 +11053,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 +11090,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 +11138,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 +11171,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 +11219,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 +11228,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 +11261,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 +11310,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 +11344,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 +11378,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); } @@ -11499,7 +11499,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 +11548,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 +11570,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 +11602,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).noUncheckedIndexedAccessCandidate); 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 +11700,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 +11903,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 +11923,7 @@ namespace ts { } const reduced = getUnionType(reducedTypes); if (reduced.flags & TypeFlags.Union) { - (reduced).resolvedReducedType = reduced; + (reduced as UnionType).resolvedReducedType = reduced; } return reduced; } @@ -11947,12 +11947,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 +11972,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 +11991,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 +12014,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 +12250,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 +12320,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 +12425,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 +12439,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 +12458,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 +12659,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 +12683,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 +12795,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 +12805,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 +12819,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 +12862,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 +12886,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 +13037,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 +13045,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 +13066,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 +13083,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 +13216,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 +13325,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 +13426,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 +13438,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 +13537,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 +13708,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 +13747,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 +13810,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 +13832,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 +13898,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 +13907,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 +13958,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 +13976,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 +14002,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 +14120,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 +14151,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 +14255,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 +14276,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 +14299,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; } @@ -14338,11 +14338,11 @@ namespace ts { // 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))); + type.flags & TypeFlags.Conditional && (!(type as ConditionalType).root.isDistributive || maybeNonDistributiveNameType((type as ConditionalType).checkType)) || + type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) && some((type as UnionOrIntersectionType | TemplateLiteralType).types, maybeNonDistributiveNameType) || + type.flags & (TypeFlags.Index | TypeFlags.StringMapping) && maybeNonDistributiveNameType((type as IndexType | StringMappingType).type) || + type.flags & TypeFlags.IndexedAccess && maybeNonDistributiveNameType((type as IndexedAccessType).indexType) || + type.flags & TypeFlags.Substitution && maybeNonDistributiveNameType((type as SubstitutionType).substitute))); } function getLiteralTypeFromPropertyName(name: PropertyName) { @@ -14393,10 +14393,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 IntersectionType).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) && maybeNonDistributiveNameType(getNameTypeFromMappedType(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 +14489,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 +14507,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 +14524,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,14 +14548,14 @@ 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); + const type = createType(TypeFlags.IndexedAccess) as IndexedAccessType; type.objectType = objectType; type.indexType = indexType; type.aliasSymbol = aliasSymbol; @@ -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,7 +14655,7 @@ namespace ts { } errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, IndexKind.Number)); return mapType(objectType, t => { - const restType = getRestTypeOfTupleType(t) || undefinedType; + const restType = getRestTypeOfTupleType(t as TupleTypeReference) || undefinedType; return noUncheckedIndexedAccessCandidate ? getUnionType([restType, undefinedType]) : restType; }); } @@ -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)); @@ -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; } @@ -14964,7 +14964,7 @@ namespace ts { 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; @@ -15016,7 +15016,7 @@ namespace ts { if (indexType.flags & TypeFlags.Union && !(indexType.flags & TypeFlags.Boolean)) { const propTypes: Type[] = []; let wasMissingProp = false; - for (const t of (indexType).types) { + for (const t of (indexType as UnionType).types) { const propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags, shouldIncludeUndefined); if (propType) { propTypes.push(propType); @@ -15048,8 +15048,8 @@ namespace ts { const potentialAlias = getAliasSymbolForTypeNode(node); const resolved = getIndexedAccessType(objectType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, 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 +15058,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 +15072,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 +15144,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 +15164,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 +15453,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 +15546,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 +15554,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 +15607,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 +15728,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 +15755,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 +15768,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 +15970,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 +16008,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 +16020,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 +16031,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 +16044,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 +16058,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 +16146,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 +16154,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 +16195,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 +16236,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 +16264,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).noUncheckedIndexedAccessCandidate, /*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 +16351,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 +16419,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 +16430,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 +16470,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 +17190,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 +17251,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 +17263,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 +17282,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 +17317,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 +17725,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 +17786,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 +17814,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 +17905,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 +17917,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 +17936,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 +18029,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 +18305,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 +18316,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 +18337,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 +18366,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 +18401,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 +18416,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 +18446,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 +18460,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, (target as IndexedAccessType).noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); if (constraint) { if (reportErrors && originalErrorInfo) { // create a new chain for the constraint error @@ -18491,8 +18491,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 +18574,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 +18611,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 +18631,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 +18654,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 +18664,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 +18693,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 +19420,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 +19617,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 +19723,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 +19772,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 +19781,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 +19795,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 +20063,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 +20131,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 +20145,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 +20216,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 +20271,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 +20296,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 +20387,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 +20427,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 +20442,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 +20544,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 +20580,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 +20637,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 +20814,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 +20834,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 +20925,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 +21012,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 +21146,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 +21154,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 +21174,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 +21184,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 +21231,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 +21259,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 +21276,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 +21295,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 +21427,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 +21440,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 +21524,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 +21565,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 +21589,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 +21603,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 +21949,18 @@ 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.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 +21983,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 +22011,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 +22043,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 +22142,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 +22159,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 +22177,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 +22222,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 +22231,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 +22240,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 +22254,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 +22280,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 +22347,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 +22364,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 +22420,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 +22447,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 +22490,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 +22530,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 +22543,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 +22552,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 +22573,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 +22594,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 +22626,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 +22638,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 +22659,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 +22669,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 +22700,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 +22721,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 +22754,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 +22779,7 @@ namespace ts { return undefined; } case SyntaxKind.ParenthesizedExpression: - return getTypeOfDottedName((node).expression, diagnostic); + return getTypeOfDottedName((node as ParenthesizedExpression).expression, diagnostic); } } } @@ -22830,7 +22830,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 +22846,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 +22865,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 +22881,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 +22898,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 +22933,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 +23023,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 +23097,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 +23121,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 +23157,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 +23190,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 +23204,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 +23257,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 +23273,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 +23412,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 +23450,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 +23464,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 +23482,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 +23524,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 +23544,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 +23649,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 +23760,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 +23768,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 +23899,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 +23986,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 +24006,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 +24024,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 +24054,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 +24072,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 +24111,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 +24121,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 +24322,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 +24442,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 +24479,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 +24684,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 +24702,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 +24841,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 +24907,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 +24952,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 +24963,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 +25064,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 +25164,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); } @@ -25191,14 +25191,14 @@ namespace ts { 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 +25320,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 +25368,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 +25406,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 +25472,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 +25559,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 +25604,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 +25633,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 +25786,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 +25928,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 +25951,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 +25989,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 +26007,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 +26032,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 +26058,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 +26338,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 +26392,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 +26924,7 @@ namespace ts { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { - checkGrammarJsxElement(node); + checkGrammarJsxElement(node as JsxOpeningLikeElement); } checkJsxPreconditions(node); @@ -26934,7 +26934,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 +26957,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 +26999,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 +27122,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 +27138,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 +27146,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 +27736,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 +27862,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 +27871,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 +27896,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; @@ -27966,7 +27966,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 +28033,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 +28066,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 +28141,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 +28280,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,13 +28290,13 @@ 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); } } @@ -28591,7 +28591,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 +28626,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 +28641,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 +28814,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 +29478,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 +30024,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 +30173,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 +30289,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 +30309,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 +30453,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 +30485,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 +30495,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 +30503,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 +30724,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 +30834,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 +31356,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; @@ -31559,14 +31559,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 +31578,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 +31588,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 +32457,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 +32528,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 +32643,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 +32708,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 +32764,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 +32805,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 +32826,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 +33031,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 +33068,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 +33120,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 +33141,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 +33308,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: @@ -33422,13 +33422,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 +33445,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 +33455,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 +33567,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 +33641,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 +33683,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 +33727,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 +33752,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 +33892,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 +33917,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 +33945,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 +34200,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 +34273,7 @@ namespace ts { return type; } - const typeAsAwaitable = type; + const typeAsAwaitable = type as PromiseOrAwaitableType; if (typeAsAwaitable.awaitedTypeOfType) { return typeAsAwaitable.awaitedTypeOfType; } @@ -34285,7 +34285,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 +34570,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 +34656,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 +34671,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 +34981,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 +35209,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 +35241,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 +35255,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 +35271,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 +35307,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 +35326,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 +35774,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 +35863,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 +35904,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 +35975,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 +36794,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 +36895,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]; } } @@ -36946,7 +36946,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]; } @@ -37021,7 +37021,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])) { @@ -37048,7 +37048,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); @@ -37143,9 +37143,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); @@ -37364,7 +37364,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) { @@ -37578,7 +37578,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)) { @@ -37594,8 +37594,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) { @@ -37622,7 +37622,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)) { @@ -37745,9 +37745,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; @@ -37755,10 +37755,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; @@ -37773,27 +37773,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) { @@ -37833,9 +37833,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) { @@ -37880,7 +37880,7 @@ namespace ts { return false; } - const enumDeclaration = declaration; + const enumDeclaration = declaration as EnumDeclaration; if (!enumDeclaration.members.length) { return false; } @@ -37909,7 +37909,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; } @@ -38036,7 +38036,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; @@ -38050,7 +38050,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 @@ -38410,7 +38410,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); @@ -38555,60 +38555,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: @@ -38642,67 +38642,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); @@ -38831,20 +38831,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; @@ -39022,7 +39022,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); @@ -39192,15 +39192,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; @@ -39277,7 +39277,7 @@ namespace ts { } while (isRightSideOfQualifiedNameOrPropertyAccess(name)) { - name = name.parent; + name = name.parent as QualifiedName | PropertyAccessEntityNameExpression; } if (isHeritageClauseElementIdentifier(name)) { @@ -39320,7 +39320,7 @@ namespace ts { 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); @@ -39340,9 +39340,9 @@ namespace ts { return links.resolvedSymbol; } } - 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); } const jsdocReference = getJSDocEntryNameReference(name); @@ -39372,7 +39372,7 @@ namespace ts { } } if (name.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(name, /*meaning*/ SymbolFlags.FunctionScopedVariable); + return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable); } return undefined; @@ -39380,7 +39380,7 @@ namespace ts { 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; @@ -39402,14 +39402,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; @@ -39422,7 +39422,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); @@ -39447,7 +39447,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; @@ -39458,11 +39458,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); @@ -39496,7 +39496,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; } @@ -39526,12 +39526,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) { @@ -39570,7 +39570,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); @@ -39593,13 +39593,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 @@ -39632,7 +39632,7 @@ namespace ts { function getRegularTypeOfExpression(expr: Expression): Type { if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; + expr = expr.parent as Expression; } return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); } @@ -39783,7 +39783,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; @@ -39905,13 +39905,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; } @@ -40236,7 +40236,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 { @@ -40588,9 +40588,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. @@ -40709,7 +40709,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 { @@ -40717,7 +40717,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); } @@ -40971,10 +40971,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) { @@ -41329,8 +41329,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; @@ -41430,7 +41430,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) { @@ -41561,7 +41561,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; @@ -41687,20 +41687,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; @@ -41780,11 +41780,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); @@ -41846,14 +41846,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) { @@ -42376,7 +42376,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; } @@ -42384,7 +42384,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/emitter.ts b/src/compiler/emitter.ts index a3007559f0dd9..acd801ef97b88 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) { @@ -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..113761a8367eb 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -531,7 +531,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 +1896,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 +1912,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 +2849,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 @@ -5457,13 +5457,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 +5481,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 +5746,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/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..6c0ee33b57e76 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,10 +476,10 @@ 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)) || visitNodes(cbNode, cbNodes, (node as JSDoc).tags); @@ -493,37 +493,37 @@ namespace ts { case SyntaxKind.JSDocPropertyTag: return visitNode(cbNode, (node as JSDocTag).tagName) || ((node as JSDocPropertyLikeTag).isNameFirst - ? visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).typeExpression) || + ? 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).typeExpression) || - visitNode(cbNode, (node).name)) || + : 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)); case SyntaxKind.JSDocImplementsTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).class) || + 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) || + 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) || + 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) || + ? 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).fullName) || - visitNode(cbNode, (node).typeExpression)) || + : 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) || @@ -538,9 +538,9 @@ namespace ts { 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)); 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.JSDocTypeLiteral: @@ -555,7 +555,7 @@ namespace ts { return visitNode(cbNode, (node as JSDocTag).tagName) || (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); } } @@ -1600,14 +1600,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 +1744,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 +2127,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 +2304,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 +2404,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 +2414,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 +2684,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 +2700,7 @@ namespace ts { } function parseLiteralNode(): LiteralExpression { - return parseLiteralLikeNode(token()); + return parseLiteralLikeNode(token()) as LiteralExpression; } function parseTemplateHead(isTaggedTemplate: boolean): TemplateHead { @@ -2709,13 +2709,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 +4031,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 +4307,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 +4545,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 +4602,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 +4723,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 +4734,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); } @@ -4919,7 +4919,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; } } @@ -5234,7 +5234,7 @@ namespace ts { continue; } - return expression; + return expression as MemberExpression; } } @@ -6287,7 +6287,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 +6743,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 +6898,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 +6913,7 @@ namespace ts { flags |= NodeFlags.GlobalAugmentation; } else { - name = parseLiteralNode(); + name = parseLiteralNode() as StringLiteral; name.text = internIdentifier(name.text); } let body: ModuleBlock | undefined; @@ -7319,7 +7319,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(); @@ -8290,7 +8290,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 +8410,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 +8438,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 +8591,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 +8827,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 +9124,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 +9134,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..429c9089c1f58 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -564,7 +564,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[] } { 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/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/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(