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?

【React × TypeScript】型安全に基準値を扱う!比較ロジックを安全設計する方法

Posted at

職場にあったら便利だなと思い開発を始めた「看護師向け計算ツールアプリ」。
今回は、基準値比較を型安全に行うTypeScriptロジックを紹介します。

要約

  • unknown で外部値を安全に受け取る
  • parseFloat + isNaN() で不正値を防止
  • compareValueToRange()"high" | "low" | "normal" を返す
  • 小規模なら型ガード、大規模入力ならZod等のスキーマ利用が◎

実装例

export type Range = { min: number; max: number; };

export const compareValueToRange = (value: unknown, range?: Range) => {
  if (!range) return "N/A";
  const numericValue = parseFloat(String(value));
  if (isNaN(numericValue)) return "invalid";
  if (numericValue > range.max) return "high";
  if (numericValue < range.min) return "low";
  return "normal";
};

📘 詳細な実装・スキーマ比較解説はZennで公開中👇
👉 【React × TypeScript】医療系アプリで学ぶ基準値UI設計③(Zenn)
(※Zenn版では設計背景や色覚対応の工夫も詳しく解説)

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?