typescriptwebpacktsconfigtsctypescript-declarations

In TypeScript's generated declaration files, exclude internally exported types


I'm writing an interview question. I'm mocking a backend server by creating an "Http Client" package. Some of my types I want exposed in .d.ts files so that the interviewee has context, but most I do not, as they would expose the inner workings of the mock, and give the interviewee some types that I'd like them to generate.

src/index.ts

import myPackageExport from `./my-package-export`;
export * from `./public-types`;
export { MyPackageExport } from `./my-package-export`;

export default myPackageExport;

I would like to simply set something in my tsconfig.json and/or in my webpack.config.js like:

tsconfig.json

{
  "compilerOptions": {
    // ...
    "noEmit": true, // I've also tried `false`
    "declartion": true,
    "emitDeclarationOnly": true,
    "rootDir": "./src",
    "outDir": "./lib",
  },
  "include": [ "./src/index.ts" ],
  // ...
}

webpack.config.js

// ...

module.exports = {
  entry: path.join(__dirName, 'src/index.ts'),
  output: {
    fileName: 'index.js',
    path: path.join(__dirName, 'lib'),
  },
  // ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [ 'ts-loader' ],
      },
    ],
  },
  resolve: {
    extensions: [ '.js', '.ts' ],
  },
  plugins: [
    // some fancy declaration plugin here
  ],
};

This, of course, is oh-so-considerate and generates declarations for the entire dependency graph of index.ts, which is the whole project. Usually this is what we'd want, just not in my case.

A simpler solution would be something like // @ts-exclude-declaration that I could prepend to each file whose types I want excluded, but as far as I know, no such thing exists.

My current workaround is to add/modify three files:

src/public-types/index.ts (modified)

export * from './my-public-types1';
// ...

export interface MyPackageExport {
  // ...
}

declare const myPackageExport: MyPackageExport;

export default myPackageExport;

tsconfig.types.json (added)

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    // ...
    "declaration": true,
    "emitDeclarationOnly": true,
    "srcRoot": "./src/public-types",
    "outDir": "./lib",
  },
  "include": [ "./src/public-types/index.ts" ],
}

package.json (modified, obviously)

{
  "scripts": {
    "build": "webpack --mode production && tsc -p tsconfig.types.json",
    // ...
  },
  // ...
}

This works, but is far from elegant.

Ideas?


Solution

  • tsconfig has a stripInternal option, which allows you to use the JSDoc @internal tag to exclude declarations from your .d.ts file.