Modules Scripts and Declaration Files 7 exercises

Typing a JavaScript Module

TypeScript doesn't automatically interpret the contents of JavaScript files. Instead, it needs a declaration file to describe the contents of the JavaScript file.

Here's our existing JavaScript module, that exports a function myFunc:

// example.js
export const myFunc = () => {
return "H

Loading solution


00:00 Okay, so let's create a declaration file that describes the contents of example.js. Now TypeScript won't by default try to go into this .js file and try to figure out what's in it and then figure out the modules.

00:16 It needs a declaration file to basically say this is what is in this .js file. So we're going to do that. We're going to go into this file and we're going to create an example.d.ts. It has to have exactly the same name, exactly the same casing. And I'll go back to my index.ts file to figure this out.

00:34 So because the thing that we're trying to describe is essentially a module, we also need our example.d.ts file to be a module. So let's add an export empty object there. Now this takes a little while to update, I think, and it might not even update.

00:49 So what I tend to do is I tend to just take a look at this and re-add the import just so it catches up. So now we're getting an error saying module example has no exported member myfunc.

01:01 So even though the .js file has something called myfunc exported from it, we're not actually describing that in the .d.ts file. So how do we do that? Well, we can say export function and then export function myfunc. And that is going to be a function that returns, what does it return?

01:19 It just returns a string here. And so export function myfunc, this is going to just return string. Copilot's wrong in this instance. And now you notice that inside our index.ts file, myfunc is just a function that returns a string. Beautiful.

01:35 Now this is so, so nice because it means now that although it won't stay in sync with our .js, so if we make it return a number, we'll also have to go into this and say that myfunc returns a number too. This means that the .d.ts gets to just sit next to the .js file and describe what's in it.

01:53 And you notice too that inside the source directory, it kind of gets grouped together. So you can see that the source here, it now has example.js and the example.d.ts, because they're related, get nested together. So this is a really nice way to basically describe JavaScript files in your project that, for instance,

02:12 maybe were auto-generated by script or, let's say, haven't been migrated across the TypeScript yet. And what we'll see is that this pattern is basically how you ship JavaScript files in NPM while still having them be compatible with your TypeScript project.