reactjs - 如何使用扩展某个对象的泛型为状态创建接口?
问题描述
我在这里有我的状态界面。
export interface IState <T extends CashflowObject> {
cashflowToPost?: T;
cashflowList: T[];
}
我想在这里用于我的抽象类:
export default abstract class CashflowListView<T> extends React.Component<{}, IState<T>>
然后我想指定我将为实现 CashflowListView 类的其他类使用什么类型的 cashflowobject:
export default class AssetList extends CashflowListView<Asset>
这是我的对象结构:
export interface CashflowObject {
id: number;
name: string;
value: number;
taxable: boolean;
}
export interface AssetLiability extends CashflowObject {
interest: number;
}
export interface Liability extends AssetLiability{}
export interface Asset extends AssetLiability{}
但是我打字稿抱怨说,在该部分:
export default abstract class CashflowListView<T> extends React.Component<{}, IState<T>>
T atReact.Component<{}, IState<T>>
不扩展 Cashflow 对象,是有道理的....但是使 T 类型为 cashflow 会使打字稿在其他领域抱怨,例如我的 AssetList 类中的渲染函数:
render() {
return (
<div className="cashflow-table">
{this.state.cashflowList.map((asset: Asset) => <this.AssetEntry asset={asset} />)}
<AssetPost listUpdateFunction={this.callApi.bind(this)}></AssetPost>
</div>
)
}
但那我怎么写我想做的事呢?
解决方案
export default abstract class CashflowListView<T extends CashflowObject> extends React.Component<{}, IState<T>>
cashflowlistview 泛型中的 T 也必须扩展 cashflowobject。现在很明显。
推荐阅读
- python - 为每个样本长度生成随机样本并计算均值问题的标准偏差
- node.js - CircleCI:构建 Meteor 2.2 docker 应用程序 - 失败
- r - 有没有办法从 R 中的多个文件夹中读取多个 CSV 文件?
- visual-studio-code - 为什么在 VS Code 中加载 web 视图时出现错误?
- javascript - 创建文件对象类型 - Reactjs
- docker - 不要从 docker 收到任何信息
- react-native - React(本机)导航中的“跳转到”与“导航”
- android - 以编程方式在膨胀布局中添加视图
- r - R:将带有参数的函数应用于向量
- go - 你如何访问这个 Go 结构?