【问题标题】:How do make an interface for a state using generics which extend a certain object?如何使用扩展某个对象的泛型为状态创建接口?
【发布时间】:2021-05-19 10:22:32
【问题描述】:

这里有我的状态界面。

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

React.Component&lt;{}, IState&lt;T&gt;&gt; 处的 T 不扩展 Cashflow 对象,这是有道理的....但是将 T 设为 cashflow 类型会使 typescript 在其他领域抱怨,例如我的 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>
        )
    }

但是我将如何写我想要做的事情呢?

【问题讨论】:

    标签: reactjs typescript generics inheritance interface


    【解决方案1】:
    export default abstract class CashflowListView<T extends CashflowObject> extends React.Component<{}, IState<T>> 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 2019-04-06
      • 1970-01-01
      • 2017-06-11
      • 2021-08-28
      • 1970-01-01
      • 2018-04-09
      • 2019-09-05
      相关资源
      最近更新 更多