Declaration Files Can Be Modules or Scripts
TypeScript declaration files allows them to be treated either as modules or scripts.
Consider the index.ts
file which imports AvailableViaImport
from treated-as-module.d.ts
, while also using GloballyAvailable
without importing it:
## index.ts
import { Equal, Expect } from "@total-t
Transcript
00:00 We've talked about declaration files and we've talked about modules versus scripts. And it turns out that you can treat declaration files as either modules or as scripts. So if we look here, we have an index.ts file, which is up the top and down the bottom now, which basically says we're importing from a file called treated as module.
00:19 And in here, we have a treated as module.d.ts. And in another file, we have a treated as script.d.ts. Now, as in treated as script.d.ts, this globally available type is globally available.
00:33 So inside my index.ts file, I can say type example equals globally available and bam, it's available to me. Nice. Available via autocomplete, available in all files because it's being treated as a script.
00:45 And you notice here too that we have a tsconfig.json, which is currently the module detection is set to force. But this only applies to .ts and .tsx files. This doesn't apply to declaration files.
01:00 Because declaration files, they always need to be able to either access the global scope or access the module scope. So where are we? Back to now treated as module.d.ts. Now inside here, this operates slightly differently to TypeScript.
01:17 I actually learned this while I was writing this exercise. This is bizarre. If we remove this export empty object, then this not available by import, which we're not exporting from this file, is actually weirdly available via an import.
01:33 Okay, even though we're not exporting it, I'm not entirely sure why this happens. I'm actually waiting for some feedback from the TS team on that. But if we add an export empty object here, then not available by import will actually not be available via import.
01:50 So adding an export empty object is a way to say to TypeScript, this d.ts file is in fact a module, not a script. And so this can be useful if you want to store your TypeScript types somewhere. But I'd actually recommend not doing that. And we'll get to that in a minute, I think.
02:09 So this is a crucial piece of information to realize is that by default, if you don't add an export empty object here, then your types in a d.ts file will be globally available. Otherwise, if you do add one, then it will obey the normal export and import rules.