Ambient Context and the declare Keyword in TypeScript
The declare
keyword in TypeScript allows you to specify types for global variables. Whenever you use it, an ambient context is created, which means that the variable is injected without needing to provide an implementation.
Here's how we would use declare
to specify the type for DEBUG
, which
Transcript
00:00 The way that we handle this is using the declare keyword. So declare basically says that whatever you declare after this is going to be, let's say, a const or something. That doesn't need to provide an implementation. So if we just said like const debug, and we said it's actually just a function,
00:18 or sorry, an object with getState on it, which returns like a function with ID one, two, three on it, then all of our tests would pass. But this isn't right, because debug is being injected globally, and we just want to access it within the scope of this module. So const debug here,
00:35 we actually want to declare it with a declare const debug. But now if we look at this error here, a const initializer in an ambient context must be a string or numeric literal or literal enum reference. We're actually getting the same error as if we were to declare this in a declaration file. So this is what's cool.
00:54 Whenever you use declare, it's like an ambient context. And ambient basically means it just gets injected without needing to provide any implementation. So this means we don't need an implementation. We can just use the colon sign here, and now we can just say debug is, let's say, an empty object. This is all we need so far to kind of like declare
01:13 that something is in global scope. And so we say declare const debug. This needs a getState property, so getState. And of course, we're in the type world here, so we have a function which returns an object where we have id string. And now just for the scope of this module, as though it's being declared as a local variable,
01:33 we just have a debug.getState. So if I add a new file here, so I'll just add like index two, for instance, and I try to access debug inside here. Sorry, I've actually copied this in the wrong file. Let me just pull this over into the solution and inside the source directory. There we go.
01:53 Move it in there. Yes, please. And now we have index two. You notice that even though we've got debug in the other file, we can't access it here. So it's not been put in the global scope. It's just been put in the local scope, declared as a kind of local const here. So declare const is really nice
02:11 when you have global sort of floating around, let's say, you know, Google Analytics or something that's injected a script into the window that you just want to declare inside one file and have that just work. And this, I think, is a really nice introduction to how declare works and the idea of an ambient context. We're going to dive into this a lot more.