How to share a global.d.ts from several packages in monorepo

Viewed 672

I have my interface definitions of the result of several database queries in a global.d.ts file. As I moved the various project folders using those interfaces into a single monorepo, I am still using a copy of the same global.d.ts in each package as it was before, and it works fine, except for the duplication, which makes little sense in the monorepo.

I have a shared tsconfig.json file at the root, which is extended by the tsconfig.json in each package.

How can I move the global.d.ts file to the root of the monorepo and have all the packages use it without importing it into each source file?

I tried changing in the tsconfig of each package:

"include": ["./src/**/*"],
// into
"include": ["./src/**/*", "../../types/**/*"],

I tried adding the typeRoots in the root tsconfig:

"typeRoots": ["./node_modules/@types", ".types"]

All to no avail.

Summary: I just want to move the two identical copies of the currently working global.d.ts files in each package, to a single file in a common location and make tsc find it just as it does when there is one copy in each package.

Thanks

1 Answers

Answer to self (sorry, I logged in with a different account, I should fix that, I don't know how I got different accounts).

The best solution I found is using reference:

/// <reference path="../../types/global.d.ts" />
/// <reference path="../../types/api.d.ts" />

In this example, the types folder is at the root of the mono-repo, it is not a package but it might have been one, it doesn't really matter, your choice. I have split the single global.d.ts which I originally meant to have, into several more specific ones. The reference needs to be in any file just once in each package. I opted to put it in the root index.ts or index.tsx file which seems the most appropriate place for it.

I like this solution better than the one I was originally looking for because, it is not bothersome, as the reference must be made just once, not in every single file, and it allows me to split the definitions into various declaration files used on-demand, instead of a single one with everything piled up together.

Related