使用 injectIntl​​() 包装 React 组件后属性类型检查丢失

Attribute type checking is lost after wrapping React component with injectIntl()

假设我有一个组件 Card,它看起来像这样:

import * as React from 'react';

interface Props {
    title: string;
}

export class Card extends React.Component<Props, null> {
    public render() {
        return (
            <div>
                {this.props.title}
            </div>
        );
    }
}

现在,由于道具的原因,我必须将此组件与属性 title 一起使用。

<Card title="Example" />

我需要用 react-intl 中的 injectIntl() 包装这个组件,所以 intl 上下文被注入。我这样做:

import * as React from 'react';
import {injectIntl} from 'react-intl';

interface Props {
    title: string;
}

class Component extends React.Component<Props, null> {
    // ..
}

export const Card = injectIntl(Component);

现在我可以使用没有属性 titleCard 组件。

<Card />

这对于打字稿编译器来说似乎很好。也没有运行时错误。我预计编译器会抛出这样的错误:

Property 'title' is missing in type '{}'.

这种行为从何而来?为什么会这样?如何解决这个问题?

提前致谢!

TL;DR: 您需要安装 @types/react-intl 包。

react-intl 包不使用类型注释,如您在 inject.js 的源代码中所见。 injectIntl 返回的组件与您的 Card 完全不同。 @types/react-intl 包中的类型添加了缺失的类型注释。