見出し画像

【ワンピースで覚えるTypeScript】第21回 型の絞り込み(JavaScript学習者向け)

今回は型の絞り込みについて解説します。

特に、typeof演算子はとても使えるので状況に応じて利用していきましょう!!


type hasAbility = "yes" | "no";

function searchAbility(type: hasAbility){
  return type == "yes" ? "能力者!" : "能力者でない";
}
//引数の型は "yes" | "no" | "unknown"
function CharacterHasAbility(type: hasAbility | "unknown"){
  if(type === "unknown"){
    return "不明";
  } else {//以下では "unknown"の可能性がない
    return searchAbility(type);
  } //=>type: hasAbility だけになっている
}
//位置によって、型が変化する=型の絞り込み

//typeof演算子
console.log(typeof "luffy");
// => "string"
console.log(typeof 19);
// => "number"

function Bounty(value: string | number){
  if(typeof value === "number" ){
    return `${value.toFixed(0)}ベリー`;
  } else {
    return `${value}ベリー`;
  }
}
console.log(Bounty("1000"));
console.log(Bounty(50.111));

//switch文
type AbilityPerson = {
  devil_fruits: "yes";
  ability: string;
}

type Person = {
  devil_fruits: "no";
  name: string;
}

type Character = AbilityPerson | Person;
function GetName(chara: Character): string {
  switch (chara.devil_fruits){
    case "yes":
      return "名前は不明の能力者";
    case "no":
      return chara.name;
  }
}
const nami: Person = {
  devil_fruits: "no",
  name: "ナミ"
}
console.log(Ge

この記事が気に入ったらサポートをしてみませんか?