philk
philk

Reputation: 2140

Accessing react native StyleSheet member via dynamic key string in typescript

I have this stylesheet:

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

And I would like to access the keys with dynamically composed strings.

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

This is when TS complains (but the code runs just fine as one would expect):

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)

How could I nudge TS in the right direction and make it happy?

Upvotes: 2

Views: 953

Answers (1)

J&#225;n Jakub Naništa
J&#225;n Jakub Naništa

Reputation: 1926

This is the minimal stripped-down working example:

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];

  // ...
}

Upvotes: 2

Related Questions