In comparison to Java (as well as other programming languages), TypeScript provides multiple options for exporting and importing entities such as classes, functions, etc.
For instance, you have the ability to export
numerous classes, constants, functions, etc. in a single file.
Furthermore, it is possible to define one default export per file.
Conversely, when it comes to importing
, you can only import the default export
, import everything using an alias, or import specific elements.
As someone coming from a Java background, I am curious if there are any conventions to follow, especially concerning constants
and functions
.
Let's consider a scenario where I have a utility file containing several functions
. In Java, I would typically create a Util.java
file with a class Util
that encompasses all the static functions
.
In TypeScript
, there are two main approaches:
- Export each function individually and import them using
import * as Util
. - Create a
class Util
withstatic functions
and export only this class.
In both cases, I can call functions using Util.functionName()
, similar to how it is done in Java.
Another scenario involves a class
with some constants
. For example, let's say I have a class Car
with a field named type
. There are also constants representing different available types such as TYPE_SUV
, TYPE_SPORT
, and so on.
Once again, I can declare these as "top-level" constants, export them along with the Car
class. Alternatively, I could define them as public static readonly
within the Car
class and export only the class itself.
Opting for the first approach may result in a lengthy import
statement when needing all constants in other files. Additionally, sub-classes would not automatically inherit these constants.
However, utilizing readonly
instead of const
might seem unconventional to some.
While seeking a standard convention, I didn't come across many resources regarding exports and imports in TypeScript, specifically addressing the aforementioned challenges. The few tips I did find were limited like this
.
Therefore, are there established guidelines governing exports and imports in TypeScript that address these issues effectively? I am also interested in determining the best practices for tool integration (e.g. refactoring, auto-importing, organizing imports, etc.).
Thank you.