platizin
platizin

Reputation: 872

How to export types in a TypeScript npm module

In TypeScript, say I want to have the user use my module's "internal" types so they can properly type their own variables when using my module - do I just export literally everything from my index.ts file to accomplish this?

// index.ts

export * from './file1' // uses types/interfaces defined in file1types
export * from './file2' // uses types/interfaces defined in file2types
export * from './types/file1types'
export * from './types/file2types'

Do .d.ts files help me accomplish this, or are they only for non-TS projects? Does tsconfig.json's option declaration: true help me accomplish this by generating a .d.ts for every TS file? Is this an alternative to exporting everything from a single index.ts file?

And if declaration: true does help me accomplish this, how would the user use all those generated .d.ts files within the build folder?

I would greatly appreciate some clarification as to how one typically exports types in TS projects. Thanks in advance.

Upvotes: 32

Views: 47238

Answers (2)

Wallace
Wallace

Reputation: 279

For those who are like me, and have made sure declaration: true is set in your tsconfig.json, and that your build process correctly creates the corresponding .d.ts files to the appropriate directory pointed to by your package.json file, AND STILL somehow can't access the internal types of your module when testing on an external project -- try restarting the TS server in VSCode (assuming you're using VSCode)

enter image description here

So much time was wasted trying to figure this out, only to realize Typescript was functioning fine and I was being sabotaged by my IDE.

Upvotes: 20

Zwiers
Zwiers

Reputation: 3678

Without declaration files you can develop a package in TypeScript, compile it and expose it to other users as JavaScript code. Including them also allows TypeScript developers to use the package with any types you defined in it. They can get more type information whilst working with your library, such as required arguments types, function return types etc, as well as warnings from their IDE/Intellisense when there are conflicts.

The declaration: true in the file tsconfig.json instructs the TypeScript compiler to output declaration files (.d.ts). Often they are bundled in a single file e.g. index.d.ts and then a "types": path/to/index.d.ts field is added to the library's package.json file to inform TypeScript where to look for the types (when a user imports the package).

Upvotes: 22

Related Questions