TypeScript Only Features 9 exercises

Merging Namespaces in TypeScript

Namespaces can be merged with declaration merging.

Here we have two declarations of GeometryUtils: one with a Circle namespace and one with a Rectangle namespace.

namespace GeometryUtils {
export namespace Circle {
export const calculateArea1 = (r: number) => Math.PI * r **

Loading explainer


00:00 Let's look at one more feature of namespaces that make them pretty interesting to use. There's a GeometryUtils namespace up here, which we've seen before, but this one only contains the circle stuff. So only the circle namespace. Then inside here, we have a GeometryUtils namespace, which only contains the rectangle space.

00:18 And if you look here, they have exactly the same name, GeometryUtils. So just like we saw that interfaces can declaration merge, so can namespaces.

00:27 And you can see that if we say namespace.GeometryUtils.Circle.CalculateArea, we have access to that. And then we also have access to GeometryUtils.Rectangle.CalculateArea, one and two, for instance.

00:45 Nope, I'm not getting that interface wrong, but you get the idea. So there are some constraints to this, like all must be exported or none of them must be exported. So if I say export namespace like this, then it's going to give me an error because individual declarations in merged GeometryUtils must be all exported or all local. Fun, fun, fun.

01:04 So this is kind of a strange feature. It will come up later in the book. There are reasons you would do this, but certainly it's as a way to organize application code. It's pretty gnarly, I would say, and not a particularly fun way to structure your code.

01:24 So yeah, I don't think, again, namespaces are probably not something that you want to be using.