TypeScript

Inertia は TypeScript を第一級でサポートしています。宣言マージによってグローバル型を設定したり、フックやルーターメソッドにジェネリクスを渡すことで、props・フォーム・状態管理を型安全に扱えます。

pnpm の使用

pnpm の厳格な依存関係分離により、@inertiajs/corenode_modules/@inertiajs/core からは参照できません。代わりに .pnpm/ 内にネストされるため、TypeScript のモジュール拡張がモジュールを解決できなくなります。

これを解決するには、pnpm を設定して パッケージを hoist してください。.npmrc ファイルに以下を追加し、pnpm install を実行します。

ini
public-hoist-pattern[]=@inertiajs/core

または、@inertiajs/core をプロジェクトの直接依存関係として追加することもできます。

bash
pnpm add @inertiajs/core

グローバル設定

@inertiajs/core モジュール内の InertiaConfig インターフェースを拡張することで、Inertia の型をグローバルに設定できます。これは通常、プロジェクトのルートや types ディレクトリにある global.d.ts ファイルで行います。

ts
// global.d.ts
declare module "@inertiajs/core" {
  export interface InertiaConfig {
    sharedPageProps: {
      auth: { user: { id: number; name: string } | null };
      appName: string;
    };
    flashDataType: {
      toast?: { type: "success" | "error"; message: string };
    };
    errorValueType: string[];
  }
}

共有ページ Props

sharedPageProps オプションは、アプリケーション内のすべてのページで共有されるデータの型を定義します。この設定により、page.props.authpage.props.appName はどこでも正しく型付けされます。

ts
sharedPageProps: {
    auth: { user: { id: number; name: string } | null }
    appName: string
}

フラッシュデータ

flashDataType オプションは、アプリケーション内のフラッシュデータの型を定義します。

ts
flashDataType: {
    toast?: { type: 'success' | 'error'; message: string }
}

エラー値

デフォルトでは、バリデーションエラーの値は string として型付けされます。1 フィールドに複数のエラーを扱うために、配列を期待するよう TypeScript を設定することもできます。

ts
errorValueType: string[]

ページコンポーネント

ページコンポーネントを解決する際の型安全性を高めるために、import.meta.glob の結果に型を付けることができます。

ページ Props

usePage() にジェネリクスを渡すことで、ページ固有の props に型を付けられます。これらはグローバルな sharedPageProps とマージされ、共有データとページ固有データの両方に対してオートコンプリートと型チェックが有効になります。

フォームヘルパー

フォームヘルパーは、型安全なフォームデータとエラー処理のためにジェネリック型パラメータを受け取ります。これにより、フォームフィールドやエラーに対するオートコンプリートが提供され、フィールド名のタイプミスを防げます。

ネストされたデータと配列

フォームの型は、ネストされたオブジェクトや配列を完全にサポートします。ドット記法を使用してネストされたフィールドにアクセス・更新でき、エラーキーも自動的に一致するよう型付けされます。

ts
import { useForm } from "@inertiajs/react";

const form = useForm<{
  user: { name: string; email: string };
  tags: { id: number; label: string }[];
}>({
  user: { name: "", email: "" },
  tags: [],
});

状態の記憶

useRemember フックは、型安全なローカル状態の永続化のためにジェネリック型パラメータを受け取ります。これによりオートコンプリートが提供され、値が期待される型と一致することが保証されます。

状態の復元

router.restore() メソッドは、履歴から復元される状態に型を付けるためのジェネリックを受け取ります。

ts
import { router } from "@inertiajs/react";

interface TableState {
  sortBy: string;
  sortDesc: boolean;
  page: number;
}

const restored = router.restore<TableState>("table-state");

if (restored) {
  console.log(restored.sortBy);
}

ルーターリクエスト

ルーターメソッドは、送信されるデータに対する型チェックを提供するため、リクエストデータに型を付けるジェネリックを受け取ります。

ts
import { router } from "@inertiajs/react";

interface CreateUserData {
  name: string;
  email: string;
}

router.post<CreateUserData>("/users", {
  name: "John",
  email: "john@example.com",
});

スコープ付きフラッシュデータ

router.flash() メソッドは、グローバルな flashDataType 設定とは別に、ページまたはセクション固有のフラッシュデータに型を付けるためのジェネリックを受け取ります。

ts
import { router } from "@inertiajs/react";

router.flash<{ paymentError: string }>({ paymentError: "Card declined" });

クライアントサイド遷移

router.push() および router.replace() メソッドは、クライアントサイド遷移の props に型を付けるためのジェネリックを受け取ります。

ts
import { router } from "@inertiajs/react";

interface UserPageProps {
  user: { id: number; name: string };
}

router.push<UserPageProps>({
  component: "Users/Show",
  url: "/users/1",
  props: { user: { id: 1, name: "John" } },
});

router.replace<UserPageProps>({
  props: (current) => ({
    ...current,
    user: { ...current.user, name: "Updated" },
  }),
});