Types Deep Dive 10 exercises

Extend the Global React namespace with Declaration Merging in TypeScript

You can have multiple declare global blocks in the same file, even if they both are going to modify the same namespace.

In order to solve this challenge, we will duplicate the existing MyAwesomeSolutionInterface and add the bar: string; property to the second block:

declare glo

Loading solution


00:00 So the solution here is basically to copy this over to add a new declareGlobal because you can have multiple per file. And now, instead of having foo string, we can actually just add bar string. And those interfaces, because they're in the same scope, they get merged. So this is declaration merging of interfaces.

00:19 This wouldn't work if these were types, right? So if we have my awesome solution up here, these aren't going to work because we have duplica identifiers in the same scope. And it also wouldn't work if they were in different scopes. So if this one was just in declareGlobal up here, so just a globally available interface,

00:35 this doesn't work because it's not in the same namespace as this. So here we can see that you can do all of this cool little kind of like declaration merging or all this interesting stuff to actually change things that are already available in the global scope. And we're going to put this into practice in the next exercise.