条件分岐 型ガード

TypeScriptでは型システムと連携した安全な分岐処理が可能です。


🛡️ 型安全な条件分岐(Type Guards)

1. typeof 型ガード

function handleInput(input: string | number) {
  if (typeof input === 'string') {
    console.log(input.toUpperCase());
  } else {
    console.log(input.toFixed(2));
  }
}

2. in 型ガード

type Cat = { meow: () => void };
type Dog = { bark: () => void };

function speak(animal: Cat | Dog) {
  if ('meow' in animal) {
    animal.meow();
  } else {
    animal.bark();
  }
}

3. カスタム型ガード関数

type Fish = { swim: () => void };
type Bird = { fly: () => void };

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim();
  } else {
    pet.fly();
  }
}

⛔ 非推奨:any 型と条件分岐

function unsafeCheck(value: any) {
  if (value > 10) {
    console.log("大きい");
  }
  // any型では型安全が失われる
}

🧩 条件型(Conditional Types)との違いに注意!

type Message
<T> = T extends string ? "text" : "binary";

// 使用例
type A = Message
<string>;  // "text"
type B = Message
<Uint8Array>; // "binary"

条件型は型レベルの条件分岐であり、実行時分岐とは別物です。

コメントを残す 0

Your email address will not be published. Required fields are marked *