typescript-go icon indicating copy to clipboard operation
typescript-go copied to clipboard

New implicit any error from self referencing in initializer

Open jkieboom opened this issue 6 months ago • 0 comments

I'm not sure if this is a bug in the current or in the new compiler, but there is a scenario where some amount of logic involved determining the type from an initializer is showing an error in the new compiler where it doesn't in the current compiler:

class A {
  next: A | null = null;

  constructor(readonly children: (A | null)[]) {}
}

function getNodes(): A[] {
  const out: A[] = [];

  let current: A | null = new A([]);

  while (current !== null) {
    let firstChild = null;

    // If the following if block is commented out, then current TS also shows an error
    if (out.length) {
      current = current.next;
      continue;
    }

    for (let i = 0; i < current.children.length; i++) {
      const child = current.children[i];

      if (child) {
        if (!firstChild) {
          firstChild = child;
          firstChild.next = current.next;
        }

        child.next = current.next;
      }
    }

    current = firstChild || current.next;
  }

  return out;
}

(example is nonsensical, just tried to reduce it to a minimal repro from the real code)

src/indirect-init.ts:21:13 - error TS7022: 'child' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

When I comment out the if condition it gives this error in both old and new compiler.

playground

jkieboom avatar May 30 '25 10:05 jkieboom