Reputation: 8839
If I want one place to define my types accessible to the rest of the project, am I supposed to use index.d.ts
or just define like any other .ts
file?
Currently, I have a folder <root>/src/types/index.ts
that works, and it compiles to <root>/dist
, where <root>
contains package.json
, tsconfig.json
, etc. I was wondering if this was normal practice or if I am supposed to define a index.d.ts
. I am unsure of the usage of index.d.ts
because it seems like it is for when publishing .js
npm modules, whereas I just have my own small project that is all .ts
. Also if I am to use index.d.ts
, should it go at the level of <root>
or <root>/src
?
Upvotes: 14
Views: 9001
Reputation: 4532
If I want one place to define my types accessible to the rest of the project, am I supposed to use
index.d.ts
or just define like any other.ts
file?
TL;DR: If you are have an existing JavaScript library, you use a .d.ts
file to define its types. If you are creating new types in your project from scratch, you use .ts
files.
.d.ts
files are type definition files. Their purpose is to allow interacting with third party JavaScript APIs in a strongly typed manner via TypeScript.
You can learn more about these files on DefinitelyTyped and search for existing definitions using Microsoft's TypeSearch.
If you are using an API that you cannot find type definitions for, you might consider writing your own .d.ts
files following Microsoft's guidelines. You might also take a look at how to produce a .d.ts “typings” definition file from an existing JavaScript library.
I want one place to define my types accessible to the rest of the project
You might want to checkout barrels. Barrels are a way to aggregate multiple modules so you can import their content with a single statement. See also: What are all the index.ts used for? This allows you more flexibility when structuring your project as you can have multiple files in multiple folders and aggregate them for easier importing. Note that you would need a module bundler such as webpack that supports using barrels.
Also if I am to use
index.d.ts
, should it go at the level of<root>
or<root>/src
?
This is not exactly a matter of it being index.d.ts
or index.ts
but of module resolution.
Upvotes: 19