記事一覧に戻る

TypeScriptのユーティリティ型を使いこなす(モック)

Partial、Pick、Omitなど、TypeScriptの便利なユーティリティ型の使い方を実例と共に解説します

TypeScriptフロントエンド型システム

はじめに

TypeScriptには、既存の型を変換して新しい型を作成するためのユーティリティ型が組み込まれています。これらを活用することで、コードの重複を減らし、型安全性を高めることができます。

よく使うユーティリティ型

Partial<T>

すべてのプロパティをオプショナルにします。

interface User {
  id: number
  name: string
  email: string
}

// すべてのプロパティがオプショナルに
type PartialUser = Partial<User>

// 更新時に一部のプロパティだけ渡せる
function updateUser(id: number, updates: Partial<User>) {
  // ...
}

updateUser(1, { name: '新しい名前' }) // OK

Pick<T, K>

指定したプロパティだけを抽出します。

interface Article {
  id: number
  title: string
  content: string
  author: string
  createdAt: Date
}

// titleとauthorだけを持つ型
type ArticlePreview = Pick<Article, 'title' | 'author'>

const preview: ArticlePreview = {
  title: 'TypeScript入門',
  author: 'John'
}

Omit<T, K>

指定したプロパティを除外します。

// idとcreatedAtを除外した型(新規作成時に便利)
type CreateArticleInput = Omit<Article, 'id' | 'createdAt'>

const newArticle: CreateArticleInput = {
  title: '新しい記事',
  content: '本文...',
  author: 'Jane'
}

Record<K, T>

キーの型と値の型を指定してオブジェクト型を作成します。

type Status = 'pending' | 'approved' | 'rejected'

// 各ステータスに対応するラベルを定義
const statusLabels: Record<Status, string> = {
  pending: '審査中',
  approved: '承認済み',
  rejected: '却下'
}

実践的な活用例

APIレスポンスの型定義

interface ApiResponse<T> {
  data: T
  status: number
  message: string
}

// ユーザー一覧のレスポンス
type UsersResponse = ApiResponse<User[]>

// 単一ユーザーのレスポンス
type UserResponse = ApiResponse<User>

フォームの状態管理

interface FormData {
  username: string
  email: string
  password: string
}

// フォームの各フィールドにエラーメッセージを持たせる
type FormErrors = Partial<Record<keyof FormData, string>>

const errors: FormErrors = {
  email: 'メールアドレスの形式が不正です'
}

まとめ

ユーティリティ型を使うことで:

  • コードの重複を削減できる
  • 型の意図が明確になる
  • 保守性が向上する

最初は難しく感じるかもしれませんが、少しずつ使っていくことで自然と身につきます。

motokifujino.com

This site is made by motoki fujino, Icons by Lucide.