Fix TS2742 false positive for self-imports in declaration files #62843
+347
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #62806
This PR fixes an issue where self-referencing imports inside
.d.tsfiles incorrectly resolve to source files duringtsc --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:
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