如何将PropTypes.shape与打字稿一起使用

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

我正在将React应用程序从Javascript重构为Typescript,但是我在迁移shape PropType时遇到了一些麻烦。我的代码现在看起来像这样:

import React from 'react';
import PropTypes from 'prop-types';

interface FooterProps {
  labels: FooterLabels;
}

interface FooterLabels {
  body: string;
}

const Footer: React.FC<FooterProps> = ({ labels }) => (
  <div className="footer">
    {/* ... */}
  </div>
);

Footer.propTypes = {
  labels: PropTypes.shape({
    body: PropTypes.string.isRequired
  }).isRequired
};

export default Footer;

但是我在PropType中遇到错误:

Type 'Validator<InferProps<{ body: Validator<string>; }>>' is not assignable to type 'Validator<FooterLabels>'.
  Type 'InferProps<{ body: Validator<string>; }>' is not assignable to type 'FooterLabels'.
    Property 'body' is optional in type 'InferProps<{ body: Validator<string>; }>' but required in type 'FooterLabels'.ts(2322)
FooterAppPromo.tsx(5, 3): The expected type comes from property 'labels' which is declared here on type 'WeakValidationMap<FooterProps>'

我是Typescript的新手,所以有时我真的不知道我在做什么,但是我尝试做类似的事情:

Footer.propTypes = {
  labels: PropTypes.shape<FooterLabels>({
    body: PropTypes.string.isRequired
  }).isRequired
};

但是我遇到了错误。我尝试搜索示例实现,但找不到任何。

编辑

Typescript类型和PropTypes是not一样。您可以轻松地编写一个示例,其中通过了Typescript验证,但仍然收到PropTypes警告(例如,外部API返回的数字应为字符串)。这是两篇解释原因的文章:

所以我的问题是如何使嵌套的PropTypes对象(PropTypes.shape())与TypeScript一起使用?

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

实际上,您在这里不需要propTypes-labels只有一个嵌套字段body,其类型为FooterLabels

interface FooterProps {
  labels: {
     body: FooterLabels;
  };
}

0
投票
interface FooterLabels {
  body: string;
}

interface FooterProps {
  labels: FooterLabels;
}
© www.soinside.com 2019 - 2024. All rights reserved.