如何在Typescript中正确使用接口

时间:2017-01-07 19:26:50

标签: javascript reactjs typescript interface react-redux

我遇到了有关接口和Typescript的问题。以下示例:     import * as React from“react”;

@seminar.reload

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

/*
 * 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/>;
    }
}

我收到以下错误消息:

  

类型'typeof UnsafeComponent'不能分配给'IUnsafeComponent'类型。

     

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

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

1 个答案:

答案 0 :(得分:4)

此声明表示您需要IUnsafeComponent实例

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组件引用如何引用类构造函数,而不是类实例。