You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript扩展Inertia-JS接口时是否需要重写所有继承属性?

问题核心

你的实现存在冗余,不需要重新引入原接口的所有属性,Inertia提供的Page接口本身预留了SharedProps泛型参数,专门用于扩展自定义props属性,直接使用泛型传入你的自定义属性即可,无需重写原有属性定义。

原写法存在的问题

你通过继承Page后重写props的写法虽然可以正常运行,但重复定义了Page接口原生自带的PageProps、errors等规则,后续如果Inertia官方调整Page接口的原生结构,你需要手动同步修改,维护成本更高。

最佳实现方式

步骤1:定义自定义属性

只需要编写你需要新增的属性即可,不需要重复写原生自带的属性:

export type User = {
  id: number;
  name: string;
  email: string;
}

// 仅定义你要新增的共享属性
interface CustomSharedProps {
  auth: {
    user: User
  }
}

步骤2:直接使用泛型调用

usePage的泛型参数直接对应Page的SharedProps参数,传入后会自动和原生props合并,原生自带的errors等属性也会正常识别:

import { usePage } from '@inertiajs/inertia-react';
import { CustomSharedProps } from './你的类型定义文件路径';

export default function Topbar(): JSX.Element {
  const { url, component, props } = usePage<CustomSharedProps>();
  // 自定义auth属性和原生errors属性都可以正常类型提示
  const { user } = props.auth
  console.log(props.errors)
}

可选:全局生效无需每次传泛型

如果auth是全局共享的属性,你可以通过类型合并直接扩展Inertia的原生PageProps,之后所有usePage调用默认都会带auth类型提示:
新建inertia.d.ts类型声明文件:

import { User } from './你的User类型定义路径'

declare module '@inertiajs/inertia' {
  interface PageProps {
    auth: {
      user: User
    }
  }
}

配置后直接调用usePage即可,不需要每次传入泛型:

const { props } = usePage()
// props.auth.user 会自动识别类型

内容的提问来源于stack exchange,提问作者Potato Science

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:36:02