From 475e201abff11742ca47d4b595078aad08937202 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 8 Oct 2020 18:06:51 -0700 Subject: [PATCH] Add new 'useUnknownInCatchVariables' flag. --- src/compiler/checker.ts | 2 +- src/compiler/commandLineParser.ts | 8 ++++++++ src/compiler/diagnosticMessages.json | 4 ++++ src/compiler/types.ts | 1 + 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9aefcc9f5d3..c81958ed696 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8603,7 +8603,7 @@ namespace ts { const declaration = symbol.valueDeclaration; if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) { const decl = declaration as VariableDeclaration; - if (!decl.type) return anyType; + if (!decl.type) return compilerOptions.useUnknownInCatchVariables ? unknownType : anyType; const type = getTypeOfNode(decl.type); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type) || type === unknownType ? type : errorType; diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 51cf7923a10..c8e6353da08 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -668,6 +668,14 @@ namespace ts { category: Diagnostics.Additional_Checks, description: Diagnostics.Require_undeclared_properties_from_index_signatures_to_use_element_accesses }, + { + name: "useUnknownInCatchVariables", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: Diagnostics.Additional_Checks, + description: Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + }, // Module Resolution { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4cb607631f5..f97ee06efcb 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -4757,6 +4757,10 @@ "category": "Message", "code": 6800 }, + "Type catch clause variables as 'unknown' instead of 'any'.": { + "category": "Message", + "code": 6801 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 7c9038ed3ba..e56fd42cc97 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5829,6 +5829,7 @@ namespace ts { /* @internal */ suppressOutputPathCheck?: boolean; target?: ScriptTarget; // TODO: GH#18217 frequently asserted as defined traceResolution?: boolean; + useUnknownInCatchVariables?: boolean; resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */