TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

CFA does not consider pass-by-reference to invalidate assumptions

Open Sainan opened this issue 10 months ago • 2 comments

🔎 Search Terms

control flow analysis, branch, condition

🕗 Version & Regression Information

Tested in 5.8.2.

⏯ Playground Link

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true#code/JYOwLgpgTgZghgYwgAgBIFcC2cTIN4BQyycA5hAPwBcyIWARtANwEC+BBM6ICYwA9rgSCAzlggAKfvQBWNDNhABKfEWTSZAOjIoAvMm4ATCDFARDLdgWEgRYdbPlYcyfXhLkaAFgBMyVizAMMhSstrkKoTENmKYkhpKLNGi9jo0dJiMUK4OWjpMyAD0hcgAcvypuNBQ-FBsBEA

💻 Code

interface Human {
  age?: number;
}

function consume(obj: Human) {
  obj.age = undefined;
}

const obj: Human = { age: 42 };
if (obj.age) {
  consume(obj);
  const age: number = obj.age; // Not an error
}

🙁 Actual behavior

Assignment of const age: number succeeds with undefined.

🙂 Expected behavior

obj.age is assessed as number | undefined, causing the assignment to fail.

Additional information about the issue

No response

Sainan avatar Mar 13 '25 19:03 Sainan

Duplicate of https://github.com/microsoft/TypeScript/issues/9998

nmain avatar Mar 13 '25 20:03 nmain

Fair, although in this case the function is not a black box.

Sainan avatar Mar 13 '25 20:03 Sainan

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar Mar 16 '25 01:03 typescript-bot