Skip to content

Commit e6d1651

Browse files
committed
Add error for asserting non-nullness of already non-null expressions
1 parent aeeff28 commit e6d1651

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/compiler/checker.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13970,7 +13970,18 @@ namespace ts {
1397013970
}
1397113971

1397213972
function checkNonNullAssertion(node: NonNullExpression) {
13973-
return getNonNullableType(checkExpression(node.expression));
13973+
if(!strictNullChecks) {
13974+
// Actually adding this error results in numerous errors compiling the ts codebase
13975+
// In the interest of keeping this PR small, it's been omitted
13976+
// error(node, Diagnostics.Use_of_non_null_assertion_operator_without_strictNullChecks_enabled);
13977+
return checkExpression(node.expression);
13978+
}
13979+
const expr = checkExpression(node.expression);
13980+
const nonNullable = getNonNullableType(expr);
13981+
if(isTypeIdenticalTo(nonNullable, expr)) {
13982+
error(node, Diagnostics.The_expression_asserted_to_be_non_null_is_already_non_null);
13983+
}
13984+
return nonNullable;
1397413985
}
1397513986

1397613987
function checkMetaProperty(node: MetaProperty) {

src/compiler/diagnosticMessages.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2043,6 +2043,14 @@
20432043
"category": "Error",
20442044
"code": 2704
20452045
},
2046+
"The expression asserted to be non-null is already non-null": {
2047+
"category": "Error",
2048+
"code": 2705
2049+
},
2050+
"Use of non-null assertion operator without strictNullChecks enabled": {
2051+
"category": "Error",
2052+
"code": 2706
2053+
},
20462054

20472055
"Import declaration '{0}' is using private name '{1}'.": {
20482056
"category": "Error",

0 commit comments

Comments
 (0)