Search code examples
typescriptnpmpeer-dependencies

Is it possible to use different declaration files for different versions of TypeScript?


I have some type definitions that I want to turn into an npm package because I use them in multiple, unrelated projects. (I would likely call it @dfoverdx/ts-magic.) Some of these projects are using 3.x, and some are using >=4.2, where leading and middle rest elements in tuple types were introduced.

Is it possible to write multiple declaration files that only use the types that work in the user's version of TypeScript?

There are four ways I can think of that might work but which I do not know enough about to implement, if they're even possible.

  1. Using the lib value in tsconfig.json, the user could specify which ts-magic declaration file to include. Then each declaration file could use a triple-slash directive to reference the previous version's declaration file.

  2. I could have multiple sub-packages with dependencies on the previous sub-packages. I would much rather not go this route, especially since there is no such thing as a nested scope in NPM, and I would not want to use a different scope than my GitHub username, nor would I want to maintain multiple separate packages under the @dfoverdx scope.

    Therefore we run into another issue: some of these types strongly type global object methods such as Object.fromEntries(), and things declared within declare global {} ambient contexts--as far as I know--can't be limited to the files that include the declaration file it was declared in. That is, if my project's index.ts imported @dfoverdx/ts-magic/3.8, because I'm importing @dfoverdx/ts-magic at all, it would include every declaration file of the package.

  3. Some magic in package.json using peerDependencies or some other property I'm unaware of.

  4. Some sort of triple-slash directive. I suspect this is not the way.

I can't imagine this isn't a way to do this somehow. Thoughts on the right way?


Solution

  • You can use typesVersions property in package.json file.