Fix TS2742 false positive for self-imports in declaration files
Fixes #62806
This PR fixes an issue where self-referencing imports inside .d.ts files incorrectly resolve to source files during tsc --build. This caused false TS2742 errors because inferred types appeared to reference non-portable paths in the source tree instead of the emitted declaration files.
Problem
During project reference builds, self-imports such as:
// packages/c/src/other.d.ts
import { C } from "c";
resolve "c" to src/C.ts instead of dist/C.d.ts.
This results in: - False positive TS2742 errors - Incorrect parentSpecifiers pointing to source directories - Behavior that occurs only under --build, not regular tsc
Solution
A post-resolution step was added to resolveModuleName to correct self-imports in .d.ts files: 1. If the importer is a .d.ts file and the resolved module is a TS source file: 2. Walk upwards to locate the nearest package.json for the importer 3. If the module name matches the package name (indicating a self-import): 4. Recompute the expected .d.ts output path using outDir/rootDir 5. Redirect the resolved module to the correct emitted .d.ts file
This redirection only applies to .d.ts importers and does not affect normal source file resolution.
Tests
Added tests in src/testRunner/unittests/tsbuild/moduleResolution.ts verifying that: - A self-import inside src/other.d.ts resolves to dist/index.d.ts instead of src/index.ts - The build produces no TS2742 errors - Trace resolution logs show the redirected path Removing the fix causes the test to fail, confirming coverage
@microsoft-github-policy-service agree