Search code examples
javascripttypescripttsconfig.d.ts

Is there a way to declare a specific module name for a generated .d.ts file (in a javascript project)?


Is there a way to declare a different module name for a generated .d.ts file?

tsc generates declare module "index" { instead of declare module "@myorg/my-pkg" (which would match the name attribute in package.json).

Note: This is in a pure javascript project where I'm attempting to generate types.

/* Generated with tsc --init via TypeScript 3.7.0-beta */
{
  "compilerOptions": {
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
     "allowJs": true,                         /* Allow javascript files to be compiled. */
     "declaration": true,                     /* Generates corresponding '.d.ts' file. */
    "outFile": "./lib/index.js",              /* Concatenate and emit output to single file. */
    "emitDeclarationOnly": true,              /* Only emit .d.ts files. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": [
    "js/**/*"
  ]
}

Solution

  • Unfortunately types cannot be outputted to a single file out of the box. There is an open proposal to add "type bundling" (#4433) to add the feature. There are also 3rd party libraries for helping with this.

    One other solution, if you're ok with multiple files being output is by specifying outDir instead of outFile. This was the solution I chose, setting "outDir": "./types" in tsconfig.json and setting "types": "./types/index.d.ts" in package.json. This worked as I expected when importing the module to other projects.