【问题标题】:How to properly use interfaces in Typescript如何在 Typescript 中正确使用接口
【发布时间】:2017-05-22 09:20:05
【问题描述】:

我遇到了一个关于接口和 Typescript 的问题。下面的例子: 从 "react" 导入 * as React;

/*
 * An interface used to describe the properties of the react component.
 */
interface IUnsafeComponentProps {
    component: IUnsafeComponent //& typeof React.Component;
}

/*
 * An interface used to describe every component that is allowed to be rendered. 
 * It needs to define a property called "componentName".
 */
export interface IUnsafeComponent {
    componentName: string;
    componentStyles?: {};
}

/*
 * The React component itself used to render the unsafe component.
 */
export class UnsafeComponent extends React.Component<IUnsafeComponentProps, any> implements IUnsafeComponent {

    public componentName: string;

    constructor(props: IUnsafeComponentProps) {
        super(props);
        this.componentName = "UnsafeComponent";
    }

    public render(): JSX.Element {
        return <this.props.component/>;
    }
}

这样一个包装器的原因是允许在我的应用程序中呈现第三方代码。如果我现在尝试使用该组件:

let content = <UnsafeComponent component={UnsafeComponent}/>;
ReactDOM.render(content, document.getElementById("root"));

我收到以下错误消息:

类型“typeof UnsafeComponent”不可分配给类型“IUnsafeComponent”。

[0] 类型“typeof UnsafeComponent”中缺少属性“componentName”。

我真的不知道为什么我的 ddeclaraion 是错误的。我对 Typescript/Javascript 很陌生。也许我在这里遇到了一些非常基本的错误。

【问题讨论】:

    标签: javascript reactjs typescript interface react-redux


    【解决方案1】:

    这个声明说你想要一个IUnsafeComponentinstance

    interface IUnsafeComponentProps {
        component: IUnsafeComponent //& typeof React.Component;
    }
    

    在这里,您为UnsafeComponent 传递了构造函数

    <UnsafeComponent component={UnsafeComponent}/>;
    

    您可能想要的是这个,它表示您需要一些构造函数来生成IUnsafeComponent

    interface IUnsafeComponentProps {
        component: new(...args: any[]) => IUnsafeComponent;
    }
    

    另请参阅 What does the error "JSX element type '...' does not have any construct or call signatures" mean?,其中讨论了 JSX 组件引用如何指向类构造函数,而不是类实例。

    【讨论】:

    • 如果我想传递一个实现了 IUnsafeComponent & typeof React.Component 的对象的构造函数,我该如何组合呢?
    • 阅读您的链接后,我尝试使用component: new(..args: any[]) =&gt; IUnsafeComponent &amp; React.Component&lt;any, any&gt;,但我无法访问componentName 属性,我在以下调用方代码上收到错误:{this.props.component.componentName} -> "Property 'componentName ' 在类型 'new (...args: any[]) => IUnsafeComponent & Component' 上不存在。"
    猜你喜欢
    • 2014-06-26
    • 2021-06-20
    • 2021-04-24
    • 2017-11-14
    • 2016-11-25
    • 1970-01-01
    • 2018-08-01
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多