Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
btoo opened this issue Nov 10, 2021 · 3 comments

Comments

@btoo
Copy link

btoo commented Nov 10, 2021

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 }

@jcalz
Copy link
Contributor

jcalz commented Nov 10, 2021

duplicate of #31755 ?

@MartinJohns
Copy link
Contributor

MartinJohns commented Nov 10, 2021

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

@btoo
Copy link
Author

btoo commented Nov 10, 2021

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

@btoo btoo closed this as completed Nov 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants