Types You Don't Control 12 exercises

Should You Use Declaration Files to Store Your Types?

A common misconception in TypeScript projects is the belief that all type definitions should be put inside .d.ts files.

The assumption is that there should be a index.ts file for implementation and a types.d.ts file for types:

// index.ts
import { Example } from "./types";
type Examp

Loading explainer


00:00 A common pattern that I see a lot in TypeScript and TypeScript repos out in the wild is that people look at the .d.ts file extension and they think, ah, this is where I should put all of my types. So I should have two different files. I should have index.ts on the left

00:18 hand side here, where I'm actually have my implementation. And then on the right hand side, I have my .d.ts files, which is where I put my types. Now this is a mistake. This is not correct because .d.ts files, they're really about

00:34 making global alterations to the scope in TypeScript. That's their purpose. And they're all about, um, like they're an ambient context, which we've seen defined before that is basically global in nature. You can change that by adding an export as we've also seen, but this isn't

00:52 quite right. Now, I think this is just very, very common. This is just a common misconception that people have when they first get into TypeScript. This is where you should put your types. But in fact, what you should be doing is all of your files should be .ts files if

01:06 they're supposed to be modules. Now, I think like the reason for this is that first of all, we've got skip lib check true in most projects. This means that you should keep your .d.ts files down to a minimum to make sure that as much of your code is type checked

01:21 as possible. The second reason is that like I've asked the TypeScript team this, and they, they think they just don't understand why people would do this in the first place. This is not what d.ts files are for. .d.ts files are for making global alterations or for describing

01:37 JavaScript as we've seen. And so if you're doing this, I would recommend putting them immediately into just .ts files. You can just say, okay, I've got my .d.ts file here. I just changed the extension and now it's a .ts file. Bam. Has exactly the same syntax.

01:55 And if I get something wrong here, then it's actually going to warn me instead of if I had this as a .d.ts file, where it just wouldn't warn me. I just lose a whole bunch of errors and I'm referencing strig instead of string there. Grim. So make sure that if you spot

02:13 this in a project, convert them immediately into .ts files, unless you notice that they're doing anything kind of like global in there. And if you do see global stuff, sure, that's fine to live in a .d.ts file, but actual modules, nah, keep them in .ts files.