Skip to content
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

Implicit type guard by other variables are not always working #46915

Closed
Egor-Koldasov opened this issue Nov 24, 2021 · 1 comment
Closed

Implicit type guard by other variables are not always working #46915

Egor-Koldasov opened this issue Nov 24, 2021 · 1 comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@Egor-Koldasov
Copy link

Bug Report

πŸ”Ž Search Terms

Implicit type guard by other variables.

Related

#44730

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type guards

⏯ Playground Link

Playground link

πŸ’» Code

const state = {
  prop1: 'value1',
  prop2: 'value2',
  prop3: 'value3',
}

type State = typeof state;

type Keys = (keyof State)

const makeSetProp = (path: Keys | undefined) => {
  // "setProp" is not null if "path" is not undefined
  const setProp = 
    path ?
      (value: string) => state[path] = value :
      null;
  // "data" is not null is "path" is not undefined
  const data =
    path ?
      'nextValue' :
      null;

  // "data" is always not null if "setProp" is not null, but the compiler does not recognize it
  if (setProp) setProp(data); // Argument of type 'string | null' is not assignable to parameter of type 'string'
  if (data) setProp(data); // Cannot invoke an object which is possibly 'null'.
  if (path) setProp(data); // Cannot invoke an object which is possibly 'null'. Argument of type 'string | null' is not assignable to parameter of type 'string'.
  if (setProp && data) setProp(data); // works
}

πŸ™ Actual behavior

  • data does not narrow by checking the setProp
  • setProp does not narrow by checking the data
  • data and setProp both do not narrow by checking the path even though they were defined by it

πŸ™‚ Expected behavior

Logically they all can be narrowed by each other:

  • data can be narrowed by checking the setProp or path
  • setProp can be narrowed by checking the data or path
@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Nov 24, 2021
@RyanCavanaugh
Copy link
Member

The behavior in #44730 doesn't go as far as a full-blown counterfactual analysis, which is basically what'd be required here. The guarding expression has to be a boolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

2 participants