diff --git a/scripts/processDiagnosticMessages.ts b/scripts/processDiagnosticMessages.ts index 6318b131309..0b7ff403a63 100644 --- a/scripts/processDiagnosticMessages.ts +++ b/scripts/processDiagnosticMessages.ts @@ -24,7 +24,7 @@ function main(): void { const inputFilePath = sys.args[0].replace(/\\/g, "/"); const inputStr = sys.readFile(inputFilePath)!; - const diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr); + const diagnosticMessagesJson = JSON.parse(inputStr) as { [key: string]: DiagnosticDetails }; const diagnosticMessages: InputDiagnosticMessageTable = ts.createMapFromTemplate(diagnosticMessagesJson); diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 7dd4ed1a39a..74f5b459b22 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1911,12 +1911,12 @@ namespace ts { } } - function errorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { + function errorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string) { const span = getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError: boolean, node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { + function errorOrSuggestionOnFirstToken(isError: boolean, node: Node, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string) { const span = getSpanOfTokenAtPosition(file, node.pos); const diag = createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); if (isError) { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e57cb810333..ec52975e786 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -788,7 +788,7 @@ namespace ts { } const jsxPragma = file.pragmas.get("jsx"); if (jsxPragma) { - const chosenpragma: any = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 + const chosenpragma = isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; @@ -17348,8 +17348,8 @@ namespace ts { } function levenshteinWithMax(s1: string, s2: string, max: number): number | undefined { - let previous = new Array(s2.length + 1); - let current = new Array(s2.length + 1); + let previous = new Array(s2.length + 1); + let current = new Array(s2.length + 1); /** Represents any value > max. We don't care about the particular value. */ const big = max + 1; @@ -18378,7 +18378,7 @@ namespace ts { for (let i = isTaggedTemplate ? 1 : 0; i < args!.length; i++) { if (isContextSensitive(args![i])) { if (!excludeArgument) { - excludeArgument = new Array(args!.length); + excludeArgument = new Array(args!.length); } excludeArgument[i] = true; excludeCount++; @@ -28298,7 +28298,7 @@ namespace ts { return sourceFile.parseDiagnostics.length > 0; } - function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { + function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): boolean { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -28308,7 +28308,7 @@ namespace ts { return false; } - function grammarErrorAtPos(nodeForSourceFile: Node, start: number, length: number, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { + function grammarErrorAtPos(nodeForSourceFile: Node, start: number, length: number, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): boolean { const sourceFile = getSourceFileOfNode(nodeForSourceFile); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); @@ -28317,7 +28317,7 @@ namespace ts { return false; } - function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { + function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): boolean { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(createDiagnosticForNode(node, message, arg0, arg1, arg2)); @@ -28472,7 +28472,7 @@ namespace ts { return false; } - function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { + function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): boolean { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index fdc8e26d9d0..5aa03e81f29 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -977,7 +977,7 @@ namespace ts { configFileText = host.readFile(configFileName); } catch (e) { - const error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + const error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message as string); host.onUnRecoverableConfigFileDiagnostic(error); return undefined; } @@ -1029,7 +1029,7 @@ namespace ts { text = readFile(fileName); } catch (e) { - return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message as string); } return text === undefined ? createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } @@ -1188,7 +1188,7 @@ namespace ts { if (extraKeyDiagnosticMessage && !option) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } - const value = convertPropertyValueToJson(element.initializer, option); + const value = convertPropertyValueToJson(element.initializer, option) as CompilerOptionsValue; if (typeof keyText !== "undefined") { if (returnValue) { result[keyText] = value; @@ -1224,7 +1224,7 @@ namespace ts { elements: NodeArray, elementOption: CommandLineOption | undefined ): any[] | void { - return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption)); + return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption)) as any[] | void; } function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption | undefined): any { @@ -1510,7 +1510,7 @@ namespace ts { * file to. e.g. outDir */ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine { - return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + return parseJsonConfigFileContentWorker(json as MapLike, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); } /** @@ -1552,7 +1552,7 @@ namespace ts { * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContentWorker( - json: any, + json: MapLike | undefined, sourceFile: TsConfigSourceFile | undefined, host: ParseConfigHost, basePath: string, @@ -1616,8 +1616,8 @@ namespace ts { } } else if (raw.compilerOptions) { - const outDir = raw.compilerOptions.outDir; - const declarationDir = raw.compilerOptions.declarationDir; + const outDir = raw.compilerOptions.outDir as string; + const declarationDir = raw.compilerOptions.declarationDir as string; if (outDir || declarationDir) { excludeSpecs = [outDir, declarationDir].filter(d => !!d); @@ -1636,16 +1636,16 @@ namespace ts { if (hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (isArray(raw.references)) { const references: ProjectReference[] = []; - for (const ref of raw.references) { + for (const ref of raw.references as any[]) { if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { references.push({ - path: getNormalizedAbsolutePath(ref.path, basePath), - originalPath: ref.path, - prepend: ref.prepend, - circular: ref.circular + path: getNormalizedAbsolutePath((ref as ProjectReference).path, basePath), + originalPath: (ref as ProjectReference).path, + prepend: (ref as ProjectReference).prepend, + circular: (ref as ProjectReference).circular }); } } @@ -1681,7 +1681,7 @@ namespace ts { } interface ParsedTsconfig { - raw: any; + raw: MapLike; options?: CompilerOptions; typeAcquisition?: TypeAcquisition; /** @@ -1699,7 +1699,7 @@ namespace ts { * It does *not* resolve the included files. */ function parseConfig( - json: any, + json: MapLike | undefined, sourceFile: TsConfigSourceFile | undefined, host: ParseConfigHost, basePath: string, @@ -1712,7 +1712,7 @@ namespace ts { if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); - return { raw: json || convertToObject(sourceFile!, errors) }; + return { raw: json as MapLike || convertToObject(sourceFile!, errors) }; } const ownConfig = json ? @@ -1747,7 +1747,7 @@ namespace ts { } function parseOwnConfigOfJson( - json: any, + json: MapLike, host: ParseConfigHost, basePath: string, configFileName: string | undefined, @@ -1770,7 +1770,7 @@ namespace ts { } else { const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends as string, host, newBase, errors, createCompilerDiagnostic); } } return { raw: json, options, typeAcquisition, extendedConfigPath }; @@ -1824,7 +1824,7 @@ namespace ts { } } }; - const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator) as MapLike; if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -1896,7 +1896,7 @@ namespace ts { const updatePath = (path: string) => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path); const mapPropertiesInRawIfNotUndefined = (propertyName: string) => { if (raw[propertyName]) { - raw[propertyName] = map(raw[propertyName], updatePath); + raw[propertyName] = map(raw[propertyName] as ReadonlyArray, updatePath); } }; @@ -1909,7 +1909,7 @@ namespace ts { return extendedConfig; } - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Push): boolean { + function convertCompileOnSaveOptionFromJson(jsonOption: MapLike, basePath: string, errors: Push): boolean { if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { return false; } @@ -1955,7 +1955,7 @@ namespace ts { basePath: string, errors: Push, configFileName?: string): TypeAcquisition { const options = getDefaultTypeAcquisition(configFileName); - const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions as TypeAcquisition); convertOptionsFromJson(typeAcquisitionDeclarations, typeAcquisition, basePath, options, Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -1985,7 +1985,7 @@ namespace ts { if (isCompilerOptionsValue(opt, value)) { const optType = opt.type; if (optType === "list" && isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); + return convertJsonOptionOfListType(opt, value, basePath, errors) as CompilerOptionsValue; } else if (!isString(optType)) { return convertJsonOptionOfCustomType(opt, value, errors); @@ -2002,24 +2002,24 @@ 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 as any[], v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v); } - return value; + return value as CompilerOptionsValue; } else if (!isString(option.type)) { - return option.type.get(isString(value) ? value.toLowerCase() : value); + return option.type.get(isString(value) ? value.toLowerCase() : "" + value); } return normalizeNonListOptionValue(option, basePath, value); } function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (option.isFilePath) { - value = normalizePath(combinePaths(basePath, value)); + value = normalizePath(combinePaths(basePath, value as string)); if (value === "") { value = "."; } } - return value; + return value as CompilerOptionsValue; } function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Push) { @@ -2034,7 +2034,7 @@ namespace ts { } } - function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray, basePath: string, errors: Push): any[] { + function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray, basePath: string, errors: Push) { return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v); } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 41d66686723..4100131e2bc 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -36,7 +36,7 @@ namespace ts { map.__ = undefined; delete map.__; - return map; + return map as MapLike; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1232,7 +1232,7 @@ namespace ts { * @param key A property key. */ export function hasProperty(map: MapLike, key: string): boolean { - return hasOwnProperty.call(map, key); + return hasOwnProperty.call(map, key) as boolean; } /** @@ -1397,8 +1397,8 @@ namespace ts { export function arrayToSet(array: ReadonlyArray): Map; export function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => string | undefined): Map; export function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => __String | undefined): UnderscoreEscapedMap; - export function arrayToSet(array: ReadonlyArray, makeKey?: (value: any) => string | __String | undefined): Map | UnderscoreEscapedMap { - return arrayToMap(array, makeKey || (s => s), () => true); + export function arrayToSet(array: ReadonlyArray, makeKey?: (value: any) => string | undefined): Map | UnderscoreEscapedMap { + return arrayToMap(array, makeKey || (s => s as string), () => true); } export function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string): MultiMap; @@ -1425,30 +1425,30 @@ namespace ts { } export function clone(object: T): T { - const result: any = {}; + const result = {} as any; for (const id in object) { if (hasOwnProperty.call(object, id)) { - result[id] = (object)[id]; + result[id] = object[id]; } } - return result; + return result as T; } export function extend(first: T1, second: T2): T1 & T2 { - const result: T1 & T2 = {}; + const result = {} as any; for (const id in second) { if (hasOwnProperty.call(second, id)) { - (result as any)[id] = (second as any)[id]; + result[id] = second[id]; } } for (const id in first) { if (hasOwnProperty.call(first, id)) { - (result as any)[id] = (first as any)[id]; + result[id] = first[id]; } } - return result; + return result as T1 & T2; } export interface MultiMap extends Map { @@ -1568,7 +1568,7 @@ namespace ts { if (e) { const args: ((t: T) => (u: U) => U)[] = []; for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; + args[i] = arguments[i] as (t: T) => (u: U) => U; } return t => compose(...map(args, f => f(t))); @@ -1601,7 +1601,7 @@ namespace ts { if (e) { const args: ((t: T) => T)[] = []; for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; + args[i] = arguments[i] as (t: T) => T; } return t => reduceLeft(args, (u, f) => f(u), t); @@ -1646,7 +1646,7 @@ namespace ts { let text = getLocaleSpecificMessage(message); if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); + text = formatStringFromArgs(text, arguments as ArrayLike, 4); } return { @@ -1666,7 +1666,7 @@ namespace ts { let text = getLocaleSpecificMessage(message); if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + text = formatStringFromArgs(text, arguments as ArrayLike, 2); } return text; @@ -1677,7 +1677,7 @@ namespace ts { let text = getLocaleSpecificMessage(message); if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); + text = formatStringFromArgs(text, arguments as ArrayLike, 1); } return { @@ -1709,7 +1709,7 @@ namespace ts { let text = getLocaleSpecificMessage(message); if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + text = formatStringFromArgs(text, arguments as ArrayLike, 2); } return { @@ -3130,14 +3130,14 @@ namespace ts { } export let objectAllocator: ObjectAllocator = { - getNodeConstructor: () => Node, - getTokenConstructor: () => Node, - getIdentifierConstructor: () => Node, - getSourceFileConstructor: () => Node, - getSymbolConstructor: () => Symbol, - getTypeConstructor: () => Type, - getSignatureConstructor: () => Signature, - getSourceMapSourceConstructor: () => SourceMapSource, + getNodeConstructor: (() => Node) as never, + getTokenConstructor: (() => Node) as never, + getIdentifierConstructor: (() => Node) as never, + getSourceFileConstructor: (() => Node) as never, + getSymbolConstructor: (() => Symbol) as never, + getTypeConstructor: (() => Type) as never, + getSignatureConstructor: (() => Signature) as never, + getSourceMapSourceConstructor: (() => SourceMapSource) as never, }; export const enum AssertionLevel { @@ -3228,14 +3228,14 @@ namespace ts { return (func).name; } else { - const text = Function.prototype.toString.call(func); + const text = Function.prototype.toString.call(func) as string; const match = /^function\s+([\w\$]+)\s*\(/.exec(text); return match ? match[1] : ""; } } export function showSymbol(symbol: Symbol): string { - const symbolFlags = (ts as any).SymbolFlags; + const symbolFlags = (ts as any).SymbolFlags as { [x: number]: string }; return `{ flags: ${symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags}; declarations: ${map(symbol.declarations, showSyntaxKind)} }`; } @@ -3251,7 +3251,7 @@ namespace ts { } export function showSyntaxKind(node: Node): string { - const syntaxKind = (ts as any).SyntaxKind; + const syntaxKind = (ts as any).SyntaxKind as { [x: number]: string }; return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); } } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 6085cc550c4..f6cc30ba95f 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -1309,11 +1309,11 @@ namespace ts { whenFalse: Expression): ConditionalExpression; export function updateConditional(node: ConditionalExpression, condition: Expression, ...args: any[]) { if (args.length === 2) { - const [whenTrue, whenFalse] = args; + const [whenTrue, whenFalse] = args as [Expression, Expression]; return updateConditional(node, condition, node.questionToken, whenTrue, node.colonToken, whenFalse); } Debug.assert(args.length === 4); - const [questionToken, whenTrue, colonToken, whenFalse] = args; + const [questionToken, whenTrue, colonToken, whenFalse] = args as [Token, Expression, Token, Expression]; return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index beaeb7dd056..e94e5b012d1 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -2,7 +2,7 @@ namespace ts { /* @internal */ export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; export function trace(host: ModuleResolutionHost): void { - host.trace!(formatMessage.apply(undefined, arguments)); + host.trace!(formatMessage.apply(undefined, arguments) as string); } /* @internal */ @@ -124,7 +124,7 @@ namespace ts { if (result.error) { return {}; } - return result.config; + return result.config as object; } catch (e) { // gracefully handle if readFile fails or returns not JSON diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 03a89343045..f452e364080 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1037,11 +1037,11 @@ namespace ts { return inContext(NodeFlags.AwaitContext); } - function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { + function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: string): void { parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } - function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): void { + function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: string): void { // Don't report another error if it would just be at the same position as the last error. const lastError = lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { @@ -1053,11 +1053,11 @@ namespace ts { parseErrorBeforeNextFinishedNode = true; } - function parseErrorAt(start: number, end: number, message: DiagnosticMessage, arg0?: any): void { + function parseErrorAt(start: number, end: number, message: DiagnosticMessage, arg0?: string): void { parseErrorAtPosition(start, end - start, message, arg0); } - function parseErrorAtRange(range: TextRange, message: DiagnosticMessage, arg0?: any): void { + function parseErrorAtRange(range: TextRange, message: DiagnosticMessage, arg0?: string): void { parseErrorAt(range.pos, range.end, message, arg0); } @@ -1204,7 +1204,7 @@ namespace ts { return false; } - function parseOptionalToken(t: TKind): Token; + function parseOptionalToken(t: TKind): Token | undefined; function parseOptionalToken(t: SyntaxKind): Node | undefined { if (token() === t) { return parseTokenNode(); @@ -1212,8 +1212,8 @@ namespace ts { return undefined; } - function parseExpectedToken(t: TKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): Token; - function parseExpectedToken(t: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): Node { + function parseExpectedToken(t: TKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Token; + function parseExpectedToken(t: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Node { return parseOptionalToken(t) || createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics._0_expected, arg0 || tokenToString(t)); } @@ -1293,7 +1293,7 @@ namespace ts { return node; } - function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): T { + function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: string): T { if (reportAtCurrentPosition) { parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); } @@ -3241,7 +3241,7 @@ namespace ts { } let expr = parseAssignmentExpressionOrHigher(); - let operatorToken: BinaryOperatorToken; + let operatorToken; while ((operatorToken = parseOptionalToken(SyntaxKind.CommaToken))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } @@ -5571,7 +5571,7 @@ namespace ts { return finishNode(node); } - function parseMethodDeclaration(node: MethodDeclaration, asteriskToken: AsteriskToken, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { + function parseMethodDeclaration(node: MethodDeclaration, asteriskToken: AsteriskToken | undefined, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { node.kind = SyntaxKind.MethodDeclaration; node.asteriskToken = asteriskToken; const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None; @@ -7723,7 +7723,7 @@ namespace ts { if (context.pragmas.has(pragma!.name)) { // TODO: GH#18217 const currentValue = context.pragmas.get(pragma!.name); if (currentValue instanceof Array) { - currentValue.push(pragma!.args); + currentValue.push(pragma!.args!); } else { context.pragmas.set(pragma!.name, [currentValue, pragma!.args]); diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 4dfb9039ccf..630db828f75 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -85,7 +85,7 @@ namespace ts { } catch (e) { if (onError) { - onError(e.message); + onError(e.message as string); } text = ""; } @@ -135,7 +135,7 @@ namespace ts { sys.writeFile(fileName, data, writeByteOrderMark); - const mtimeAfter = sys.getModifiedTime!(fileName); // TODO: GH#18217 + const mtimeAfter = sys.getModifiedTime!(fileName)!; // TODO: GH#18217 outputFingerprints.set(fileName, { hash, @@ -161,7 +161,7 @@ namespace ts { } catch (e) { if (onError) { - onError(e.message); + onError(e.message as string); } } } @@ -812,7 +812,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 = {} as ResolvedModuleFull; for (let i = 0; i < moduleNames.length; i++) { const moduleName = moduleNames[i]; @@ -823,7 +823,7 @@ namespace ts { if (isTraceEnabled(options, host)) { trace(host, Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); } - (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; (reusedNames || (reusedNames = [])).push(moduleName); continue; } @@ -844,7 +844,7 @@ namespace ts { } if (resolvesToAmbientModuleInNonModifiedFile) { - (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } else { // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. @@ -1887,7 +1887,7 @@ namespace ts { } function createRedirectSourceFile(redirectTarget: SourceFile, unredirected: SourceFile, fileName: string, path: Path): SourceFile { - const redirect: SourceFile = Object.create(redirectTarget); + const redirect = Object.create(redirectTarget) as SourceFile; redirect.fileName = fileName; redirect.path = path; redirect.redirectInfo = { redirectTarget, unredirected }; @@ -2093,8 +2093,8 @@ namespace ts { fileProcessingDiagnostics.add(createDiagnostic(refFile!, refPos!, refEnd!, // TODO: GH#18217 Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, - resolvedTypeReferenceDirective.resolvedFileName, - previousResolution.resolvedFileName + resolvedTypeReferenceDirective.resolvedFileName!, // TODO: GH#18217 + previousResolution.resolvedFileName! // TODO: GH#18217 )); } } @@ -2116,7 +2116,7 @@ namespace ts { } } - function createDiagnostic(refFile: SourceFile, refPos: number, refEnd: number, message: DiagnosticMessage, ...args: any[]): Diagnostic { + function createDiagnostic(refFile: SourceFile, refPos: number, refEnd: number, message: DiagnosticMessage, ...args: string[]): Diagnostic { if (refFile === undefined || refPos === undefined || refEnd === undefined) { return createCompilerDiagnostic(message, ...args); } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 41b65c67864..8c62493ccc6 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -299,7 +299,7 @@ namespace ts { /* @internal */ export function computeLineStarts(text: string): number[] { - const result: number[] = new Array(); + const result = new Array(); let pos = 0; let lineStart = 0; while (pos < text.length) { diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 91e5a48dc05..c5966edeede 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -1,6 +1,3 @@ -declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; -declare function clearTimeout(handle: any): void; - namespace ts { /** * Set a high stack trace limit to provide more information in case of an error. @@ -300,7 +297,7 @@ namespace ts { } function scheduleNextPoll(pollingInterval: PollingInterval) { - pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout!(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); + pollingIntervalQueue(pollingInterval).pollScheduled = !!host.setTimeout!(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } function getModifiedTime(fileName: string) { @@ -447,7 +444,7 @@ namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - getModifiedTime?(path: string): Date; + getModifiedTime?(path: string): Date | undefined; /** * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) */ @@ -476,16 +473,11 @@ namespace ts { referenceCount: number; } - declare const require: any; - declare const process: any; - declare const global: any; - declare const __filename: string; - export function getNodeMajorVersion(): number | undefined { if (typeof process === "undefined") { return undefined; } - const version: string = process.version; + const version = process.version as string; if (!version) { return undefined; } @@ -526,22 +518,19 @@ namespace ts { const byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem(): System { - const _fs = require("fs"); - const _path = require("path"); - const _os = require("os"); + const _fs = require("fs") as typeof import("fs"); + const _path = require("path") as typeof import ("path"); + const _os = require("os") as typeof import("os"); // crypto can be absent on reduced node installations let _crypto: typeof import("crypto") | undefined; try { - _crypto = require("crypto"); + _crypto = require("crypto") as typeof import("crypto"); } catch { _crypto = undefined; } - const Buffer: { - new (input: string, encoding?: string): any; - from?(input: string, encoding?: string): any; - } = require("buffer").Buffer; + const Buffer = (require("buffer") as typeof import("buffer")).Buffer; const nodeVersion = getNodeMajorVersion(); const isNode4OrLater = nodeVersion! >= 4; @@ -566,7 +555,7 @@ namespace ts { process.stdout.write(s); }, writeOutputIsTTY() { - return process.stdout.isTTY; + return !!process.stdout.isTTY; }, readFile, writeFile, @@ -629,8 +618,8 @@ namespace ts { process.stdout.write("\x1Bc"); }, setBlocking: () => { - if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) { - process.stdout._handle.setBlocking(true); + if (process.stdout && (process.stdout as any)._handle && (process.stdout as any)._handle.setBlocking) { + (process.stdout as any)._handle.setBlocking(true); } }, base64decode: Buffer.from ? input => { @@ -832,7 +821,7 @@ namespace ts { } function fsWatch(fileOrDirectory: string, entryKind: FileSystemEntryKind.File | FileSystemEntryKind.Directory, callback: FsWatchCallback, recursive: boolean, fallbackPollingWatchFile: HostWatchFile, pollingInterval?: number): FileWatcher { - let options: any; + let options: { persistent?: boolean, recursive?: boolean }; /** Watcher for the file system entry depending on whether it is missing or present */ let watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ? watchMissingFileSystemEntry() : @@ -999,7 +988,7 @@ namespace ts { } const name = combinePaths(path, entry); - let stat: any; + let stat; try { stat = _fs.statSync(name); } @@ -1142,7 +1131,7 @@ namespace ts { if (typeof ChakraHost !== "undefined") { sys = getChakraSystem(); } - else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + else if (typeof process !== "undefined" && process.nextTick && !(process as any).browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify sys = getNodeSystem(); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index a92448e5290..138b9d36b05 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -573,7 +573,7 @@ namespace ts { while (length(lateMarkedStatements)) { const i = lateMarkedStatements!.shift()!; if (!isLateVisibilityPaintedStatement(i)) { - return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[(i as any).kind] : (i as any).kind}`); + return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[(i as any).kind as number] : (i as any).kind}`); } const result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); lateStatementReplacementMap.set("" + getOriginalNodeId(i), result); @@ -802,7 +802,7 @@ namespace ts { input.isTypeOf )); } - default: Debug.assertNever(input, `Attempted to process unhandled node kind: ${(ts as any).SyntaxKind[(input as any).kind]}`); + default: Debug.assertNever(input, `Attempted to process unhandled node kind: ${(ts as any).SyntaxKind[(input as any).kind as number]}`); } } @@ -1080,7 +1080,7 @@ namespace ts { } } // Anything left unhandled is an error, so this should be unreachable - return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${(ts as any).SyntaxKind[(input as any).kind]}`); + return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${(ts as any).SyntaxKind[(input as any).kind as number]}`); function cleanup(node: T | undefined): T | undefined { if (isEnclosingDeclaration(input)) { diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 0865861414e..c71cf45c8a2 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -151,7 +151,7 @@ namespace ts { return getTypeAliasDeclarationVisibilityError; } else { - return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${(ts as any).SyntaxKind[(node as any).kind]}`); + return Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${(ts as any).SyntaxKind[(node as any).kind as number]}`); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index a118e349ac3..6ce71681956 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -123,7 +123,7 @@ namespace ts { catchClauseNames.forEach((_, escapedName) => { if (enclosingFunctionParameterNames.has(escapedName)) { if (!catchClauseUnshadowedNames) { - catchClauseUnshadowedNames = cloneMap(enclosingFunctionParameterNames); + catchClauseUnshadowedNames = cloneMap(enclosingFunctionParameterNames) as UnderscoreEscapedMap; } catchClauseUnshadowedNames.delete(escapedName); } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 5ae6bcb8b32..ddbec247061 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1337,7 +1337,7 @@ namespace ts { const parameter = parameters[i]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array>(parameters.length); } decorators[i] = parameter.decorators; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e04caa1ef9b..8619c881fdf 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3574,13 +3574,8 @@ namespace ts { /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. - * The shape of this brand is rather unique compared to others we've used. - * Instead of just an intersection of a string and an object, it is that union-ed - * with an intersection of void and an object. This makes it wholly incompatible - * with a normal string (which is good, it cannot be misused on assignment or on usage), - * while still being comparable with a normal string via === (also good) and castable from a string. */ - export type __String = (string & { __escapedIdentifier: void }) | (void & { __escapedIdentifier: void }) | InternalSymbolName; + export type __String = string & { __escapedIdentifier: void } | InternalSymbolName; /** ReadonlyMap where keys are `__String`s. */ export interface ReadonlyUnderscoreEscapedMap { @@ -5243,8 +5238,8 @@ namespace ts { /*@internal*/ onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number; /*@internal*/ onEmitSourceMapOfPosition?: (pos: number) => void; /*@internal*/ onSetSourceFile?: (node: SourceFile) => void; - /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray | undefined) => void; - /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray | undefined) => void; + /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray | undefined) => void; + /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray | undefined) => void; /*@internal*/ onBeforeEmitToken?: (node: Node) => void; /*@internal*/ onAfterEmitToken?: (node: Node) => void; } @@ -5535,7 +5530,7 @@ namespace ts { /* @internal */ export interface PragmaMap extends Map { set(key: TKey, value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]): this; - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; + get(key: TKey): PragmaPsuedoMap[TKey] | NonNullable[]; forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index a3da44c5b1f..4b8fb9bbd8a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -609,7 +609,7 @@ namespace ts { case SyntaxKind.ComputedPropertyName: return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined!; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - Debug.assertNever(name); + return Debug.assertNever(name); } } @@ -4116,7 +4116,7 @@ namespace ts { /** Add a value to a set, and return true if it wasn't already present. */ export function addToSeen(seen: Map, key: string | number): boolean; export function addToSeen(seen: Map, key: string | number, value: T): boolean; - export function addToSeen(seen: Map, key: string | number, value: T = true as any): boolean { + export function addToSeen(seen: Map, key: string | number, value: T = true as never): boolean { key = String(key); if (seen.has(key)) { return false; @@ -4500,7 +4500,7 @@ namespace ts { } try { // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) - ts.localizedDiagnosticMessages = JSON.parse(fileContents!); + ts.localizedDiagnosticMessages = JSON.parse(fileContents!) as MapLike; } catch { if (errors) { diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 5f35a3027dc..569057e5885 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -959,7 +959,7 @@ namespace ts { return initial; } - const reduceNodes: (nodes: NodeArray | undefined, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft; + const reduceNodes: (nodes: NodeArray | undefined, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft as never; const cbNodes = cbNodeArray || cbNode; const kind = node.kind; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index e869dfc966c..7b318f949fe 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -19,7 +19,7 @@ namespace ts { return diagnostic => system.write(formatDiagnostic(diagnostic, host)); } - const diagnostics: Diagnostic[] = new Array(1); + const diagnostics = new Array(1); return diagnostic => { diagnostics[0] = diagnostic; system.write(formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); @@ -88,7 +88,7 @@ namespace ts { /** Parses config file using System interface */ export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, system: System, reportDiagnostic: DiagnosticReporter) { - const host: ParseConfigFileHost = system; + const host: ParseConfigFileHost = system as never; host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic); const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217 @@ -724,7 +724,7 @@ namespace ts { } catch (e) { if (onError) { - onError(e.message); + onError(e.message as string); } } @@ -963,7 +963,7 @@ namespace ts { } catch (e) { if (onError) { - onError(e.message); + onError(e.message as string); } } }