打字稿和材料ui如何修复类型错误

时间:2020-07-10 10:35:07

标签: reactjs typescript material-ui

我是ts的新手,请不要生我的气。我对材料ui有问题。无法设置[classes[color + 'CardHeader']]: color

的类型

引发错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<"cardHeader" | "cardHeaderPlain" | "warningCardHeader" | "successCardHeader" | "dangerCardHeader" | "infoCardHeader" | "primaryCardHeader", string>'.

您能解释一下我在哪里出错吗?

import React, { ReactNode } from 'react';
import classNames from 'classnames';
import useStyles from './styles/cardHeaderStyle';

type CardHeaderProps = {
  className: string,
  children: ReactNode,
  color: ColorType,
  plain?: boolean,
};

type ColorType = 'warning' | 'success' | 'danger' | 'info' | 'primary';

const CardHeader = (props: CardHeaderProps): JSX.Element => {
  const classes = useStyles();
  const { className = '', children, color, plain, ...rest } = props;
  console.log('classes', classes);

  const cardHeaderClasses = classNames({
    [classes.cardHeader]: true,
    // [classes['primaryCardHeader']]: color,
    [classes[color + 'CardHeader']]: color, 
    [classes.cardHeaderPlain]: plain,
    [className]: className !== undefined,
  });

  return (
    <div className={cardHeaderClasses} {...rest}>
      {children}
    </div>
  );
};

export default CardHeader;

enter image description here

1 个答案:

答案 0 :(得分:0)

这似乎是因为您正在将字符串文字与变量color + 'CardHeader'结合使用。

TypeScript编译器不会知道您/没有给它适当的字符串。即如果将'CardHeader'替换为'foo'会发生什么?没有一种类型可以匹配。

一种可能的解决方案是重构您的ColorType使其包含'CardHeader'部分,使其看起来像这样:

type ColorType = 'warningCardHeader' | 'successCardHeader' | 'dangerCardHeader' | 'infoCardHeader' | 'primaryCardHeader';

现在它将与Record<"cardHeader" | "cardHeaderPlain" | "warningCardHeader" | "successCardHeader" | "dangerCardHeader" | "infoCardHeader" | "primaryCardHeader", string>类型匹配。