Reactjs 如何在对象中键入inded签名
我是新来的。如果我把我的问题命名错了,我很抱歉 我想创建一个React组件,它将根据提供给它的道具更改图像源 我被一些代码卡住了Reactjs 如何在对象中键入inded签名,reactjs,typescript,typescript-typings,styled-components,Reactjs,Typescript,Typescript Typings,Styled Components,我是新来的。如果我把我的问题命名错了,我很抱歉 我想创建一个React组件,它将根据提供给它的道具更改图像源 我被一些代码卡住了 这是CustomIcon组件的内部 import React from 'react'; import { CustomIconProps } from './CustomIcon.types'; import { Img } from './CustomIcon.styles'; import iconPath from '../../assets/icons/
这是CustomIcon组件的内部
import React from 'react';
import { CustomIconProps } from './CustomIcon.types';
import { Img } from './CustomIcon.styles';
import iconPath from '../../assets/icons/iconPath';
export const CustomIcon: React.FC<CustomIconProps> = props => {
return <Img src={iconPath[props.type]} />;
};
这是iconPath.ts的内部
import tooth from './tooth.png';
const iconPath = {
tooth: tooth,
};
export default iconPath;
这是我的错误:
TypeScript error in /home/buashei/work/reservation_module/src/components/CustomIcon/CustomIcon.tsx(15,20):
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Toot'.
No index signature with a parameter of type 'string' was found on type 'Toot'. TS7053
13 |
14 | export const CustomIcon: React.FC<CustomIconProps> = props => {
> 15 | return <Img src={iconPath[props.type]} />;
| ^
16 | };
17 |
/home/buashei/work/reservation\u module/src/components/CustomIcon/CustomIcon.tsx中的类型脚本错误(15,20):
元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“Toot”。
在类型“Toot”上未找到具有“string”类型参数的索引签名。TS7053
13 |
14 |导出常量自定义图标:React.FC=props=>{
>15 |返回;
| ^
16 | };
17 |
请告诉我应该在哪里以及如何为“牙齿”添加类型
提前感谢您在这个问题上的帮助,它让我的头脑发热了基本上它说的是您不知道您的
字符串
变量props.type
代表iconPath
的属性。我不会添加索引签名,而是限制props.type
,使其只能是有效键,而不仅仅是任何字符串
export type CustomIconProps = {
type: keyof typeof iconPath;
};
基本上,它说的是您不知道您的字符串变量props.type
表示iconPath
的属性。我不会添加索引签名,而是限制props.type
,使其只能是有效键,而不仅仅是任何字符串
export type CustomIconProps = {
type: keyof typeof iconPath;
};
您的错误是关于Toot
-是另一个组件还是打字错误?@DeanJamesToot
是iconPath对象中的键和值。但我已经找到了解决问题的办法<代码>导出接口IconPathProps扩展了记录{tooth:string;}
您的错误是关于Toot
-这是另一个组件还是打字错误?@DeanJamesToot
是iconPath对象中的键和值。但我已经找到了解决问题的办法<代码>导出接口IconPathProps扩展记录{tooth:string;}