iTranslated by AI
Essential Knowledge for Using .d.ts Files Correctly
.d.ts files are what are known as declaration files (type definition files) in TypeScript. Unfortunately, I sometimes see .d.ts files being used in incorrect ways. Therefore, in this article, I will explain the knowledge necessary to use .d.ts files correctly.
What is a .d.ts file?
Regarding .d.ts files, please start by reading the following explanation from the official TypeScript blog (quoted from Announcing TypeScript 5.5).
Declaration files (a.k.a. .d.ts files) describe the shape of existing libraries and modules to TypeScript. This lightweight description includes the library’s type signatures and excludes implementation details such as the function bodies. They are published so that TypeScript can efficiently check your usage of a library without needing to analyse the library itself. Whilst it is possible to handwrite declaration files, if you are authoring typed code, it’s much safer and simpler to let TypeScript generate them automatically from source files using --declaration.
Japanese translation (from original article): Declaration files (.d.ts files) describe the shape of existing libraries and modules to TypeScript. This is a lightweight description that includes the library's type signatures but excludes implementation details such as function bodies. By publishing .d.ts files, TypeScript can efficiently check your usage of a library without needing to analyze the library itself. While it is possible to hand-write declaration files, if the code you are writing is typed (Translator's note: writing TypeScript instead of JavaScript), it is much safer and simpler to let the TypeScript compiler automatically generate .d.ts files from source files using the --declaration option.
As a side note, various AI "Deep Research" features are very useful for finding where such official explanations are located. Especially for TypeScript, important insights are often briefly mentioned in "Announcing TypeScript" blog posts, or critical explanations might not be found unless you look at GitHub.
When are .d.ts files used?
Currently, the most common scenario where .d.ts files are used, as mentioned in the explanation above, is when code written in TypeScript is compiled into JavaScript and distributed via npm, etc. For example, consider a project with the following structure:
src
├── index.ts
└── utils.ts
If you compile this with TypeScript and also output .d.ts files, the output will look like this:
dist
├── index.js
├── index.d.ts
├── utils.js
└── utils.d.ts
Then, you publish the contents of this dist directory as a package to npm. This allows library users to obtain the library's type information through the .d.ts files.
In this case, the .d.ts files are artifacts of the compiler and are not written by hand. This is what the official explanation means by "if you are authoring typed code, it’s much safer and simpler to let TypeScript generate them automatically... using --declaration." If the original source code is TypeScript, there is no need to write .d.ts files by hand.
In other words, the "incorrect usage" I mentioned at the beginning refers to situations where someone is writing .d.ts files by hand in a TypeScript project.
Incorrect usage of .d.ts files
In my view, because .d.ts files are also known as "type definition files," there is a misunderstanding that all type definitions should be written in .d.ts files.
// "It's a user type definition, so let's put it in src/types/user.d.ts!" (Misconception)
export interface User {
id: string;
name: string;
email: string;
// ...
}
In this case, there is no need to create a .d.ts file. If it's a TypeScript project, you can just write the type definitions in a .ts file. In this example, src/types/user.ts is fine (regardless of whether the directory structure is ideal).
The significance of a .d.ts file's existence
For instance, if a file named src/foo.d.ts exists in a project, the TypeScript compiler recognizes it as the "type definition for src/foo.js." Originally, a .d.ts file was meant to be the type definition for a .js file with the same name. Looking at the dist directory example again, the .js and .d.ts files are indeed paired.
dist
├── index.js
├── index.d.ts
├── utils.js
└── utils.d.ts
Conversely, the basic principle is that it is abnormal for a .d.ts file to exist without a corresponding .js file.
For example, if you have src/types/user.d.ts as mentioned before, the code using the User type would import it like this:
import type { User } from './types/user';
const user: User = {
id: "123",
name: "John Doe",
email: "john.doe@example.com"
};
Actually, you can also write the import as follows. Because user.d.ts exists, TypeScript assumes the file is a type definition for user.js. The previous ./types/user is also treated as if the .js extension was omitted.
import type { User } from './types/user.js';
Particularly in Node.js ESM environments (module: "nodenext"), where extensions cannot be omitted in import declarations, you must explicitly write .js.
In any case, if such an "import for a non-existent file" accidentally persists into the runtime, it could cause runtime errors.
Aside
Actually, since TypeScript 5.0, it has been possible to import .d.ts files using import type.
import type { User } from './types/user.d.ts';
This contradicts the earlier explanation that ".d.ts files are type definitions for .js files." This syntax explicitly handles the existence of the .d.ts file itself.
Personally, I thought it would be better if this weren't allowed, so I researched why it is permitted. The reason is explained in the following comment:
According to this, it was motivated by convenience in use cases that span multiple projects, such as with Project References.
Type Definitions Used Throughout the Project
Sometimes type definitions like "project-wide type definitions" are written in files like types.d.ts. To begin with, directory design should be improved to place type definitions in appropriate locations, but I'll set that aside for now.
Even in cases like this, there is no need to use a .d.ts file.
As many of you might know, if you have such a src/types.d.ts, simply defining the types without exporting them makes those types available in all files.
// src/types.d.ts
interface User {
id: string;
name: string;
email: string;
// ...
}
// src/index.ts
// The User type can be used without importing!
const user: User = {
id: "123",
name: "John Doe",
email: "john.doe@example.com"
};
This is sometimes misunderstood as being an effect of the .d.ts file, but it actually has nothing to do with it. Even if you change src/types.d.ts to src/types.ts, the types will still be available in all files in the same way.
// src/types.ts
interface User {
id: string;
name: string;
email: string;
// ...
}
// src/index.ts
// The User type can be used without importing!
const user: User = {
id: "123",
name: "John Doe",
email: "john.doe@example.com"
};
The reason for this is that TypeScript distinguishes source files like .ts into scripts and modules, and the scope of a script is the global scope. In this case, src/types.ts is treated as a script, and because the User type is defined in the global scope, it can be referenced from other files.
Using declare global
There is a caveat to the discussion above. That is when the TypeScript options are set for Node.js, such as module: "nodenext".
Under this setting, if "type": "module" is specified in package.json, TypeScript treats all .ts files as modules. This means src/types.ts also becomes a module, so you cannot define types in the global scope.
Furthermore, there is a problem even if "type": "module" is not specified. In the case of module: "nodenext", the default value of the moduleDetection compiler option becomes force. If this option is set, all .ts files are handled as modules anyway.
Thus, in settings for Node.js, a double mechanism is at work to treat all files as modules.
In such environments, you can still define types in the global scope from a .ts file by using the declare global syntax.
// src/types.ts
declare global {
interface User {
id: string;
name: string;
email: string;
// ...
}
}
// src/index.ts
// The User type can be used without importing!
const user: User = {
id: "123",
name: "John Doe",
email: "john.doe@example.com"
};
Also, declare global can be used even when types.ts contains import declarations. TypeScript does not treat files containing import declarations as scripts. In that case, you must use declare global to define types in the global scope from types.ts.
// src/types.ts
import type { UserId } from './id';
declare global {
interface User {
id: UserId;
name: string;
email: string;
// ...
}
}
.d.ts files and modules
Actually, .d.ts files are treated as scripts if they satisfy the traditional conditions (the file contains no imports or exports), even when "type": "module" is written in package.json or the moduleDetection option is set to force. In cases where global types could not be defined in src/types.ts, you can define global types if the content is the same but you rename the file to src/types.d.ts.
Therefore, in cases where you want to use .d.ts as a signal representing "it is a script, not a module," .d.ts is indeed convenient.
However, in this case, you can just use the aforementioned declare global, so there is also the option of not using .d.ts.
In the Case of Ambient Module Declarations
For example, if you are configuring a bundler to allow importing image files, you will need a module declaration (ambient module declaration) like the following:
declare module '*.png' {
const value: string;
export default value;
}
There are cases where such declarations are written in .d.ts files. However, just like with global type definitions, it is perfectly fine to write them in a .ts file as long as the file is treated as a script.
// src/pngs.ts
declare module '*.png' {
const value: string;
export default value;
}
// src/index.ts
// You can import png files!
import logo from './logo.png';
Therefore, fundamentally, there is no need to use a .d.ts file here either, but there is one exception. That is the case of moduleDetection: "force" mentioned earlier. In this case, since all .ts files are treated as modules, writing declare module '*.png' in a .ts file will cause an error.
Error details
The error that occurs in this case is as follows:
Invalid module name in augmentation, module '*.png' cannot be found.
If you want to know more about what this means, I recommend this article.
Actually, ambient module declarations cannot be written inside declare global. Therefore, in this case, you must prepare a .d.ts file to write it.
// src/pngs.d.ts
declare module '*.png' {
const value: string;
export default value;
}
Aside: About .d.ext.ts files
Actually, hidden in the shadow of .d.ts files, there are also .d.ext.ts files (where "ext" can be any extension). These are for providing type definitions for files with specific extensions.
For example, to provide type definitions for a specific .css file, you can create a file named styles.d.css.ts.
/* styles.css */
.foo {
color: red;
}
.bar {
color: blue;
}
// styles.d.css.ts
const styles: {
foo: string;
bar: string;
};
export default styles;
Users can import it like this:
import styles from './styles.css';
console.log(styles.foo);
console.log(styles.bar);
However, to import files other than .js or .ts in this manner, you need to enable TypeScript's allowArbitraryExtensions option.
Comparison with the Traditional Method
Previously, to provide type definitions for styles.css and import it, there was a method of creating a file named styles.css.d.ts (note the difference in the order of extensions).
// styles.css.d.ts
declare const styles: {
foo: string;
bar: string;
};
export default styles;
// It can be loaded!
import styles from './styles.css';
However, this method involved a kind of trickery. In fact, with this method, TypeScript assumes it is loading a file named styles.css.js. The .js extension is being omitted.
Remember the principle: "A .d.ts file is a type definition for a .js file of the same name." Following this principle, TypeScript recognizes styles.css.d.ts as the type definition for styles.css.js.
In contrast, styles.d.css.ts explicitly represents that it is a type definition for styles.css. It is not treated as if .js were omitted.
Traditional .d.ts files could only represent type definitions for .js files. The .d.ext.ts files were introduced to supplement this. Thinking about it this way, it makes sense that the allowArbitraryExtensions option was added simultaneously with the .d.ext.ts feature.
Particularly in Node.js ESM environments where extensions cannot be omitted, you cannot import styles.css unless the allowArbitraryExtensions option is enabled.
Summary
In this article, I explained the correct usage of .d.ts files and common misconceptions.
Since the original meaning of a .d.ts file is to represent type definitions for existing JS files, using them for other purposes should generally be avoided.
However, .d.ts files possess unique and convenient behaviors that cannot be replaced by .ts files. Especially in Node.js ESM environments or environments where moduleDetection: "force" is set, you may find yourself relying on these behaviors.
- When you want to define types in the global scope (can also be replaced by
declare global) - When making ambient module declarations (cannot be replaced by
declare global)
Reference Links
The content of this article overlaps with the following article. However, since I still see misconceptions even after that article was published, I decided to write an article about it as well.
Discussion