artemtam
artemtam

Reputation: 83

The best way to share types in a large TypeScript project?

I'm working on a large React application written on TypeScript. I have many common types declared in separate files, and every time I need a type I import it. It works well, but creates tons of different imports, what I definitely don't like.

Another option would be to use .d.ts files to declare types globally and be able to use types without explicitly importing them. Is this considered as a better practice or I should stay with imports?

Upvotes: 8

Views: 11615

Answers (2)

Nati Kamusher
Nati Kamusher

Reputation: 791

  1. Put all the shared declarations in a file, say index.d.ts.

  2. Put this file in a folder say /src/typings

  3. In tsconfig.json, update the following field:

    {.   
       "compilerOptions": {.  
           "typeRoots": ["./node_modules/@types", "./src/typings"].  
       }.  
    }.  
    

Now the types will be available in all files.

Upvotes: 6

rrd
rrd

Reputation: 5977

I think a common sense approach to this is the best. For example, we are working in a large React app right now, using a monorepo, with a shared repository for shared components. So we have rules about things like declarations and components:

  • if you use a type/interface in more than one place it goes into the ~shared/lib/types.ts file
  • if you have a component that's used in more than one place it gets refactored to to the ~shared/components folder
  • if you extend a type/interface, it can be declared locally, but as long as it doesn't get used more than once

Once people get used to these simple rules, it begins to make development work a lot easier. Devs get used to refactoring when they need to, but also about thinking about how they code.

Upvotes: 12

Related Questions