Types You Don't Control 12 exercises

Use Wildcards in TypeScript Module Declarations

Let's start by creating a png.d.ts file in the src directory since we need to put something in the global scope.

Then inside of the png.d.ts file, we'll declare a module named *.png.

Note that we can't use relative module names inside of the .d.ts file. Instead, we'll use a wildcard to

Loading solution


00:00 Okay, let's start by creating a .d.ts file because we need to put something in the global scope. So let's just say module.d.ts or maybe just png.d.ts, since that's what we're looking at. So inside here, we're gonna say declare module. And now declare module, we need to give it a module specifier. And so we could say declare module

00:19 and we could just go through all of the pngs here. So we could say, where are they? Example1.png, let's grab that and put that there. Does that even work? Ambient module cannot specify relative module name, yeah. So we can't actually do relative module names here. We could say if like example1.png,

00:38 like adding a sort of global thing here. But what we really need to do is to say for every single png, then we need to say, this returns or it exports a string as its default export. So we can actually add a wildcard into this declare module here.

00:56 And now what we'll see is the example.png, it's actually corresponding to module wildcard.png. And let's look at this and we actually go to our type definition here. Except png URL, it's currently just sort of nothing at the moment, basically. So we need to say what this module actually has on it.

01:15 Now, in order to say, okay, let's just say we, I'm not sure, we don't think we need to do declare const. Png is a string like this. Don't think we need to do that because you don't need to do a declare inside another declare. So we can just say const png is a string here. If we export this,

01:33 then it's gonna be exported as a named export. And so we've got png string from example1.png. This isn't correct. We actually want to export it as a default here. And so we can say export default png. So if we remove this const export,

01:53 now the only thing that's exported from here is a default export where it is string. So if we try to do anything else inside here, it's not gonna give us any options for named things to import here. And module like wildcard png has no exported member of url.

02:10 Did you mean to say import url from png instead? Fantastic. So now this is working as expected. And this is the lesson here. You can use these wildcards in declare module in order to basically declare other things which are not JavaScript files are very, very useful.