gpt4 book ai didi

javascript - 如何在 Typescript 中正确使用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 09:40:08 26 4
gpt4 key购买 nike

我遇到了一个关于接口(interface)和 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"));

我收到以下错误消息:

Type 'typeof UnsafeComponent' is not assignable to type 'IUnsafeComponent'.

[0] Property 'componentName' is missing in type 'typeof UnsafeComponent'.

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

最佳答案

这个声明说你想要一个 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 组件引用如何指向类构造函数,而不是类实例。

关于javascript - 如何在 Typescript 中正确使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com