TypeScript: Specify a directory to look for module type definitions
Asked Answered
B

2

27

Heyho,

I want to use some javascript libraries in my typescript code for which there are no typings in npm. So I wrote the typings myself and put them in a definitions directory in my source tree. However, I could not get typescript to look in that directory for those modules.

My directory structure looks like this:

+-node_modules
| |
| +-moduleA
| |
| +-moduleB
|
+-src
| |
| +-definitions
| | |
| | +-moduleA.d.ts
| | |
| | +-moduleB.d.ts
| |
| +-ts
|   |
|   + ... all typescript code ...
|
+-tsconfig.json

I tried including the modules in the definitions-directory using

  • include
  • files
  • typeRoots
  • paths

However none of it worked.

Can somebody tell me, how to get typescript to include those typings?

PS: Why is the TypeScript module handling so complicated???

Brammer answered 4/8, 2017 at 12:58 Comment(0)
A
20
{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types",
      "./some-custom-lib"
    ]
  }
}

the typeRoots string array is just for that. In addition to your regular "node_modules/@type", add a custom made typings folder.

Autochthonous answered 4/8, 2017 at 13:9 Comment(6)
This seems to work as long as I do not have any import-statements in my module definition. But without the import I cannot type my module correctly.Brammer
This doesn't work because typeRoots expect typings in script format instead of module format.Spoonful
Is that documented somewhere? I could not find information on such things.Brammer
I have no idea, this is just what I do.Autochthonous
I found my typeRoots were ignored as I had the files ending with .d.ts ; changing to .ts instead works; so this approach no doubt requires some other compiler options set to not ignore the .d.ts (at least in my case)Brisesoleil
@Brammer Move your import statement inside your module declaration, e.g. declare module 'my-module' { \n import type { Buffer } from 'node:buffer' .... This solved the import statement issue that I also had.Dichogamy
P
9

You can include them with the triple-slash Directives to direct the compiler to use them.

E.g. create an index.d.ts file and put it your definitions folder. There you can include every custom typing you made. It could look like this

/// <reference path="react.patch.d.ts" />
/// <reference path="custom-typings.d.ts" />

Inside the typings file the first line has to be

/// <reference types="nameOfIt" />

Then in your tsconfig.json you include them in the files field e.g.

"files": [
    "definitions/index.d.ts"
  ]
Prewar answered 4/8, 2017 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.