Typescript has these things called namespaces. To cut to the chase, namespaces offer a way to group things up. You can find out some information about what they are and how to use them here.
I've known about their existence for quite some time but until recently, I didn't think I had a reason to use them. There are already so many other ways you can group things up.
You can group things up using objects:
export const CustomMath = {
add(a: number, b: number) {},
subtract(a: number, b: number) {},
}
You can group things up using classes:
export class CustomMath {
public static add(a: number, b: number) {}
public static subtract(a: number, b: number) {}
}
You can group things up using wildcard imports:
// customMath.ts
export function add(a: number, b: number): void {}
export function subtract(a: number, b: number): void {}
export type Range = { lower: number; upper: number }
// anotherFile.ts
import * as CustomMath from './customMath'
const myRange: CustomMath.range = { ... }
With this solution, you can also include types/interfaces within the grouping. As far as I'm aware that isn't possible with the previous 2 methods.
One thing I don't like about wildcard imports is that it's still possible to import each of those functions individually. There's nothing in place to stop people from doing this. Straggler functions (and types) that seem like they would be better off being logically grouped annoy me a bit.
Namespaces
// customMath.ts
export namespace CustomMath {
export function add(a: number, b: number): void {}
export function subtract(a: number, b: number): void {}
export type Range = { lower: number; upper: number }
}
// anotherFile.ts
import { CustomMath } from './customMath'
const myRange: CustomMath.range = { ... }
You can still access functions, constants, types and interfaces that are exported from your namespace, but now they're grouped nicely under a single import. Bliss.
There are drawbacks to using namespaces, some of which have been mentioned here. There are also other ways to avoid the minor annoyances I've mentioned in this post. One way is to make better use of index
files. This is something I've done in personal projects and it works well for me, however it seems like too much of a manual effort to convince my colleagues to try this. Namespaces will be my go-to in situations where objects or classes aren't more appropriate.
Top comments (1)
Back in TS 0.somthing they used to encourage this all the time. I think they wanted the language to be much more like C# back then. So all my really old code is namespaced and I even used reverse DNS when doing it.
Then somewhere after that, it seemed like it was frowned upon. I'm not sure now if it was my linters or IDE that was telling me to remove namespaces.
I don't have a lot of opinions but JS is very PRO deconstruction. Which definitely loses some context when you simply see
range
but if something we managed to make nice small units of code that shouldn't be too much of a problem.