TypeScript错误7053:React自定义样式组件的type属性类型怎么定义?
报错原因
你给type属性定义的string类型范围过于宽泛,TypeScript 无法保证你拼接得到的container_${type}、text_${type}一定是styles对象上存在的合法属性,因此会触发类型校验报错。
解决方法
方法1:手动定义合法类型(适合类型固定的场景)
- 先定义支持的按钮类型联合类型:
type ButtonType = 'PRIMARY' | 'TERTIARY'
- 将Props中的
type类型替换为上述联合类型:
interface Props { text: string; type?: ButtonType; onPress: () => void; }
- 给拼接的样式key加上类型断言,让TS识别为styles的合法索引,分别修改Pressable和Text的style属性:
// Pressable的style style={[styles.container, styles[`container_${type}` as keyof typeof styles]]} // Text的style style={[styles.text, styles[`text_${type}` as keyof typeof styles]]}
方法2:自动推导类型(适合经常新增样式类型的场景)
不需要手动维护联合类型,直接从styles对象中自动提取合法的type值,后续新增container_XXX样式时会自动更新类型范围:
// 自动提取所有container_前缀的后缀作为合法type值 type ButtonType = keyof typeof styles extends `container_${infer T}` ? T : never interface Props { text: string; type?: ButtonType; onPress: () => void; }
后续类型断言逻辑和方法1完全一致。
修改后完整代码
import React from 'react'; import { StyleSheet, Text, Pressable } from 'react-native'; // 手动定义类型用这个 type ButtonType = 'PRIMARY' | 'TERTIARY' // 自动推导类型就把上面一行换成下面这行 // type ButtonType = keyof typeof styles extends `container_${infer T}` ? T : never interface Props { text: string; type?: ButtonType; onPress: () => void; } const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => { return ( <Pressable onPress={onPress} style={[styles.container, styles[`container_${type}` as keyof typeof styles]]} > <Text style={[styles.text, styles[`text_${type}` as keyof typeof styles]]}>{text}</Text> </Pressable> ); }; export default CustomButton; const styles = StyleSheet.create({ container: { width: '100%', padding: 15, marginVertical: 5, alignItems: 'center', borderRadius: 5, }, container_PRIMARY: { backgroundColor: '#3B71F3', }, container_TERTIARY: {}, text: { fontWeight: 'bold', color: 'white', }, text_TERTIARY: { fontWeight: 'normal', color: 'gray', }, });
内容的提问来源于stack exchange,提问作者user14263509
相关产品推荐
相关产品推荐

