How to Organize Your TypeScript Types
Introduction
TypeScript type definition files are often created as a global type.ts
file, which is convenient for referencing everywhere. However, this practice can lead to confusion as projects grow, as I have encountered recent issues, prompting me to research the general methods for managing type files.
Problem
Have you ever seen a single type file explode to thousands of lines? If all the type definitions for an entire project are piled in one place, it fundamentally discourages reuse. Understanding what was defined earlier and where to find it becomes problematic.
Management Methods
Method 1: Local Definition
If a type definition is only used in a single file, define it directly within that file.
interface Props { foo: string bar: number}
export const MyComponent = (props: Props) => { // ...}
Some prefer to create a same-named .types.ts
file in the same location and import it. This is purely a matter of preference; I find this approach looks cleaner but requires more effort when moving code, which I don’t prefer.
├── Foo.tsx└── Foo.types.ts
Method 2: Minimal Abstraction
If types are used in more than one place, they should be defined in a shared location.
src└── components ├── ComponentA.tsx ├── ComponentB.tsx └── components.types.ts
This reasoning applies equally to larger scales like Monorepo, defining types in a “shared location,” namely in packages
that are common outside of apps
.
apps├── app├── website└── docspackages├── types├── src└── shared.types.ts
Conclusion
Often, managing too many elements and adding poor abstractions unnecessarily becomes a problem. Elevating all types to the top level may seem convenient and give a sense of management, but it can be quite bad. The intent of separating code snippets (types, utility functions) is to encourage reuse; overly deep or shallow abstraction can create a burden.
This article primarily references the suggestions from Matt Pocock at TotalTypeScript: Where To Put Your Types in Application Code - Matt Pocock
You might also be interested in my previous article: How to Manage Utility Functions - WebDong