15
4

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学習ログ No.8

Posted at

React公式ドキュメント学習メモ:TypeScript の使用

React開発におけるTypeScriptの価値

TypeScript(TS)は、JavaScriptコードベースに型定義を追加
React開発においては、実行前にPropsのミスやStateの不整合といったバグを検出し、開発の安全性を劇的に向上

  • TSのサポート: TSはJSXを標準でサポートしており、@types/react@types/react-dom を追加することで、React Webに対する完全な型サポートが得られる
  • ファイル拡張子: JSXを含むファイルは、必ず .tsx 拡張子を使用する必要

1. コンポーネントへの型付け:Propsの定義

コンポーネントを扱う際の主な違いは、Propsに型を指定すること

1-1. interface または type でPropsを定義する(推奨)

複数のフィールドがある場合、インラインではなく interface または type を使用する

interface MyButtonProps {
  /** The text to display inside the button */
  title: string;
  /** Whether the button can be interacted with */
  disabled: boolean;
}

// 関数の引数に型を適用
function MyButton({ title, disabled }: MyButtonProps) { /* ... */ }

2. Hooksの型付けパターン

@types/react に含まれる型定義により、
組み込みフックは追加設定なしで使用可能だが、より厳密な型付けの例

2-1. useState の型付け

パターン コード例 ポイント
自動推論 const [enabled, setEnabled] = useState(false); 初期値があれば boolean 型を自動で推論
ユニオン型 const [status, setStatus] = useState<Status>("idle"); type Status = "idle" | "loading" | ... のように、取りうる値を限定するユニオン型を <Status> で明示的に指定
構造化 State const [state, setReq] = useState<RequestState>({ status: 'idle' }); status の値によってオブジェクトの構造(データやエラーの有無)が変わる判別可能ユニオン型を適用し、安全なデータアクセスを保証

2-2. useReducer の型付け

複雑な状態管理では、StateとActionの型を明確に分離

  1. interface State: リデューサーの State の構造を定義
  2. type CounterAction: ディスパッチできるアクション({ type: "reset" } など)の型をユニオン型で定義
  3. リデューサー関数の型: function stateReducer(state: State, action: CounterAction): State のように、引数と戻り値に型を適用することで、リデューサー関数全体を型安全にする

2-3. useContext の型付けと null 回避

createContext のデフォルト値に意味のある値がない場合、
型に ContextShape | null を指定する必要

  • 推奨パターン: useContext を使用するカスタムフックを作成し、
    フック内で if (!object) { throw new Error(...) } のチェックを行うことで、
    利用側で | null の可能性を排除し、安全に値を利用できるようにする

3. その他の便利な型(@types/react から)

Reactの型定義パッケージには、開発を強力にサポートする便利な型が含まれる

用途 TypeScriptの型 備考
子要素(汎用) React.ReactNode JSXで子として渡せるすべての型(要素、文字列、数値など)を許可。最も包括的
子要素(JSXのみ) React.ReactElement JSX要素のみを指し、文字列や数値は含まない
DOMイベント React.ChangeEvent<HTMLInputElement> 特定のDOM要素(<HTMLInputElement>)に対するイベントハンドラの型を定義。useCallback と組み合わせる際に特に有用
インラインスタイル React.CSSProperties style プロパティに渡すオブジェクトの型。有効なCSSプロパティのみを許可し、自動補完を可能にする
15
4
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
15
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?