🔎 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.
🔎 Search Terms
parameter symbol assignment binding pattern dependent narrowing variables
🕗 Version & Regression Information
⏯ Playground Link
https://www.typescriptlang.org/play?ts=5.4.0-dev.20231105#code/GYVwdgxgLglg9mABFApgZygCgNoA8A0iAngLoBci2AjIQEwmIA+lAzIQCwkCUiA3gFCJEMYIkwBZAIZQAFgDoATpLAATOAFtMXHgKFCiiALyJaAbkGIAvhZFiDhhyZ0WhuF4gD0HxAD0A-BbW1vxeiMqIKLiS6gAOADYoiABuknEwKogQqXHIMtKI6jAA5jJQiAmSGVBwYYgK4LDqiSgKCnAKwkiyiVlxCRmgkLAI-KgYOGyInFymQA
💻 Code
🙁 Actual behavior
Assignment to
ykeeps narrowingxas ifywas never mutated. Effectively the binding pattern in this parameter is treated asconstvariable🙂 Expected behavior
I'd expect this assignment to prevent dependent narrowing altogether.
Additional information about the issue
Assignment to
xactually 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.