[英]Element implicitly has an 'any' type because expression of type 'string' can't be used to index type React Typescript
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:
这适用于 javascript 但使用 typescript 我收到错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ like: string;元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ like: string; dislike: string;
不喜欢:字符串; }'.
}'。 No index signature with a parameter of type 'string' was found on type '{ like: string;
在“{ like: string; 类型”上找不到带有“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!我对 typescript 的反应相当陌生,所以我不太确定如何解决这个问题,所以任何帮助都会很棒!
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;
Your COLORS
object defines 2 key value pairs: "like"
and "dislike"
.您的
COLORS
object 定义了 2 个键值对: "like"
和"dislike"
。 If you try to access COLORS["foobar"]
, it will give you a typescript error as it is not a defined key.如果你尝试访问
COLORS["foobar"]
,它会给你一个 typescript 错误,因为它不是一个定义的键。
Similarly, your type
is defined as a string
and not constrained to only "like"
or "dislike"
.同样,您的
type
被定义为一个string
,而不是仅限于"like"
或"dislike"
。 To constrain it, you need to only allow the "like"
or "dislike"
keys for it.要约束它,您只需要允许它使用
"like"
或"dislike"
键。
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.一种更稳健的方法是根据您的 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:作为旁注,您的 React 为您提供了泛型类型,您可以使用它使您键入表达式不那么混乱:
const Choice: React.FC<{type : keyof typeof COLORS}> = ({type}) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.