Fix --strictAny issues in core compiler

This commit is contained in:
Anders Hejlsberg
2018-05-29 11:30:04 -07:00
parent c643bb5f2b
commit 1039ca68f5
19 changed files with 126 additions and 142 deletions
+1 -1
View File
@@ -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);
+2 -2
View File
@@ -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) {
+8 -8
View File
@@ -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<number>(s2.length + 1);
let current = new Array<number>(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<boolean>(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);
+29 -29
View File
@@ -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<Expression>,
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<FileExtensionInfo>): ParsedCommandLine {
return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
return parseJsonConfigFileContentWorker(json as MapLike<any>, /*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<any> | 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<any>;
options?: CompilerOptions;
typeAcquisition?: TypeAcquisition;
/**
@@ -1699,7 +1699,7 @@ namespace ts {
* It does *not* resolve the included files.
*/
function parseConfig(
json: any,
json: MapLike<any> | 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<any> || convertToObject(sourceFile!, errors) };
}
const ownConfig = json ?
@@ -1747,7 +1747,7 @@ namespace ts {
}
function parseOwnConfigOfJson(
json: any,
json: MapLike<any>,
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<any>;
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<string>, updatePath);
}
};
@@ -1909,7 +1909,7 @@ namespace ts {
return extendedConfig;
}
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Push<Diagnostic>): boolean {
function convertCompileOnSaveOptionFromJson(jsonOption: MapLike<any>, basePath: string, errors: Push<Diagnostic>): boolean {
if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
return false;
}
@@ -1955,7 +1955,7 @@ namespace ts {
basePath: string, errors: Push<Diagnostic>, 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(<CommandLineOptionOfListType>opt, value, basePath, errors);
return convertJsonOptionOfListType(<CommandLineOptionOfListType>opt, value, basePath, errors) as CompilerOptionsValue;
}
else if (!isString(optType)) {
return convertJsonOptionOfCustomType(<CommandLineOptionOfCustomType>opt, <string>value, errors);
@@ -2002,24 +2002,24 @@ namespace ts {
if (option.type === "list") {
const listOption = <CommandLineOptionOfListType>option;
if (listOption.element.isFilePath || !isString(listOption.element.type)) {
return <CompilerOptionsValue>filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v);
return <CompilerOptionsValue>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<Diagnostic>) {
@@ -2034,7 +2034,7 @@ namespace ts {
}
}
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray<any>, basePath: string, errors: Push<Diagnostic>): any[] {
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray<any>, basePath: string, errors: Push<Diagnostic>) {
return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v);
}
+28 -28
View File
@@ -36,7 +36,7 @@ namespace ts {
map.__ = undefined;
delete map.__;
return map;
return map as MapLike<T>;
}
/** 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<any>, 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<string>): Map<true>;
export function arrayToSet<T>(array: ReadonlyArray<T>, makeKey: (value: T) => string | undefined): Map<true>;
export function arrayToSet<T>(array: ReadonlyArray<T>, makeKey: (value: T) => __String | undefined): UnderscoreEscapedMap<true>;
export function arrayToSet(array: ReadonlyArray<any>, makeKey?: (value: any) => string | __String | undefined): Map<true> | UnderscoreEscapedMap<true> {
return arrayToMap<any, true>(array, makeKey || (s => s), () => true);
export function arrayToSet(array: ReadonlyArray<any>, makeKey?: (value: any) => string | undefined): Map<true> | UnderscoreEscapedMap<true> {
return arrayToMap<any, true>(array, makeKey || (s => s as string), () => true);
}
export function arrayToMultiMap<T>(values: ReadonlyArray<T>, makeKey: (value: T) => string): MultiMap<T>;
@@ -1425,30 +1425,30 @@ namespace ts {
}
export function clone<T>(object: T): T {
const result: any = {};
const result = {} as any;
for (const id in object) {
if (hasOwnProperty.call(object, id)) {
result[id] = (<any>object)[id];
result[id] = object[id];
}
}
return result;
return result as T;
}
export function extend<T1, T2>(first: T1, second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
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<T> extends Map<T[]> {
@@ -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<string>, 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<string>, 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<string>, 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<string>, 2);
}
return {
@@ -3130,14 +3130,14 @@ namespace ts {
}
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: () => <any>Node,
getTokenConstructor: () => <any>Node,
getIdentifierConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature,
getSourceMapSourceConstructor: () => <any>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 (<any>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();
}
}
+2 -2
View File
@@ -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<SyntaxKind.QuestionToken>, Expression, Token<SyntaxKind.ColonToken>, Expression];
return node.condition !== condition
|| node.questionToken !== questionToken
|| node.whenTrue !== whenTrue
+2 -2
View File
@@ -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
+11 -11
View File
@@ -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<TKind extends SyntaxKind>(t: TKind): Token<TKind>;
function parseOptionalToken<TKind extends SyntaxKind>(t: TKind): Token<TKind> | undefined;
function parseOptionalToken(t: SyntaxKind): Node | undefined {
if (token() === t) {
return parseTokenNode();
@@ -1212,8 +1212,8 @@ namespace ts {
return undefined;
}
function parseExpectedToken<TKind extends SyntaxKind>(t: TKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): Token<TKind>;
function parseExpectedToken(t: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): Node {
function parseExpectedToken<TKind extends SyntaxKind>(t: TKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Token<TKind>;
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<T extends Node>(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): T {
function createMissingNode<T extends Node>(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]);
+10 -10
View File
@@ -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 = <any>{};
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<ResolvedModuleFull>(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<ResolvedModuleFull>(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);
}
+1 -1
View File
@@ -299,7 +299,7 @@ namespace ts {
/* @internal */
export function computeLineStarts(text: string): number[] {
const result: number[] = new Array();
const result = new Array<number>();
let pos = 0;
let lineStart = 0;
while (pos < text.length) {
+14 -25
View File
@@ -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<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, 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();
+3 -3
View File
@@ -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<T extends Node>(node: T | undefined): T | undefined {
if (isEnclosingDeclaration(input)) {
@@ -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) {
+1 -1
View File
@@ -123,7 +123,7 @@ namespace ts {
catchClauseNames.forEach((_, escapedName) => {
if (enclosingFunctionParameterNames.has(escapedName)) {
if (!catchClauseUnshadowedNames) {
catchClauseUnshadowedNames = cloneMap(enclosingFunctionParameterNames);
catchClauseUnshadowedNames = cloneMap(enclosingFunctionParameterNames) as UnderscoreEscapedMap<true>;
}
catchClauseUnshadowedNames.delete(escapedName);
}
+1 -1
View File
@@ -1337,7 +1337,7 @@ namespace ts {
const parameter = parameters[i];
if (decorators || parameter.decorators) {
if (!decorators) {
decorators = new Array(parameters.length);
decorators = new Array<ReadonlyArray<Decorator>>(parameters.length);
}
decorators[i] = parameter.decorators;
+4 -9
View File
@@ -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<T> {
@@ -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<any> | undefined) => void;
/*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray<any> | undefined) => void;
/*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray<Node> | undefined) => void;
/*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray<Node> | undefined) => void;
/*@internal*/ onBeforeEmitToken?: (node: Node) => void;
/*@internal*/ onAfterEmitToken?: (node: Node) => void;
}
@@ -5535,7 +5530,7 @@ namespace ts {
/* @internal */
export interface PragmaMap extends Map<PragmaPsuedoMap[keyof PragmaPsuedoMap] | PragmaPsuedoMap[keyof PragmaPsuedoMap][]> {
set<TKey extends keyof PragmaPsuedoMap>(key: TKey, value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]): this;
get<TKey extends keyof PragmaPsuedoMap>(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][];
get<TKey extends keyof PragmaPsuedoMap>(key: TKey): PragmaPsuedoMap[TKey] | NonNullable<PragmaPsuedoMap[TKey]>[];
forEach(action: <TKey extends keyof PragmaPsuedoMap>(value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void;
}
}
+3 -3
View File
@@ -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<true>, key: string | number): boolean;
export function addToSeen<T>(seen: Map<T>, key: string | number, value: T): boolean;
export function addToSeen<T>(seen: Map<T>, key: string | number, value: T = true as any): boolean {
export function addToSeen<T>(seen: Map<T>, 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<string>;
}
catch {
if (errors) {
+1 -1
View File
@@ -959,7 +959,7 @@ namespace ts {
return initial;
}
const reduceNodes: (nodes: NodeArray<Node> | undefined, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray<Node>) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const reduceNodes: (nodes: NodeArray<Node> | undefined, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray<Node>) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft as never;
const cbNodes = cbNodeArray || cbNode;
const kind = node.kind;
+4 -4
View File
@@ -19,7 +19,7 @@ namespace ts {
return diagnostic => system.write(formatDiagnostic(diagnostic, host));
}
const diagnostics: Diagnostic[] = new Array(1);
const diagnostics = new Array<Diagnostic>(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 = <any>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);
}
}
}