Closed
Description
Suggestion
π Search Terms
- Control flow
- Aliased conditions
- Type narrowing
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
TypeScript 4.4 added "Control Flow Analysis of Aliased Conditions and Discriminants" which is a great feature, but unfortunately it seems unable to narrow the types on object properties which limits the benefit.
π Motivating Example
Take null checks for instance, the following code results in a compiler warning in the AliasedControlFlow
-method. The RegularControlFlow
method works fine even though it does the exakt same comparison.
interface ITest {
prop?: string;
}
function AliasedControlFlow(test: ITest) {
const hasProp = test.prop != null;
// Object is possibly 'undefined'.
return hasProp ? test.prop.big() : "";
}
function RegularControlFlow(test: ITest) {
return test.prop != null ? test.prop.big() : "";
}
π» Use Cases
This would really help when converting code that is currently not using strictNullChecks
as null checks may already be aliased in existing code.