It appears that TypeScript has a limitation when the "--strictNullChecks" compiler option is disabled, as there are no existing GitHub issues addressing this. Enabling "--strictNullChecks" is highly recommended to avoid potential issues with code behavior and coverage.
An analysis suggests that certain interactions occur unfavorably:
With "--strictNullChecks" off, "null" and "undefined" can be assigned to almost any type but not to the "never" type specifically. This distinction creates challenges in working with these values:
In situations where a union type includes "null" or "undefined," TypeScript treats them similarly to the "never" type:
Assigning values to object keys of a union type requires compatibility with the intersection of value types for each key, enhancing type safety but potentially causing errors:
Combining these factors leads to scenarios like the one described below:
Given the assignment "data[key] = undefined;
" within a loop, the behavior with "--strictNullChecks" on results in safe type evaluation. Conversely, turning it off collapses types in a way that triggers an error due to incompatible assignments.
If you prefer keeping "--strictNullChecks" off and don't wish to report this as an issue on GitHub, utilizing type assertions can serve as a workaround:
for (const key of ['a', 'b'] as const) {
data[key] = undefined as never; // allows successful assignment
}
This method may compromise some level of type safety, but it offers a practical approach to managing such situations without major alterations.
To further address this concern without enabling "--strictNullChecks" or submitting a GitHub issue, incorporating type assertions remains a reliable solution. Although this approach involves risks, it provides a viable means of handling conflicts related to nullability in TypeScript code.
(Alternatively, consider activating "--strictNullChecks" alongside other recommended features in the TypeScript compiler suite to benefit from enhanced robustness and functionality. The "--strict" options collectively enhance type security and resolution of common coding issues, offering valuable support for maintaining quality codebases.)
Access Playground Link