【发布时间】:2020-04-04 23:20:24
【问题描述】:
我正在将 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;
但我在 PropTypes 中遇到错误:
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 不是一回事。您可以轻松编写一个 Typescript 验证通过但仍会收到 PropTypes 警告的示例(例如,一个返回数字的外部 API,其中应该是字符串)。这里有两篇文章解释了原因:
所以我的问题是如何使嵌套的 PropTypes 对象(PropTypes.shape() 或 PropTypes.objectOf())与 TypeScript 一起工作?
【问题讨论】:
-
我认为只有
interface和React.FC<FooterProps>就足够了。你不需要propTypes使用 Typescript 进行反应 -
@AnhNguyen 我会争辩说,如果您这样做,则只能使用组件的 TS 感知消费者。我也在寻找
propTypes的 TS 解决方案。现在,tsc出现错误:Type 'undefined' is not assignable to type 'MetaType'.
标签: reactjs typescript types react-proptypes