1
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でも使える!三項演算子(?:)をまとめ直してみた

Last updated at Posted at 2025-09-25

はじめに

React + Supabase でアプリを作っているときに、
「ある条件のときだけリンクを表示したい」という場面に出くわしました。

最初は if/else で書いていたのですが、三項演算子(?:) を思い出しました。

改めて三項演算子(?:)についてまとめ直したいと思います。

三項演算子とは?

書き方はシンプル:

条件 ? 真の場合の処理 : 偽の場合の処理

例:GitHub URL の場合分け
普通の if/else

let githubUrl;
if (user.github_id) {
  githubUrl = `https://github.com/${user.github_id}`;
} else {
  githubUrl = null;
}

三項演算子を使うと…

const githubUrl = user.github_id
  ? `https://github.com/${user.github_id}`
  : null;

JSX 内でも活躍

三項演算子は 表示・非表示の切り替え にも便利です。

{githubUrl ? (
  <a href={githubUrl} target="_blank">GitHub</a>
) : (
  <p>未登録</p>
)}

まとめ

少し忘れている文法もあったので改めて復習し直したいと思います。

1
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
1
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?