Проптипы: проверка массива интерфейса как опоры в реакции - PullRequest
1 голос
/ 14 апреля 2020

У меня возникли некоторые проблемы с реагирующим компонентом, и мне нужна помощь для решения ...

Я хочу использовать 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;
  }

Реализация Proptypes:

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'.

Спасибо за помощь!

1 Ответ

2 голосов
/ 16 апреля 2020

Публикация моих комментариев в качестве ответа.

Вы должны использовать PropTypes.exact() вместо PropTypes.shape(), а также добавить пропущенные вызовы .isRequired в поля lineData и 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,
};
...