Skip to content

Yielding an assertion function call does not narrow the asserted typeΒ #55205

Closed as not planned
@WilcoKruijer

Description

@WilcoKruijer

Bug Report

πŸ”Ž Search Terms

generator, yield, assertion function

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about assertion functions and generators.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

 function * testFunc() {
    type SomeType = {a: number};

    let count = 0;
    function assertAThing(obj: unknown): asserts obj is SomeType {
        // don't care about the impl
        count++;
    }

    const bla: unknown = {a: 3};
    assertAThing(bla);

    // no type error here
    console.log(bla.a);

    const bla2: unknown = {a: 4};
    yield assertAThing(bla2);

    // bla2 is unknown, but should be SomeType as asserted by the assertAThing call.
    if (bla2.a !== 4) {
        throw new Error("bla2.a should be 4.");
    }

    if (count !== 2) {
        throw new Error("Count should be two.");
    }

    console.log("Javascript success")
 }

for (const item of testFunc()) {
    //
}

πŸ™ Actual behavior

The variable bla2 is still unknown even after passing it through the assertion function assertAThing.

πŸ™‚ Expected behavior

bla2 should be narrowed to be SomeType like bla1.

Workaround

We are effectively yielding void since assertion functions cannot return anything. This means there is a simple workaround:

assertAThing(bla2);
yield;

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