【TypeScrpt】定義した型ガード関数で絞り込む方法
TypeScript

【TypeScrpt】定義した型ガード関数で絞り込む方法

作成日:2022年05月14日
更新日:2022年05月14日

以前、ユニオン型で型の内容を絞り込む方法を紹介しました。

tsx
type Walk = {
type: "onFoot";
walkSpeed: number;
};
type Car = {
type: "transfer";
carSpeed: number;
};
type Move = Walk | Car;
function App() {
const transportation = (move: Move) => {
if (move.type === "onFoot") {
return `徒歩は、時速${move.walkSpeed}kmです`;
}
if (move.type === "transfer") {
return `車は、時速${move.carSpeed}kmです`;
}
};
const speed = transportation({ type: "onFoot", walkSpeed: 4 });
return <>{speed}</>;
}
export default App;

どの場合に Walk や Car に切り替えるかを型ガード関数を使用することで、コードが読み取りやすくなります。

型ガード関数は、Walk の場合と Car の場合で、戻り値を boolean 型にします。

tsx
function isWalk(move: Move): move is Walk {
return move.type === "onFoot";
}
function isCar(move: Move): move is Car {
return move.type === "transfer";
}

条件文を書き換えましょう。

tsx
const transportation = (move: Move) => {
if (isWalk(move)) {
return `徒歩は、時速${move.walkSpeed}kmです`;
}
if (isCar(move)) {
return `車は、時速${move.carSpeed}kmです`;
}
};

ブラウザを確認すると、

image2

意図した内容が表示されました。

© 2024あずきぱんウェブスタジオ