TypeScript: Comparing == null does not work as type guard when explicitNullChecks is disabled
TypeScript Version: 2.6.1
Code
(with “strictNullChecks” disabled)
function foo(value: number | null | undefined): string | null | undefined {
if (value == null) {
return value;
}
return value.toString();
}
Expected behavior: Compile without errors.
Actual behavior: “Type ‘number’ is not assignable to ‘string’” at the “return value” line

Enabling “strictNullChecks” causes the code to compile without error, but I unfortunately cannot enable strictNullChecks in my project due to a 3rd party typescript library that was not designed with structNullChecks.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 16 (7 by maintainers)
@UselessPickles based on your description, what you’re missing is how pre-
strictNullCheckschecking works.With SNC off, there is no distinction about whether a value is null or not. There’s no distinctions, anywhere, about what
nullmeans, whether something has been determined to benullor not, or when something may or may not benull. It’s just completely untracked; type guards checking fornulldo nothing.When
--strictNullChecksis not enabled, every type implicitly includesnullandundefined. Therefore, from a type level perspective, the functionis equivalent to
The only difference is that the former is more self-documenting.