简体   繁体   English

如何在Typescript中正确使用接口

[英]How to properly use interfaces in Typescript

I came across a problem concerning interfaces and Typescript. 我遇到了有关接口和Typescript的问题。 The following example: import * as React from "react"; 下面的例子: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/>;
    }
}

The reason for such a wrapper is to allow to render third party code within my application. 使用此类包装的原因是允许在我的应用程序中呈现第三方代码。 If I now try to use the component: 如果我现在尝试使用该组件:

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

I get the following error message: 我收到以下错误消息:

Type 'typeof UnsafeComponent' is not assignable to type 'IUnsafeComponent'. 类型“ typeof UnsafeComponent”不可分配给类型“ IUnsafeComponent”。

[0] Property 'componentName' is missing in type 'typeof UnsafeComponent'. [0]类型“ UnsafeComponent”的类型中缺少属性“ componentName”。

I have really no idea why my ddeclaraion is wrong. 我真的不知道为什么我的声明是错误的。 I am quite new to Typescript/Javascript. 我是Typescript / Java的新手。 Maybe I am getting something very basic wrong here. 也许我在这里遇到了一些非常基本的错误。

This declaration says you want an instance of IUnsafeComponent : 该声明说您想要IUnsafeComponent实例

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

Here, you passed the constructor function for UnsafeComponent : 在这里,您传递 UnsafeComponent 的构造函数

<UnsafeComponent component={UnsafeComponent}/>;

What you probably wanted was this, which says that you want some constructor function that produces an IUnsafeComponent : 您可能想要的就是这个,它表示您需要一些生成IUnsafeComponent构造函数:

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

See also What does the error "JSX element type '...' does not have any construct or call signatures" mean? 另请参见错误“ JSX元素类型'...'没有任何构造或调用签名”是什么意思? which talks about how JSX component references are to class constructors, not class instances. 讨论了JSX组件引用如何指向类构造函数,而不是类实例。

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

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