【问题标题】:How to type inded signature in object如何在对象中键入索引签名
【发布时间】:2021-04-13 13:23:42
【问题描述】:

我是新来的。如果我把我的问题命名错了,我很抱歉。

我想创建一个 React 组件,该组件将根据给它的 prop 更改图像源。

我被一些代码卡住了。

<CustomIcon type={'tooth'} />

这是一个 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]} />;
};

这是CustomIcon.types.ts的内部

export type CustomIconProps = {
  type: string;
};

这是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 |

请告诉我应该在哪里以及如何为“牙齿”添加类型。

在此先感谢您对这个问题的帮助,这让我大吃一惊

【问题讨论】:

  • 您的错误涉及Toot - 是另一个组件还是拼写错误?
  • @DeanJames Toot 是 iconPath 对象中的键和值。但我找到了解决我的问题的方法。 export interface IconPathProps extends Record&lt;string, string&gt; { tooth: string; }

标签: reactjs typescript typescript-typings styled-components


【解决方案1】:

基本上它说的是你不知道你的string 变量props.type 代表iconPath 的一个属性。我不会添加索引签名,而是限制props.type,使其只能是有效密钥,而不仅仅是任何string

export type CustomIconProps = {
  type: keyof typeof iconPath;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多