Redux-Form(v7)结合Reactstrap与TypeScript的类型兼容问题求助
解决Redux-Form(v7) + Reactstrap + TypeScript的类型不兼容问题
我刚帮你梳理了这个TS错误的根源,其实就是类型范围不匹配:Reactstrap的Input组件要求type必须是它定义的InputType枚举(只能是"text"、"password"这类特定的字符串字面量),但Redux-Form的Field组件默认会把你写的type="text"推断成宽泛的string类型,两边类型对不上就报错了。
下面给你几个实用的解决方案,按需选就行:
方案一:在Form里明确约束类型
在Form.tsx里导入InputType,然后给Field的type属性加上类型断言,让TypeScript识别它是合法的InputType值:
import { InputType } from 'reactstrap/lib/Input'; // 写法1:直接断言为InputType类型 <Field type="text" as={InputType} component={InputField} /> <Field type="password" as={InputType} component={InputField} /> // 写法2:更精确地指定字面量类型(推荐,类型检查更严格) <Field type="text" as="text" component={InputField} /> <Field type="password" as="password" component={InputField} />
方案二:在InputField组件里兼容类型
如果不想改Form里的代码,可以在InputField里把接收到的type断言为InputType,告诉TS这个值是符合要求的:
import { Input, InputType } from 'reactstrap'; import { WrappedFieldProps } from 'redux-form/lib/Field'; type Props = { type?: InputType; }; const InputField = (props: WrappedFieldProps & Props) => { const { type, input } = props; // 给type加上类型断言,消除TS错误 return <Input type={type as InputType} {...input} />; };
方案三:给Field指定泛型参数(最严谨)
如果想要更规范的类型约束,可以给Redux-Form的Field组件指定泛型,明确它传递给InputField的props类型:
// Form.tsx中 import { Field } from 'redux-form'; import { InputType } from 'reactstrap/lib/Input'; import InputField from './InputField'; // 定义Field需要传递的props类型 type FieldInputProps = { type?: InputType; }; // 使用泛型指定Field的props类型 <Field<FieldInputProps> type="text" component={InputField} /> <Field<FieldInputProps> type="password" component={InputField} />
为什么之前只解决了一半问题?
你之前把InputField的type改成InputType后,组件自身的类型匹配了,但Form里的Field还是把type="text"推断成string——因为Field不知道它需要传递InputType类型的参数,所以必须从Form端也约束类型,或者在InputField里做兼容,两边都对齐了就不会报错了。
内容的提问来源于stack exchange,提问作者Bernard Stojanović
相关产品推荐
相关产品推荐

