【问题标题】:Typescript error from defaultProps on React FunctionComponent来自 React FunctionComponent 上 defaultProps 的 Typescript 错误
【发布时间】:2019-06-06 11:05:51
【问题描述】:

我有以下 React 功能组件:

import React, { memo } from 'react';

interface Props {
  buttonType?: JSX.IntrinsicElements['button']['type'];
  text: string;
};

const defaultProps = {
  buttonType: 'button',
};

const Button: React.FunctionComponent<Props> = ({
  buttonType,
  text,
}) => (
  <button type={buttonType}>
    {text}
  </button>
);

Button.defaultProps = defaultProps;

export default memo(Button);

这会引发 Typescript 错误:

Type '{ buttonType: string; }' is not assignable to type 'Partial<Props>'.

这是我平时写无状态组件的方式,这里的错误是因为我给组件分配了defaultProps。如果我将 defaultProps 声明写为:

Button.defaultProps = {
  buttonType: 'button',
};

为什么在从 const 分配 defaultProps 时会出现错误,但如果我全部内联则不会?不是一样的吗?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    您必须在 defaultProps 对象上指定 buttonType 的类型。当您使用Button.defaultProps 时,它会自动推断为JSX.IntrinsicElements['button']['type'],但是当您创建一个新对象时,它会将其视为string

    const defaultProps: Partial<Props> = {
      buttonType: 'button',
    }
    

    应该有效

    【讨论】:

    • 啊,对。在所有组件中始终为 defaultProps 声明 const defaultProps: Partial&lt;Props&gt; = { 以避免将来发生此类事情是一种好习惯吗?
    • 在我看来,我喜欢直接使用Component.defaultProps。干净多了。否则,是的,我建议您指定类型 - 如前所述,在此示例中 Typescript 无法推断它。
    • 很公平。我将它写成 const 的唯一原因是它可以通过 Props 的类型定义位于顶部。这样就可以立即清楚地知道需要哪些道具以及它们在文件顶部的默认设置。在文件的顶部和底部之间拆分这些信息感觉很混乱。
    猜你喜欢
    • 2019-02-26
    • 2017-02-19
    • 2019-06-03
    • 2017-01-24
    • 1970-01-01
    • 2018-05-06
    • 2019-12-10
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多