React TypeScript:属性“ X”的类型不兼容。类型“ Y”不可分配给类型“ Z”

时间:2018-09-16 20:21:01

标签: reactjs typescript font-awesome

我正在使用React-TypeScript应用程序,创建信用卡号输入组件。当用户输入信用卡号时,输入中的FontAwesome图标应更新为品牌形象。我收到此错误:

Types of property 'icon' are incompatible.
  Type 'string' is not assignable to type 'IconProp'

已经尝试了对我不起作用的解决方案:https://github.com/FortAwesome/react-fontawesome/issues/143#issuecomment-410677960

我认为这是TypeScript问题,错误的类型传递给了icon道具。

这是我的tsx文件的简化版本,也许有帮助:

import { faCreditCard } from '@fortawesome/fontawesome-free-solid';
import { faCcMastercard, faCcVisa } from '@fortawesome/free-brands-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const CARD_TYPES: { [index: string]: string } = {
  mastercard: 'MASTERCARD',
  visa: 'VISA',
};
const CARD_ICONS: { [index: string]: any } = {
  mastercard: faCcMastercard,
  placeholder: faCreditCard,
  visa: faCcVisa,
};

interface IProps {
  placeholder: string;
  icon: string;
}

interface IState {
  cardIcon: string;
}

export default class CardNumber extends Component<IProps,IState
> {

  constructor(props: IWmxCardNumberProps) {
   super(props);
   this.state = {
    cardIcon: CARD_ICONS.placeholder,
   };
  }

  componentDidMount() {
   this.setState({
    cardIcon: CARD_ICONS[cardType] || CARD_ICONS.placeholder
   });
  }

  onCardNumberChange(e: any) {
   this.setState({
    cardIcon: CARD_ICONS[cardType] || CARD_ICONS.placeholder
   });
  }

  public render() {
   const { cardIcon } = this.state;
   const { placeholder } = this.props;

   return (
    <Container>
     <FieldWrapper>
      <InputWrapper data-max="9999 9999 9999 9999 9999">
        {/* Error: Types of property 'icon' are incompatible. Type 'string' is not assignable to type 'IconProp' */}
        <FontAwesomeIcon icon={cardIcon} className="credit-card-icon" />
        <Input
          type="tel"
          placeholder={placeholder}
          onChange={this.onCardNumberChange}
        />
      </InputWrapper>
     </FieldWrapper>
    </Container>
   );
  }
}

那么我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

您需要更改此内容:

interface IState {
  cardIcon: IconProp;
}

您遇到的错误是因为icon道具只能使用string的子集,即IconProp

您可以查看定义here,其中包括类型IconName in this file