How to declare Typescript types for generated Javascript

Viewed 26

What's the right way to declare types for generated Javascript that allows it to be exposed from a library? It seems like it should be straightforward, but getting the hand-written .d.ts file to be used and copied to the outDir is proving very difficult. Currently, I'm getting the .d.ts files generated by tsc in the outDir, so it has inferred types instead of the correct ones.

Source structure:

src/
  __generated__/
    validateEvent.js     <-- generated
    validateEvent.d.ts   <-- NOT generated, but doesn't seem to work elsewhere
  Event.ts
  index.ts

validateEvent.d.ts:

import { ValidateFunction } from "ajv";
import { Event } from "../Event.js";

export const validate: ValidateFunction<Event>;
export default validate;

index.ts:

export * from "./Event.js";
export { default as validateEvent } from "./__generated__/validateEvent.js";

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "composite": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["es2021"],
    "module": "es2022",
    "moduleResolution": "node",
    "outDir": "./dist",
    "rootDir": "./src",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2022",
  },
  "include": ["src/**/*"]
}

There seems to be two related questions here:

  1. How can I get my .d.ts file copied to outDir instead of the one generated from the generated Javascript?
  2. Can I put my .d.ts file somewhere other than the __generated__ directory? (If I can solve this, maybe #1 is moot. I've tried various forms of declare module, but nothing has worked except putting the .d.ts next to the generated source.)

If it matters, I'm using ES modules and tsc --build with project references. As a temporary hack, I am manually copying the .d.ts files to outDir, but that doesn't play so well with tsc --build --watch and nodemon.

1 Answers

My best answer so far is just to import the generated Javascript with generated typings and then export a casted version:

index.ts:

export * from "./Event.js";

import { ValidateFunction } from "ajv";
import { Event } from "./Event.js";
import { default as validateEvent0 } from "./__generated__/validateEvent.js";

export const validateEvent =
  validateEvent0 as ValidateFunction<Event>;
Related