Modules Scripts and Declaration Files 7 exercises

Understanding Global Declarations in TypeScript

There are two ways to declare global types in TypeScript.

Use a .d.ts File for Global Declarations

The first approach involves declaring global types and constants in a .d.ts file.

In this case, we'll create a new debug.d.ts file that contains a typed version of the DEBUG variable we

Loading solution


00:00 Okay, let's take a look at both of these solutions. The first solution here, you'll notice that debug, the errors have gone away. If we look at both of the files here, both of the .ts files, we can see that debug.getState is declared. And if we command click it, we can see where it's coming from.

00:18 It's coming from a .d.ts file that I've created inside here. Now, when we do declare like basically a runtime sort of type in this context, we need to use declare here. If we don't use declare, we're going to get an error saying that top level declarations in .d.ts files

00:37 must start with either a declare or an export modifier. And because we're declaring this as a global and not exporting it from the file, we use declare here. So declare const debug looks exactly the same as when we had it actually in our file. Now, the other solution here, instead of using a .d.ts file

00:55 is to use a declare global declaration. And now a declare global declaration, we just basically put the const debug inside this scope that we've opened out here. So we just say declare global inside a .ts file and boom, we can just put anything we want to in here. So we can say const debug two

01:14 and we'll declare that as a string. And now we get access to debug two, not only in this file, but also in other files too. So now this other file .ts, we've still got access to debug two inside here. So it's kind of like we've been able to get around making a declaration file.

01:32 Instead, we just get to declare global inside a .ts file and boom, we're good to go. So this is useful and it's a question then, what should you use? Should you use a declaration file or should you declare global inside your own files here?

01:49 I tend to prefer using a declaration file. If we take a look at the just Explorer here and we compare these two options, this solution without the .d.ts file, it's kind of unclear where it lives. And of course you can dive into a file and just command click and go to it. So that's perfectly fine.

02:07 But with a actual declaration file, it becomes immediately obvious where that file lives. And it's just a nice place where you can organize and put your global types. So I would recommend if you're doing any global ambience kind of alterations, you put them in a .d.ts file.

02:26 But if you just want them to live in like co-located with the file that they're next to or the one that they're related to, yeah, why not? Declare global is a perfectly useful syntax and it comes up useful in certain situations too.