To help you out, I've broken down the process step-by-step with detailed explanations to make it easier to follow along. While it may seem like a lot of information, if you just stick to the provided instructions, it should only take a few minutes. Alternatively, you can use this shortened version that can be run in either bash or PowerShell!
mkdir -p ./local-types/foo
cd ./local-types/foo
npm init --scope types --yes
echo "export function hello(): void; export function world(): void" > ./index.d.ts
cd ../..
npm install ./local-types/foo
A Little Background
Imagine you have the following project structure:
proj/
├─ tsconfig.json
└─ src/
└─ ...
Setting Up the Local Types Folder
You need to create a folder at the root of your project to store local types. It doesn't matter what you name it, but for now let's call it local-types
. You can always rename it later once you're comfortable with the setup.
proj/
├─ tsconfig.json
├─ local-types/
└─ src/
└─ ...
In most cases not covered by this example, you might want to name this folder types
.
Creating a New Package in the Local Types Directory
If you are looking to import a module named foo
, you'll need to create a folder called foo
within the local types directory and include an index.d.ts
file.
// local-types/foo/index.d.ts
export function hello(): void;
export function world(): void;
To turn this into an npm package, you also need to set up a package.json file:
cd local-types/foo
npm init --scope types --yes
At this point, your project structure should resemble the following:
proj/
├─ tsconfig.json
├─ local-types/
| └─ foo/
| └─ index.d.ts
| └─ package.json
└─ src/
└─ ...
You should now be able to import foo
from any file within the src
directory.
import { hello, world } from "foo";
hello();
world();
Keep in mind that if you don't have a single-entry-point package with an index.d.ts
, you'll need to replicate the package structure as seen on npm.
Adding the Package as a Dependency
For libraries, consider adding this as a dependency, while applications may prefer devDependencies. Simply specify file:./local-types/foo
as the version for @types/foo
:
"dependencies": {
"@types/foo": "file:local-types/foo"
}
Submitting to DefinitelyTyped
If your .d.ts
files are complete and useful, think about writing tests and submitting a pull request to DefinitelyTyped so others can benefit as well!
If you can successfully import these packages without any runtime issues, then you've likely structured the package correctly.
Key Points to Remember