下面是一个例子来说明一个问题:
首先,我有一个 React 的 Typescript 定义,其中我们有一个组件的定义:
class Component<P, S> implements ComponentLifecycle<P, S> {
static propTypes: ValidationMap<any>;
static contextTypes: ValidationMap<any>;
static childContextTypes: ValidationMap<any>;
static defaultProps: Props<any>;
constructor(props?: P, context?: any);
setState(f: (prevState: S, props: P) => S, callback?: () => any): void;
setState(state: S, callback?: () => any): void;
forceUpdate(callBack?: () => any): void;
render(): JSX.Element;
props: P;
state: S;
context: {};
refs: {
[key: string]: Component<any, any>
};
}
然后在应用程序中,我创建了扩展组件的类。
class App extends React.Component<any, any> {
}
我想要一个返回组件实例的函数。
function Test<T extends React.Component<any, any>>(): T
{
return App;
}
Typescript 编译器不允许我这样做。错误是:
“typeof App”类型中缺少属性“setState”
我不明白,因为类应该从 Component 继承一切。