TypeScript+React Native使用Pick<T,K>给textContentType赋值报错如何解决
问题根因
你对Pick工具类型的使用确实存在误用:Pick<T, K>的作用是从对象类型T中提取指定属性集合K,返回包含这些属性的新对象类型,而非返回属性对应的数值类型。
你代码中Pick<TextInputProps, 'textContentType'>实际得到的类型是{ textContentType: 原生定义的textContentType联合类型 },是一个对象类型,而TextInput的textContentType prop要求传入的是联合类型值,两者类型不匹配因此触发报错。
解决方案
不需要手动重复定义联合类型,直接使用TypeScript的索引访问类型即可提取已有属性的类型,语法为T[属性名]。
修正后的完整代码如下:
import { KeyboardTypeOptions, TextInputProps } from 'react-native'; import { TextInput } from 'react-native-paper'; export interface ValidatedInputProps { autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters', // 用索引访问类型直接提取textContentType的原生类型 contentType: TextInputProps['textContentType'], isSecure?: boolean, keyboard?: KeyboardTypeOptions, label: string, } export const ValidatedInput = ({ autoCapitalize = 'none', contentType, isSecure = false, keyboard = 'default', label, }: ValidatedInputProps) => { return ( <TextInput textContentType={contentType} {/* 其余属性逻辑 */} /> ); };
如果你的contentType是可选参数,直接在属性名后加?即可:
contentType?: TextInputProps['textContentType']
内容的提问来源于stack exchange,提问作者Kenny83
相关产品推荐
相关产品推荐

