7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptのフロントエンドとバックエンドでの使い方

Last updated at Posted at 2024-10-21

TypeScriptは、JavaScriptに型を付与することで開発効率を向上させ、バグを減らす目的で広く使われています。この記事では、フロントエンドとバックエンドそれぞれでのTypeScriptの使い方と具体例について紹介します。

TypeScriptを使う理由についてはこちらで記事にしていますので気になるかたは是非読んでみてください!

1. フロントエンドでのTypeScriptの使い方

フロントエンドの開発では、ReactやAngularなどのフレームワークと一緒にTypeScriptを使うことが多いです。

1.1 ReactとTypeScriptの連携
Reactでは、コンポーネントの型定義を行うことで、プロパティ(props)や状態(state)のバグを防ぐことができます。

Reactの基本的なコンポーネント例

import React, { useState } from 'react';

// propsの型定義
type CounterProps = {
  initialCount: number;
};

const Counter: React.FC<CounterProps> = ({ initialCount }) => {
  const [count, setCount] = useState<number>(initialCount);

  return (
    <div>
      <p>現在のカウント: {count}</p>
      <button onClick={() => setCount(count + 1)}>増やす</button>
    </div>
  );
};

export default Counter;

ポイント
React.FC: Functional Componentの型です。
useState: useStateフックに型を指定することで、状態管理を型安全に行います。

1.2 フロントエンド開発でのメリット
開発中のエラー検出: 型エラーが早期にわかるため、バグを防止できます。
IDEの補完機能の強化: 型定義によって、エディタがプロパティや関数の補完を行ってくれます。
コードの可読性向上: コンポーネントのインターフェースが明確になるため、チーム開発での理解が容易です。

2. バックエンドでのTypeScriptの使い方

バックエンドの開発では、Node.jsの環境でTypeScriptを使用することで、サーバーサイドのロジックも型安全に構築できます。

2.1 ExpressでのTypeScriptの使用例
ExpressはNode.jsの軽量フレームワークであり、TypeScriptと組み合わせることで、APIのエンドポイントも型安全に設計できます。

Expressのサンプルコード

import express, { Request, Response } from 'express';

const app = express();
const PORT = 3000;

// ユーザー情報の型定義
interface User {
  id: number;
  name: string;
  email: string;
}

// ダミーのユーザーデータ
const users: User[] = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' },
];

// エンドポイントの定義
app.get('/users', (req: Request, res: Response) => {
  res.json(users);
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

ポイント
interface: データ構造の型定義。APIのレスポンスに使用する型を明確にします。
RequestとResponse: Expressのリクエストとレスポンスの型を指定することで、正確なAPI設計が可能です。

2.2 バックエンド開発でのメリット
API設計の一貫性: 型定義により、エンドポイント間でのデータのやり取りが一貫します。
メンテナンス性向上: 大規模なプロジェクトでも型定義により、関数やデータ構造の管理が容易になります。
セーフティネットの提供: ランタイムエラーを未然に防げるため、サーバーの信頼性が向上します。

3. フロントエンドとバックエンド間の型共有

TypeScriptを使うことで、フロントエンドとバックエンドで型定義を共有することも可能です。これにより、APIのリクエストやレスポンスのデータ構造が一貫し、開発効率が向上します。

型定義を共有する方法
共通の型定義ファイルを作成します。
フロントエンドとバックエンドで同じ型定義を使用するため、sharedディレクトリなどに配置します。
例:型定義の共有

// shared/types.ts
export interface User {
  id: number;
  name: string;
  email: string;
}

フロントエンドでの使用例:

import { User } from '../shared/types';

const fetchUsers = async (): Promise<User[]> => {
  const response = await fetch('/users');
  return response.json();
};

バックエンドでの使用例:

import { User } from '../shared/types';

const users: User[] = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
];

4. まとめ

TypeScriptは、フロントエンドとバックエンドの両方で使うことで、以下のような多くのメリットをもたらします:

型安全性により、エラーの予防とバグの削減。
開発効率の向上とコード補完の強化。
型の共有による一貫性のあるAPI設計。
フロントエンドではReactなどのフレームワークで、バックエンドではExpressやNestJSと組み合わせて使用することで、TypeScriptの強力な機能を最大限に活用できます。

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?