diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7d0f2cb0bbb95..c75631249a1da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13970,7 +13970,18 @@ namespace ts { } function checkNonNullAssertion(node: NonNullExpression) { - return getNonNullableType(checkExpression(node.expression)); + if(!strictNullChecks) { + // Actually adding this error results in numerous errors compiling the ts codebase + // In the interest of keeping this PR small, it's been omitted + // error(node, Diagnostics.Use_of_non_null_assertion_operator_without_strictNullChecks_enabled); + return checkExpression(node.expression); + } + const expr = checkExpression(node.expression); + const nonNullable = getNonNullableType(expr); + if(isTypeIdenticalTo(nonNullable, expr)) { + error(node, Diagnostics.The_expression_asserted_to_be_non_null_is_already_non_null); + } + return nonNullable; } function checkMetaProperty(node: MetaProperty) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 43a9cce4de6e6..25a6fbe467493 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2043,6 +2043,14 @@ "category": "Error", "code": 2704 }, + "The expression asserted to be non-null is already non-null": { + "category": "Error", + "code": 2705 + }, + "Use of non-null assertion operator without strictNullChecks enabled": { + "category": "Error", + "code": 2706 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error",