Aquí está el código para mi componente personalizado. Obteniendo un error que no le gusta que le di a 'tipo' el tipo de cadena. ¿Cuál es la forma correcta de definir qué es 'tipo'? Supongo que necesitaría definir algún tipo de objeto para él, pero no estoy seguro de cómo hacerlo.
import React from 'react'; import { StyleSheet, Text, Pressable } from 'react-native'; interface Props { text: string; type?: string; onPress: () => void; } const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => { return ( <Pressable onPress={onPress} style={[styles.container, styles[`container_${type}`]]} > <Text style={[styles.text, styles[`text_${type}`]]}>{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', }, });Dado que está tratando de usar una clave generada dinámicamente para el objeto de styles , TS se queja porque la propiedad de type es de tipo string , que podría ser cualquier cadena y, por lo tanto, no coincidir con una clave del objeto de styles .
Una forma de solucionar esto sería convertir la propiedad type a keyof typeof styles :
const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => { const containerKey = `container_${type}` as keyof typeof styles; const textKey = `text_${type}` as keyof typeof styles; return ( <Pressable onPress={onPress} style={[styles.container, styles[containerKey]]}> <Text style={[styles.text, styles[textKey]]}>{text}</Text> </Pressable> ); }; Pero dado que la conversión no es confiable, también puede configurar el type de propiedad de tipo para que sea de tipo TS string literal :
type TERTIARY = 'TERTIARY'; interface Props { text: string; type?: 'PRIMARY' | TERTIARY; onPress: () => void; } const CustomButton: React.FC<Props> = ({ onPress, text, type = 'PRIMARY' }) => { return ( <Pressable onPress={onPress} style={[styles.container, styles[`container_${type}`]]}> {/* An error would still be displayed here since the styles object doesn't have a text_PRIMARY field */} {/* <Text style={[styles.text, styles[`text_${type}`]]}>{text}</Text> */} {/* If there's no other option, you could resort to casting */} <Text style={[styles.text, styles[`text_${type as TERTIARY}`]]}>{text}</Text> </Pressable> ); };