如何实现React组件与对应Props类型的联动校验?
问题描述
我定义了以下React函数组件及对应Props类型,当前State类型定义存在类型错误,请问如何实现组件与对应Props类型的联动校验,确保使用某一组件时,props为其对应的类型?
原代码(存在类型错误)
import React from 'react'; type ComponentAProps = { a: string; }; function ComponentA(props: ComponentAProps) { return <div>component A</div>; } type ComponentBProps = { b: string; }; function ComponentB(props: ComponentBProps) { return <div>component B</div>; } type State = { Component: React.FunctionComponent<ComponentAProps | ComponentBProps>; props: ComponentAProps | ComponentBProps; }; const state: State = { Component: ComponentA, // 错误:ComponentBProps中缺少ComponentAProps要求的'a'属性 props: { a: 'a', }, };
解决方案
使用可辨识联合类型,将组件与对应Props类型一一绑定,让TypeScript自动校验两者的匹配关系:
import React from 'react'; type ComponentAProps = { a: string; }; function ComponentA(props: ComponentAProps) { return <div>component A</div>; } type ComponentBProps = { b: string; }; function ComponentB(props: ComponentBProps) { return <div>component B</div>; } // 定义联合类型,每个分支明确绑定组件和其对应的Props type State = | { Component: typeof ComponentA; props: ComponentAProps } | { Component: typeof ComponentB; props: ComponentBProps }; // ✅ 合法:ComponentA 匹配 ComponentAProps const validStateA: State = { Component: ComponentA, props: { a: 'a' }, }; // ✅ 合法:ComponentB 匹配 ComponentBProps const validStateB: State = { Component: ComponentB, props: { b: 'b' }, }; // ❌ 非法:ComponentA 对应了 ComponentBProps,会触发类型错误 const invalidState: State = { Component: ComponentA, props: { b: 'b' }, };
原理说明
通过将State拆分为多个分支的联合类型,每个分支严格对应一个组件和它的专属Props类型,TypeScript会在赋值时自动检查组件与props的匹配关系,避免出现“组件需要的props与传入props类型不匹配”的问题。如果后续需要新增组件,只需在State的联合类型中添加新的分支即可,扩展性强。
内容的提问来源于stack exchange,提问作者user1849962
相关产品推荐
相关产品推荐

