Búsqueda de sitios web

Accediendo a un miembro de StyleSheet de React Native mediante una cadena de clave dinámica en TypeScript


Tengo esta hoja de estilo:

const styles = StyleSheet.create({
  primary: {},
  secondary: {},
})

Y me gustaría acceder a las claves con cadenas compuestas dinámicamente.

<View style={styles[props.type]}/>

Esto es cuando TS se queja (pero el código se ejecuta perfectamente como uno esperaría):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ primary: { }; secondary: { }'.
  No index signature with a parameter of type 'string' was found on type '...'.ts(7053)

¿Cómo podría orientar a TS en la dirección correcta y hacerla feliz?

Respuesta #1

Este es el ejemplo funcional mínimo y simplificado:

import { StyleSheet } from "react-native";

type Props = {
    type: 'primary' | 'secondary'
}

const styles = StyleSheet.create({
    primary: {},
    secondary: {}
});

const Component: React.FC<Props> = ({ type }) => {
  const style = styles[props.type];

  // ...
}