在react-admin中使用TypeScript校验输入/字段组件的source参数
实现方案
完全可行,react-admin 4.0及以上版本原生支持该能力,低版本也可以通过自定义类型封装实现,具体实现方案如下:
- 方案1:直接使用组件内置泛型
所有官方提供的字段、输入组件都支持传入记录类型作为泛型参数,传入后source属性会自动被TypeScript校验是否属于对应类型的合法键名,不符合的取值会直接报错。
示例代码:
type Organisation = { id: number; name: string; } const OrganisationShow = (props: ShowProps) => { const { record, ...controllerProps } = useShowController<Organisation>(props); return ( <ShowView record={record} {...controllerProps} > <TextField<Organisation> source="id" /> <TextField<Organisation> source="name" /> <TextField<Organisation> source="foo" /> // TypeScript会直接抛出错误,提示"foo"不是Organisation类型的合法属性 </ShowView> ) }
- 方案2:封装绑定类型的业务组件
如果同一个记录类型会在多个列表、详情、编辑页复用,可以提前封装绑定了对应类型的组件,避免每次调用组件都重复声明泛型,简化业务代码写法。
示例代码:
// 公共层提前封装 import { TextField, TextInput, ReferenceField } from 'react-admin'; export const OrgTextField = TextField<Organisation>; export const OrgTextInput = TextInput<Organisation>; export const OrgReferenceField = ReferenceField<Organisation>; // 业务页面直接使用 const OrganisationShow = (props: ShowProps) => { const { record, ...controllerProps } = useShowController<Organisation>(props); return ( <ShowView record={record} {...controllerProps}> <OrgTextField source="id" /> <OrgTextField source="name" /> <OrgTextField source="foo" /> // 同样会触发TypeScript校验报错 </ShowView> ) }
- 低版本兼容方案
如果使用的是4.0以下的react-admin版本,可以通过自定义组件类型覆盖的方式实现相同能力:
import { TextField as RaTextField, TextFieldProps } from 'react-admin'; // 自定义带泛型的TextField组件 const TypedTextField = <T extends Record<string, any>>( props: Omit<TextFieldProps, 'source'> & { source: keyof T } ) => <RaTextField {...props as TextFieldProps} />; // 业务使用方式和上面一致 <TypedTextField<Organisation> source="foo" /> // 会触发报错
内容的提问来源于stack exchange,提问作者Nicolas D
相关产品推荐
相关产品推荐

