When working with interfaces in TypeScript, there are two main approaches to consider. The first involves defining them in regular .ts files and importing them as needed. The second option is to define the interfaces in .d.ts files and let the compiler discover them automatically from node_modules/@types or by specifying paths in typeRoots within tsconfig.json. This allows the interfaces to be accessible throughout the project without direct imports.
In my current setup, I have separate client (React) and server (Express) projects, both written in TypeScript. To share common interfaces between these projects while keeping dependencies separate, I moved the shared interfaces to a standalone project stored in declaration files. I then included this project as a dev dependency using the following syntax:
"@types/my-definitions": "git+ssh://[email protected]/myaccount/my-definitions.git"
This configuration enables the TypeScript compiler to automatically recognize the interfaces from node_modules/@types without the need for explicit imports.
My question is, is this approach considered best practice? Should I instead store the interfaces in regular .ts files, import the shared project as a standard dependency, and explicitly import the interfaces when needed? What are the advantages and disadvantages of each method?