Skip to content

Assertions do not narrow related variables like conditions do #60904

Closed
@tusharsnx

Description

@tusharsnx

🔎 Search Terms

Assertion functions
Narrowing

🕗 Version & Regression Information

  • This changed between versions ______ and _______
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

⏯ Playground Link

https://www.typescriptlang.org/play/?ssl=17&ssc=54&pln=1&pc=1#code/MYewdgzgLgBGCuBbAXHJAjApgJxgXhgEYBuAKFElgEsIA5JAeTE3zUXzwJNJ4HpeYAFQAWLAIIQIOKFXAxwAGwCecAIbZsIAO4QYAAxr1ETTHphQQMAERRs8TFYA0MdPFgLMqgG6ZdehIhmqroBWNikAGbwYMAycsFS2FCCdpgAFF6qCvao6CAgHqpgAJSoCdK6mdksNOapMADepDAwVBEwaQCEVfbF5sKaWjAAohog2GlWYCCwtvZWxWQAvqTlSSn2aYaMzIuk28bMxC0nLfwwqrHwWah6c6bHmAAeAA6YsZgAJrf3ZoCg5KQAsdTiCzgJLlBrgpbqEcHpHq93lAvrdCGYYIAZch4pHOegAkhEzGB1INdHkoMJ9AcTEEwJ99AE9Pt2l0tnQdphin0KYMRmMJlMZnV5ntqUdQTBzhCoT9UvCYM83h9vvpfjAAUCJSCpVcbvo0QilciVXo0RK-kA

💻 Code

const num: number = 1;
const isNumOne = num === 1;


// The Assertion only narrows `isNumOne` to "true", but leaves `num` as number
function assertTrue(value: boolean): asserts value is true {
  if (!value) throw Error("not true");
}
assertTrue(isNumOne);
isNumOne;       // actual: `true`; expected: `true` ✅
num;            // actual: `number`; expected: `1`  ❌


// `If` narrows both `isNumOne` and `num`
if (!(isNumOne)) throw Error("not true");
isNumOne;       // actual: `true`; expected: `true` ✅
num;            // actual: `1`; expected: `1`       ✅

🙁 Actual behavior

In the example above, when isNumOne is narrowed to true using an assertion function assertTrue() or if, I expect num to be narrowed down to 1 at the same time because they're related.

🙂 Expected behavior

This seems only true in the case of if. assertTrue() narrows only isNumOne without narrowing num.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions