Search code examples
typescripttypescript-typingstsc

How to add types d.ts incrementally to my js library?


I am building a library written in pure javascript. I was asked to create types for consumers that are using the library from typescript projects. The library is a little bit extensive so they are happy for me to provide the definition for only the most used functions.

I did exactly that with the most used functions in "types/index.d.ts"... but now I am struggling to get the configuration right for my package.json.

1.- adding at package.json

{
  ...
  "types": "types/index.d.ts",
  ...
}

works for my consumers in typescript so they get autocompletion in vscode but fails to them when compiling a typescript that tries to import a missing function in the types/index.d.ts

import {superFetch} from 'aweJsTurbo'

types/index.d.ts TS2305: Module '"aweJsTurbo"' has no exported member superFetch

Interestingly, it generates js code that work perfectly (as it is able to import the right javascript).

2.- removing from package.json "types": "types/index.d.ts", makes the tsc compiler works but they lose autocompletion.

I would have thought that there should be a way to remove the annoying compilation errors for types declaration for which there is an actual implementation in javascript.

Any help?


Solution

  • fails to them when compiling a typescript that tries to import a missing function'

    The whole point of Typescript is to ensure type safety, so this is expected behavior.

    You might want to look at approaches like this one to ease the burden of maintaining the *.d.ts file for a large codebase, though. I haven't tried it, but wager if you provide even the simplest JSDoc for all of your API methods, it will generate reasonable TS declarations you can then incrementally improve upon.