首页 > 解决方案 > 如何使用扩展某个对象的泛型为状态创建接口?

问题描述

我在这里有我的状态界面。

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>
        )
    }

但那我怎么写我想做的事呢?

标签: reactjstypescriptgenericsinheritanceinterface

解决方案


export default abstract class CashflowListView<T extends CashflowObject> extends React.Component<{}, IState<T>> 

cashflowlistview 泛型中的 T 也必须扩展 cashflowobject。现在很明显。


推荐阅读