Skip to content

Null check does not cause control flow analysis to narrow nullable interface property #46757

Closed
@btoo

Description

@btoo

Bug Report

🔎 Search Terms

interface optional properties props nullable nonnullable non-nullable control flow analysis type narrow

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed all the FAQ entries

⏯ Playground Link

Playground link with relevant code

💻 Code

interface NullableProps {
  nullableProp?: string
}

type RequiredProps = Required<NullableProps>

declare function withRequiredProps(requiredProps: RequiredProps): any;

function withNullableProps(props: NullableProps) {
  if (!props.nullableProp) return;

  /** this is correct */
  type ProperlyTypeNarrowedToBeNonNullable = typeof props.nullableProp

  /** but this is incorrect */
  type IncorrectlyStillNullableProps = typeof props;

  /**
   * Argument of type 'NullableProps' is not assignable to parameter of type 'Required<NullableProps>'.
   *   Types of property 'someNullableProp' are incompatible.
   *     Type 'string | undefined' is not assignable to type 'string'.
   *       Type 'undefined' is not assignable to type 'string'.(2345)
   */
  withRequiredProps(props)
}

🙁 Actual behavior

the line

if (!props.nullableProp) return;

does not narrow props to be { nullableProp: NonNullable }

🙂 Expected behavior

the line

if (!props.nullableProp) return;

should narrow props to be { nullableProp: NonNullable }

Activity

jcalz

jcalz commented on Nov 10, 2021

@jcalz
Contributor

duplicate of #31755 ?

MartinJohns

MartinJohns commented on Nov 10, 2021

@MartinJohns
Contributor

Duplicate of #42384 (which refers to #31755).

btoo

btoo commented on Nov 10, 2021

@btoo
Author

glad i'm not the only one. let's hope #42384 (comment) leads somewhere!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jcalz@MartinJohns@btoo

        Issue actions

          Null check does not cause control flow analysis to narrow nullable interface property · Issue #46757 · microsoft/TypeScript