概要
https://www.typescriptlang.org/tsconfig#declaration
{
"declaration": true
}
これをtrue
にすると、コンパイルした TS ファイルの中でexport
しているもの全ての型定義ファイルをファイルごとに作成します。
export
が一つもなくてもファイル自体は作成されます。
詳細
"declaration": true
.
├── index.ts
├── package-lock.json
├── package.json
├── src
│ ├── hoge.ts
│ └── piyo
│ ├── foo
│ │ └── foo.ts
│ └── piyo.ts
└── tsconfig.json
こういうディレクトリ構成だとして、index.ts
は、
export const func = async () => {
// Promiseにジェネリクスで型を渡さないと`resolve`の返り値が`unknown`になるので`string`渡す
return new Promise<string>((resolve) => {
setTimeout(() => {
resolve("5秒経ちました");
}, 5000);
});
};
const hoge = "hoge";
console.log("hoge");
で、その他の.ts
ファイルは空ファイルです。
この状態でコンパイル結果は下記("outDir": "./dist"
で、./dist
配下だけ表示)のようになります。
./dist/
├── index.d.ts
├── index.js
└── src
├── hoge.d.ts
├── hoge.js
└── piyo
├── foo
│ ├── foo.d.ts
│ └── foo.js
├── piyo.d.ts
└── piyo.js
// index.d.ts
export declare const func: () => Promise<string>;
index.js
のうち、func
の型定義が出力されています。
試しにindex.ts
のconst hoge = ~~~
をexport
してからコンパイルすると、
export const func = async () => {
return new Promise<string>((resolve) => {
setTimeout(() => {
resolve("5秒経ちました");
}, 5000);
});
};
export const hoge = "hoge";
結果は下記のようになります。
// index.d.ts
export declare const func: () => Promise<string>;
export declare const hoge = "hoge";
export
したので型定義ファイルの出力対象になっていますね。
空の TS ファイルの型定義ファイルは空ファイルになります。