admin管理员组

文章数量:1221379

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?

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?

Share Improve this question asked Dec 20, 2019 at 8:47 artemtamartemtam 731 gold badge2 silver badges5 bronze badges 1
  • If i'm working with typescript directly I usually would not create a .d.ts file, but if you have shared Types, you could maybe move them to a separate file, as rdd mentions in his answer. If you where to compile it, typescript has the options to generate a .d.ts files automatically – Keff Commented Dec 20, 2019 at 8:59
Add a comment  | 

2 Answers 2

Reset to default 12

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.

  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.

本文标签: javascriptThe best way to share types in a large TypeScript projectStack Overflow