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
2 Answers
Reset to default 12I 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.
Put all the shared declarations in a file, say index.d.ts.
Put this file in a folder say /src/typings
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
版权声明:本文标题:javascript - The best way to share types in a large TypeScript project? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739299733a2157080.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论