React组件Props Either类型约束:解决属性不存在TS报错
解决TypeScript联合类型Props解构报错问题
你遇到的错误是因为Props是CreateProps和UpdateProps的联合类型,这两个类型没有共有的createDocFn、updateDocFn、deleteDocFn属性——TypeScript无法确定当前传入的props到底属于哪一种类型,所以直接解构这些非共有属性会触发类型错误。
下面是两种可行的解决方式:
方案一:添加判别式字段(推荐)
给两种Props类型添加一个共同的判别字段(比如mode),让TypeScript能通过这个字段明确当前的类型分支,从而安全访问对应属性:
type CommonProps = { // 你的公共属性定义 }; type CreateProps = { mode: 'create'; // 判别式,标识创建模式 createDocFn: (value: any) => void; } & CommonProps; type UpdateProps = { mode: 'update'; // 判别式,标识更新模式 updateDocFn: (id: string, value: any) => void; deleteDocFn: (id: string) => void; } & CommonProps; type Props = CreateProps | UpdateProps; export default function MyForm(props: Props) { const { /* 解构公共属性 */ } = props; if (props.mode === 'create') { // 此处TypeScript明确知道props是CreateProps类型 const { createDocFn } = props; // 处理表单创建逻辑 } else { // 此处TypeScript明确知道props是UpdateProps类型 const { updateDocFn, deleteDocFn } = props; // 处理表单更新/删除逻辑 } }
这种方式逻辑直观,TypeScript的类型推断更可靠,后续维护也更清晰。
方案二:使用类型守卫函数
如果不想额外添加判别字段,可以编写类型守卫函数来判断当前props的具体类型:
type CommonProps = { // 你的公共属性定义 }; type CreateProps = { createDocFn: (value: any) => void; } & CommonProps; type UpdateProps = { updateDocFn: (id: string, value: any) => void; deleteDocFn: (id: string) => void; } & CommonProps; type Props = CreateProps | UpdateProps; // 类型守卫:判断是否为CreateProps类型 function isCreateProps(props: Props): props is CreateProps { return 'createDocFn' in props; } // 类型守卫:判断是否为UpdateProps类型 function isUpdateProps(props: Props): props is UpdateProps { return 'updateDocFn' in props && 'deleteDocFn' in props; } export default function MyForm(props: Props) { const { /* 解构公共属性 */ } = props; if (isCreateProps(props)) { const { createDocFn } = props; // 处理创建逻辑 } else if (isUpdateProps(props)) { const { updateDocFn, deleteDocFn } = props; // 处理更新/删除逻辑 } }
这种方式不需要修改原有类型结构,但要确保类型守卫的判断逻辑准确,避免出现类型误判。
内容的提问来源于stack exchange,提问作者Ranu Vijay
相关产品推荐
相关产品推荐

