Part 1 - Utilizing the "types" Field
When a TypeScript library like library A provides type definitions alongside its normal exports, it looks like this:
declare global {
function someGlobalFunction(): void;
}
Library B depends on the type definitions from library A. To make this work, we include the following in the tsconfig.json of library B:
"types": ["library-a"],
- By doing this, any usage of
someGlobalFunction
will no longer throw a compiler error. - Naturally, "library-a" needs to be listed as a dependency in the package.json of library B.
- Furthermore, "library-a" must be installed and accessible in the "node_modules" subdirectory.
Part 2 - Handling a Monorepo
In my TypeScript monorepo (using NX and Yarn), the same setup from part 1 needs to be replicated. However, there are some challenges when dealing with the 'types' field in conjunction with the 'paths' field in the tsconfig.json file used for inter-package imports within the monorepo.
Here's where it gets tricky:
- Specifying
"types": ["library-a"]
will prompt TypeScript to report that it can't find "library-a". - Adding a
typeRoots
field to point to the correct "dist" directory may resolve the previous error, but it could lead to "not found" errors for individual symbols within "library-a". - Simply installing "library-a" directly might seem like a quick fix, but it defeats the purpose of using a monorepo in the first place.
What's the correct approach for a package to import types from another package within a monorepo? Any insight or guidance on this issue is greatly appreciated.
If necessary, I can provide a concise example repository to demonstrate the problem.