🔄 TypeScript のクラスの import / export

TypeScript では、クラスを別ファイルに分けて import / export を使って管理できます。

✅ クラスを export(エクスポート)する

Animal.ts

export class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  speak(): void {
    console.log(`${this.name} が鳴いています`);
  }
}

✅ クラスを import(インポート)する

main.ts

import { Animal } from './Animal';

const dog = new Animal("ポチ");
dog.speak(); // ポチ が鳴いています

📦 export default の使い方

Cat.ts

export default class Cat {
  meow(): void {
    console.log("にゃーん");
  }
}

main.ts

import Cat from './Cat';

const cat = new Cat();
cat.meow(); // にゃーん

💡 補足ポイント

🛠 tsconfig.json の例

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext", 
    "moduleResolution": "node",
    "outDir": "dist",
    "rootDir": "src"
  }
}

✅ import/export まとめ

操作方法
クラスのエクスポートexport class クラス名 {}
デフォルトエクスポートexport default クラス名
インポートimport { クラス名 } from 'パス'
デフォルトインポートimport 任意名 from 'パス'