Reputation: 544
I am trying to give a conditional colour to a component in react if the type is like it will be green or dislike it will be red. This would work in javascript but with using typescript I am getting the error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ like: string; dislike: string; }'. No index signature with a parameter of type 'string' was found on type '{ like: string; dislike: string; }'.
I am fairly new to typescript in react so I am not too sure how to solve this so any help would be great!
import React from "react";
import {Text, View} from "react-native";
import {styles} from "./styles";
const COLORS = {
like: '#00edad',
dislike: '#ff006f',
}
const Choice = ({type} : {type : string}) => {
const color = COLORS[type];
return (
<View style={[styles.container, {borderColor: color}]}>
<Text style={[styles.text, {color}]}>{type}</Text>
</View>
)
}
export default Choice;
Upvotes: 1
Views: 705
Reputation: 6081
Your COLORS
object defines 2 key value pairs: "like"
and "dislike"
. If you try to access COLORS["foobar"]
, it will give you a typescript error as it is not a defined key.
Similarly, your type
is defined as a string
and not constrained to only "like"
or "dislike"
. To constrain it, you need to only allow the "like"
or "dislike"
keys for it.
One way to do it is to say:
const Choice = ({type} : {type : "like" | "dislike" }) => {
A more robust way is to make the possible values based on your object.
const Choice = ({type} : {type : keyof typeof COLORS}) => {
As a side note, you React gives you generic types you can use it make you type expressions less cluttered:
const Choice: React.FC<{type : keyof typeof COLORS}> = ({type}) => {
Upvotes: 3