Types Deep Dive 10 exercises

Merge Namespaces in TypeScript

We started with a declare global block that initiates a namespace React:

declare global {
namespace React {}

Anything declared in the React namespace here will be merged with the existing namespace.

In this case, since the test is expecting a MySolutionInterface,

Loading solution


00:00 As you might have figured out, the solution is very, very simple. Inside this declare global, we're initiating a namespace React. This isn't conflicting with the existing namespace. Actually, anything you declare in here will be merged with the existing namespace. And so, I've got, I'm expecting a MySolutionInterface here.

00:18 If I say interface MySolutionInterface, I can now, you'll now start to see this error actually changes, and MySolutionInterface now exists. I can actually use this. I can say type example equals React.MySolutionInterface. There it is. So weird.

00:35 And now, what we can do is we can say foo string inside here. And now the error goes away. Now, this is going to come up later, but this is a really, like, important thing to understand about how you can actually work with the global namespace. You can append to existing namespaces,

00:54 and inside them, you can actually add new interfaces into there, which is really interesting. And we're going to see how that comes up in the next exercises.