Skip to content

Control flow analysis of aliased conditions is not able to narrow object propertiesΒ #46412

Closed
@DavidZidar

Description

@DavidZidar

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions