In contrast to Java (and other languages), TypeScript offers you multiple ways to export and import things (classes, functions etc.).
For example, you can export multiple classes, constants, functions etc. per file.
Also you can define 1 default export per file.
On the other side you can import only the default export, import everything using an alias or import the given things.
Coming from Java, I wonder, if there is any convention, especially regarding constants and functions.
Let's say I have a util-file, having a lot of functions. In Java I would create a File Util.java with class Util, which contains all the static functions.
In TypeScript I have following possibilities:
- Export every single function and import it using
import * as Util. - Create a
class Utilwithstatic functions and export only this class.
In both cases I can call functions using Util.functionName(), just like in java.
Another case is a class with a few constants.
For example I have a class Car with a field type. There are also constants for the available types, like TYPE_SUV, TYPE_SPORT and so on.
Again, I can define them as "top-level" constants and export them and the class Car. But I can also define them as public static readonly inside the Car-class and export that class only.
Using the first approach, I would have a verry big import statement, if I need all constants in other files. Also sub-classes won't "inherit" those constants.
However using readonly instead of const feels kind of strange to me...
So I was looking for some kind of convention, but I did not find much.
I only found a few tips like this.
So, are there any guidelines regarding exports and imports in TypeScript, which take care about the explained problems? I am also looking for the best way, regarding integration of tools (refactoring, auto-importing, organizing imports etc.).
Thanks.
import static package.Util.functionName, by the way, for static methods and variables. In both cases importing a subset of what's available initializes both namespaces fully (class and js-file respectively). Other than that, answer to this lies in some place with whether you indent you code with tabs or spaces, and how much of each of those a good programmer needs in their life.import static, however it seems to be rarely used. As I am pretty new to TypeScript I don't have a preference on that yet, so I wanted to choose the thing, that tools (IDEs, Editors etc.) like the most. For exampledefault exportsseem to cause problems with refactoring.stream.collect(Collectors.toList())is a little shorter withoutCollectorsin the middle. As for tool and refactoring, - it at least looks to me that there is more than one way to express same import in JS, so tools get confused, but tools will eventually catch up anyway. You should choose what's better for you to read, not for machines.