microsoft / microsoft/TypeScript

Spurious "referenced directly or indirectly in its own initializer" when combined with narrowing, asserts function, and loop

Open
#53,955 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

referenced directly or indirectly asserts

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

Playground Link

💻 Code
declare const myRequire: ((p: string) => {} | undefined) | undefined;

declare function assertIsDefined<T>(value: T): asserts value is NonNullable<T>

function fn1() {
    if (!myRequire) {
        return;
    }

    for (const p of ["a", "b"]) {
        // Error?
        const result = myRequire("something");
        assertIsDefined(result);
    }
}
🙁 Actual behavior

result is claimed to be referenced directly or indirectly in its initializer.

Modifying the code in various ways makes the error go away.

🙂 Expected behavior

No error; there's no relationship between the initializer and the result.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground and run the provided code sample to reproduce the diagnostic. Investigate the compiler's handling of narrowing, asserts functions, and the loop around the initializer. Done means the sample no longer reports that result is referenced in its own initializer while the expected narrowing behavior remains intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.