【发布时间】: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