MeWrite Docs

TypeScript: Cannot augment module

TypeScriptでモジュール拡張が正しく機能しない場合のエラー原因と解決策

概要

既存のモジュールの型定義を拡張しようとした際に、正しく認識されないエラーです。

エラーメッセージ

``` error TS2339: Property ‘customField’ does not exist on type ‘Request’. ```

原因

  1. declare module の構文エラー: import/exportの欠落
  2. tsconfig.json の設定不足: typeRootsやincludeの問題
  3. ファイル拡張子の問題: .d.ts ファイルが認識されない
  4. モジュール解決の競合: 他の型定義との競合

解決策

1. 正しいモジュール拡張の書き方

```typescript // types/express.d.ts

// 重要: import または export が必要 import { User } from ‘../models/user’;

declare global { namespace Express { interface Request { user?: User; customField?: string; } } }

// 空のexportでモジュールとして認識させる export {}; ```

2. グローバル型の拡張

```typescript // types/global.d.ts declare global { interface Window { gtag: (…args: any[]) => void; dataLayer: any[]; } }

export {}; ```

3. tsconfig.json を設定

```json { “compilerOptions”: { “typeRoots”: ["./node_modules/@types", “./types”], “types”: [“node”, “express”] }, “include”: [“src//*”, “types//*”] } ```

4. ライブラリの型を拡張

```typescript // types/next-auth.d.ts import { DefaultSession } from ’next-auth’;

declare module ’next-auth’ { interface Session { user: { id: string; role: string; } & DefaultSession[‘user’]; } } ```

よくある間違い

  • export文を忘れてスクリプトファイルになる
  • declare moduleのパスが実際のモジュール名と異なる
  • typeRootsの設定漏れ

関連エラー

関連エラー

TypeScript の他のエラー

最終更新: 2025-12-10