Skip to content

Not all parameter assignments prevent incorrect dependent narrowings Β #56312

Closed
@Andarist

Description

@Andarist

πŸ”Ž Search Terms

parameter symbol assignment binding pattern dependent narrowing variables

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.0-dev.20231105#code/GYVwdgxgLglg9mABFApgZygCgNoA8A0iAngLoBci2AjIQEwmIA+lAzIQCwkCUiA3gFCJEMYIkwBZAIZQAFgDoATpLAATOAFtMXHgKFCiiALyJaAbkGIAvhZFiDhhyZ0WhuF4gD0HxAD0A-BbW1vxeiMqIKLiS6gAOADYoiABuknEwKogQqXHIMtKI6jAA5jJQiAmSGVBwYYgK4LDqiSgKCnAKwkiyiVlxCRmgkLAI-KgYOGyInFymQA

πŸ’» Code

function test([x, y]: [1, 2] | [3, 4]) {
  if (Math.random()) {
    y = 2;
  }
  if (y === 2) {
    x
    // ^? (parameter) x: 1
  }
}

// an example valid call that might lead to a runtime error in the called function
test([3, 4]);

πŸ™ Actual behavior

Assignment to y keeps narrowing x as if y was never mutated. Effectively the binding pattern in this parameter is treated as const variable

πŸ™‚ Expected behavior

I'd expect this assignment to prevent dependent narrowing altogether.

Additional information about the issue

Assignment to x actually prevents dependent narrowing in a scenario like this: TS playground. It's just that those assignments are tracked per symbol and not per the root declaration. I believe that the simplest fix would be to just mark the whole root declaration as reassigned and treat all contained variables as non-const based on that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Possible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions