Instead of repeatedly copying Typescript types from one project to another, I have created a private NPM package with all the shared types under a Typescript namespace. Each project installs this NPM package if it uses the shared types.
index.d.ts
export * as v1_6 from './types/version1_6';
export as namespace SharedNamespace;
One of the projects using these types is a Serverless mono-repo structured as follows:
package.json
tsconfig.json
|_ lib
|_ services
|_ service1
|_ service2
|_ service3
|_ service4
|_ serviceX
The main tsconfig.json
is in the parent directory, and there are several serverless projects within a services
sub-directory, where only service1
has the private NPM types installed.
When trying to use the namespace in the service1
project, an error occurs:
Cannot find namespace 'SharedNamespace'.
This error could be due to two reasons:
- The types are not in the default
./node_modules/@types
location. - Since the NPM module contains only Typescript namespaces, it is not explicitly imported anywhere in the project.
My question is: What is the best way to include it in our global type scope?
Initially, I tried extending the base tsconfig.json
file with a custom one in the service1
directory:
{
"compilerOptions": {
"typeRoots": [
"../../node_modules/@types",
"./node_modules/@types",
"./node_modules/@myOrg/privateTypes"
]
},
"extends": "../../tsconfig.json"
}
However, even after doing so, the same error persisted.
But when the namespace was manually imported where needed, the error disappeared. Ideally, importing it every time would not be necessary.
Update 1
If I use the following tsconfig.json
:
{
"compilerOptions": {
"typeRoots": [
"./node_modules/@myOrg/privateTypes"
]
},
"extends": "../../tsconfig.json"
}
An error now occurs stating
Cannot find type definition file for 'types'. The file is in the program because: Entry point for implicit type library 'types'.
However, in the package.json
of the private NPM module:
"main": "",
"types": "index.d.ts",
"typeScriptVersion": "3.9.7",
and in the project directory:
https://i.sstatic.net/Ck2e9.png
So why can't it locate that file?