如何在打字稿中强类型反应组件?
问题描述:
我正在尝试为反应Component
创建强类型的基类,其中包括RouteComponentProps
。我想实现的是这样的:如何在打字稿中强类型反应组件?
import * as React from "react";
interface IDetailsModel {
show: string;
}
interface IComponentProps<TParams, TProps> extends ReactRouter.RouteComponentProps<TParams, {}>, TProps {
}
class ComponentBase<TParams, TProps> extends React.Component<IComponentProps<TParams, TProps>, {}> {
}
class Details extends ComponentBase<{ id: number }, { show: string; }> {
render() {
var show = this.props.show;
var id = this.props.params.id;
return (
<div className="container"></div>
);
}
}
这不是工作,因为我IComponentProps
不能的方式,我想它来扩展TProps
。
当我用替代混凝土界面TProps在IComponentProps定义这样的,一切正常:
interface IComponentProps<TParams, TProps> extends ReactRouter.RouteComponentProps<TParams, {}>, IDetailsModel{
}
是否有任何其他的方式来实现这一目标?
答
我敢肯定的intersection type应该这样做:
interface IComponentProps<TParams> extends ReactRouter.RouteComponentProps<TParams, {}> {}
class ComponentBase<TParams, TProps> extends React.Component<IComponentProps<TParams> & TProps, {}> {}
class Details extends ComponentBase<{ id: number }, { show: string; }> {
render() {
var show = this.props.show;
var id = this.props.params.id;
return (
<div className="container"></div>
);
}
}
它没有工作,非常感谢。有趣的是我以前试过这个,但看起来像ReSharper报告这个问题是不正确的。在您的答案之后,我已经检查了ReSharper关闭并且它工作。 – mmoron