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?

TypeScript初心者がユニオン型とtype guardでコードを安全にする3つのコツ

0
Posted at

TypeScript を学び始めたばかりの人は、ユニオン型とtype guardの組み合わせが何に役立つのかイメージしにくいことが多いです。ここでは、実務でよく出てくる「API のレスポンスを安全に扱う」シナリオを例に、3 つのポイントに絞って解説します。

1. ユニオン型で「可能性」を明示する

たとえば、ユーザー情報を取得するエンドポイントは以下のような 2 通りの形を返すとします。

type UserSuccess = {
  ok: true
  data: { id: number; name: string }
}
type UserError = {
  ok: false
  error: string
}
type UserResponse = UserSuccess | UserError

UserResponse がユニオン型になることで、成功か失敗かは必ずどちらかであることが型レベルで保証されます。これだけでも、any で受け取るよりは格段に安全です。

2. type guard で「実際の形」を絞り込む

ユニオン型だけでは、コンパイラはどちらのプロパティが使えるか分かりません。そこで type guard を作ります。

function isUserSuccess(res: UserResponse): res is UserSuccess {
  return res.ok === true
}

res is UserSuccess と書くことで、isUserSuccess が true を返したときは res が UserSuccess 型であると確定させられます。

3. 絞り込み後は安心してプロパティへアクセス

実際の使用例です。

async function fetchUser(id: number) {
  const response: UserResponse = await api.get(`/users/${id}`)

  if (isUserSuccess(response)) {
    // ここは TypeScript が data が存在すると判断
    console.log(`User ${response.data.name} (ID:${response.data.id}) が取得できました`)
  } else {
    // エラーケースのハンドリング
    console.error(`取得失敗: ${response.error}`)
  }
}

if (isUserSuccess(response)) のブロックに入ると、response の型は自動的に UserSuccess に絞り込まれます。逆に else ブロックでは UserError とみなされ、error プロパティだけが利用可能です。

まとめ

  1. ユニオン型で可能性を表現 → 失敗と成功のどちらかが必ず来ることを型で示す
  2. type guard で実際の形を判定 → isX 関数で絞り込みを行う
  3. 絞り込み後は安全にプロパティへアクセス → コンパイル時にエラーが出にくくなる

この流れを覚えておけば、API の戻り値だけでなく、React の Props や Redux の state など、さまざまな場面で「安全なコード」を書く土台ができます。

詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

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?