我正在研究长达数百行的代码,但我已将问题归结为以下示例。我的问题是为什么Typescript编译器在一个案例中失败,但在使用基础类时成功。
以下代码编译得很好:
import * as React from "react";
interface ComponentProps {
}
class Component<P extends ComponentProps> extends React.Component<P, any> {
}
interface RootComponentProps extends ComponentProps {
viewManager?: ViewManager;
}
class RootComponent<P extends RootComponentProps> extends Component<P> {
static childContextTypes = {
viewManager: React.PropTypes.object
}
private _viewManager: ViewManager;
getChildContext(): RootComponentProps {
return { viewManager: this._viewManager }
};
}
class ViewManager {
constructor(managedElement: HTMLElement, rootComponent: typeof Component) {
const rootFactory = React.createFactory(rootComponent);
}
}
但是,如果我做了一个更改,那么改变&#34; typeof Component&#34; to&#34; typeof RootComponent&#34;在ViewManager的构造函数中,编译器(和VS2015 Intellisense)抱怨:
import * as React from "react";
interface ComponentProps {
}
class Component<P extends ComponentProps> extends React.Component<P, any> {
}
interface RootComponentProps extends ComponentProps {
viewManager?: ViewManager;
}
class RootComponent<P extends RootComponentProps> extends Component<P> {
static childContextTypes = {
viewManager: React.PropTypes.object
}
private _viewManager: ViewManager;
getChildContext(): RootComponentProps {
return { viewManager: this._viewManager }
};
}
class ViewManager {
constructor(managedElement: HTMLElement, rootComponent: typeof RootComponent) {
const rootFactory = React.createFactory(rootComponent);
}
}
错误在React.createFactory方法的参数中,并说:
错误TS2345:构建:RootComponent类型&#39;类型的参数&#39;不能分配给&#39; ComponentClass&lt; any&gt;类型的参数| StatelessComponent&LT;任何&GT;&#39;
当将鼠标悬停在React.createFactory的参数上时,VS 2015 Intellisense会提供更多信息,即:
类型&#39; typeof RootComponent&#39;不提供签名匹配&#39;(props?:any,context?:any):ReactElement&lt; any&gt;&#39;
所有这一切的另一个奇怪的怪癖....如果我删除或注释掉静态&#34; childContextTypes&#34;在RootComponent中,然后它编译都很好,但是当我在我工作更长的应用程序中运行它时,我得到关于缺少childContextTypes的运行时抱怨。
我知道这并不神奇,但此刻对我来说似乎是黑魔法,任何澄清的见解都会受到最高的赞赏。
答案 0 :(得分:0)
在回顾评论后,我开始怀疑打字。我找到了以下helpful gotcha。
关键是要向我的childContextTypes添加一个显式类型注释,如下所示:
static childContextTypes: React.ValidationMap<any> = {
viewManager: React.PropTypes.object
}
这解决了相当迟钝的编译错误。我还没有完成所有代码的工作和测试,但对于这种情况,这肯定是一个可行的解决方法,根据链接,这应该在Typescript 2.0中修复。