代码之家  ›  专栏  ›  技术社区  ›  Robin

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

  •  1
  • Robin  · 技术社区  · 7 年前

    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" />
    

    我需要用 injectIntl() 从…起 react-intl ,所以 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);
    

    现在我可以使用 卡片 不带属性的组件 标题

    <Card />
    

    这对于typescript编译器来说似乎很好。也没有运行时错误。我预计编译器会抛出如下错误:

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

    这种行为是从哪里来的?为什么是这样?如何解决这个问题?

    提前谢谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   TomáÅ¡ Ehrlich    7 年前

    TL;博士: @types/react-intl 包裹

    react-intl 包不使用类型注释,正如您在的源代码中所看到的那样 inject.js . 组件返回者 injectIntl Card . 类型来自 @types/react-intl 包添加缺少的类型批注。