Proptypes:验证接口数组作为props in react

问题描述 投票:1回答:1

我在react组件上遇到了一些麻烦,需要一些帮助以寻求解决方案...

我想在我的组件上使用propTypes以便进行运行时验证。我已经为要使用的道具实现了接口。一些道具是接口数组。这是我到目前为止的内容:

类型的定义:

   export type Point = {
    /** x value */
    readonly x: number;

    /** y value */
    readonly y: number;
  }

  /** Contains information relative to a line plot */
  export interface LineData {
    /** name of the line. Will be used in legend */
    readonly legend: string;

    /** Color of the line. If unspecified, a color will be chosen automatically */
    color?: string;

    /** width of the line in pixel. If not specified, a default value is provided */
    strokeWidth?: number;

    /** Contains all points associated with this line */
    readonly data: Array<Point>;
  }

  /** Graph properties */
  export interface GraphProps {
    /** An array that contains all line definitions */
    readonly lineDatas: Array<LineData>;

    /** The plot's title. Is set in upper left corner of the plot, outside border */
    readonly plotTitle?: string;

    /** Plot title's font size */
    readonly plotTitleFontSize?: number;
  }

原型的实现:

Graph.propTypes = {  
  lineDatas: PropTypes.arrayOf(PropTypes.shape({
    legend : PropTypes.string.isRequired,
    color:PropTypes.string,
    strokeWidth: PropTypes.number,
    data: PropTypes.arrayOf(PropTypes.shape({
      x: PropTypes.number,
      y: PropTypes.number
    }))
  })),
  plotTitle: PropTypes.string,
  plotTitleFontSize: PropTypes.number,
};

即使按要求设置了egend,我也会收到此错误...

Property 'legend' is optional in type 'InferProps<{ legend: Requireable<string>; color: Requireable<string>; strokeWidth: Requireable<number>; data: Requireable<InferProps<{ x: Requireable<number>; y: Requireable<...>; }>[]>; }>' but required in type 'LineData'.

感谢您的帮助!

reactjs typescript react-proptypes
1个回答
0
投票

发表我的评论作为答案。

您应该使用PropTypes.exact()而不是PropTypes.shape(),并且还向.isRequiredlineData字段添加一些丢失的data调用。

原型代码将是:

Graph.propTypes = {  
  lineDatas: PropTypes.arrayOf(PropTypes.exact({
    legend : PropTypes.string.isRequired,
    color:PropTypes.string,
    strokeWidth: PropTypes.number,
    data: PropTypes.arrayOf(PropTypes.exact({
      x: PropTypes.number,
      y: PropTypes.number
    })).isRequired
  })).isRequired,
  plotTitle: PropTypes.string,
  plotTitleFontSize: PropTypes.number,
};
© www.soinside.com 2019 - 2024. All rights reserved.