0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Typescript] 複雑なtypeを分解する

Last updated at Posted at 2024-04-03

はじめに

型を分解して定義することのメリットは以下の通りです:

  1. 可読性の向上: 型が単純化され、各型の責務が明確になるため、コードの読みやすさが向上します。
  2. 再利用性の向上:分解されたtypeは他のコンテキストでも再利用しやすくなります。
  3. メンテナンスの容易さ: 型が分割されていると、特定の部分の変更が他の部分に影響を与えにくくなり、メンテナンスが容易になります。

Typescript初めての方下記がおすすめです。

以下の例を考えてください。どうtypeを定義しますか?

example.ts
const user = {
  id: 1,
  name: "Alice Johnson",
  contact:{
    phone: "080-8466-5622",
    email: "alice.johnson@example.com",
  },
  posts: [
    {
      id: 101,
      title: "My First Post",
      content: "This is the content of my first post.",
      comments: [
        {
          id: 1001,
          content: "Great post!",
          author: "Bob Smith",
        },
        {
          id: 1002,
          content: "Thanks for sharing.",
          author: "Charlie Davis",
        },
      ],
    },
  ],
};

実装

下記に定義してみたところ、読みにくいですね。

types.d.ts
type User = {
  id: number;
  name: string;
  contact: {
    phone: string;
    email: string;
  };
  posts: {
    id: number;
    title: string;
    content: string;
    comments: {
      id: number;
      content: string;
      author: string;
    }[];
  }[];
};

慣習としてはtypesを「.d.ts」ファイルで定義します

分解して定義すれば読みやすくなります。

types.d.ts
type User = {
  id: number;
  name: string;
  contact: Contact; // Contact typeを利用する
  posts: Post[]; // Post typeを利用する
};

type Contact = {
  phone: string;
  email: string;
};

type Post = {
  id: number;
  title: string;
  content: string;
  comments: Comment[]; // Comment typeを利用する
};

type Comment = {
  id: number;
  content: string;
  author: string;
};

まとめ

この記事では、TypeScriptで複雑なオブジェクトの型を定義する方法について説明しました。具体的なユーザー情報の例を通じて、ネストされたオブジェクトや配列を含む型の定義方法を見てきました。最初に示した一つの大きなUser型は、読みにくさと管理の難しさを示しています。これを改善するために、Contact、Post、Commentといった個別の型に分解し、User型の中でこれらを参照する方法を紹介しました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?