1

In my eyes, we can put type declaration in any typescript file ( such as '.d.ts', '.ts', '.tsx' ).

But I found that almost every npm package's type declaration file is .d.ts file.

Is this necessary?


My real world scene is that I just want my npm package been used by some typescript project, so I publish my package without compile (all .ts files)

I'm not sure is there any problem?

sputnik
  • 45
  • 4
  • 1
    You (generally) don't ship .ts or .tsx (or .jsx) files when publishing, you ship .js. So the types have to be in a .d.ts declaration-only file because they're erased in creation of the .js. – jonrsharpe Feb 09 '22 at 08:55
  • 1
    Does this answer your question? [About "\*.d.ts" in TypeScript](https://stackoverflow.com/questions/21247278/about-d-ts-in-typescript) – jonrsharpe Feb 09 '22 at 08:57
  • @jonrsharpe If I just want my npm package been used by some typescript project, so I publish my package without compile (all .ts files), is their any problem? (even if it's not common) – sputnik Feb 09 '22 at 09:05
  • @sputnik the problem comes when you want to use your library. Even if you use it in a TS project, the resulting code will always have to be JS, so you will have to compile your TS to JS sooner or later. Either before you publish (the recommended way) or right before the package is used (it works, but it usually requires some custom compilation logic). – Olian04 Feb 09 '22 at 09:16

1 Answers1

3

When publishing a package you generate .js files and .d.ts files. This guarantees that people can install your package in a 'normal' JavaScript project and do not have to use TypeScript if they don't want to. They can not interpret .ts or .tsx files. The .d.ts files alongside your .js files can then be ignored.

If you only want to use this package in your own TypeScript projects. You will have to tell your bundler (like Webpack) to also compile this package by using the ts-loader, as a browser cannot interpret TypeScript. Also, if it is a Node.js app, Node itself is a lot faster than ts-node. In my opinion this would be unnecessary overhead.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437