繁体   English   中英

如何在Typescript中正确使用接口

[英]How to properly use interfaces in Typescript

我遇到了有关接口和Typescript的问题。 下面的例子:import * as React from“ 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]类型“ UnsafeComponent”的类型中缺少属性“ componentName”。

我真的不知道为什么我的声明是错误的。 我是Typescript / Java的新手。 也许我在这里遇到了一些非常基本的错误。

该声明说您想要IUnsafeComponent实例

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

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

<UnsafeComponent component={UnsafeComponent}/>;

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

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

另请参见错误“ JSX元素类型'...'没有任何构造或调用签名”是什么意思? 讨论了JSX组件引用如何指向类构造函数,而不是类实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM