【问题标题】:Implementing a generic class based on another generic class in Angular 7基于Angular 7中的另一个泛型类实现一个泛型类
【发布时间】:2020-05-19 20:00:29
【问题描述】:

我在 TypeScript 中有以下接口和类:

export interface PageInterface<T> {
    count: number;
    previous: string;
    next: string;
    results: T[];
}

export class Page<T> implements PageInterface<T> {}

----------------------------------------------------------

export interface AdapterInterface<T> {
    adapt(item: any): T;
}

我需要实现PageAdapter&lt;Page&lt;T&gt;&gt;

有可能吗?我尝试了以下方法,但最终出现错误(Type 'Page' si not generic):

export class PageAdapter<Page> implements AdapterInterface<Page> {
    adapt(item: any): Page<T> {
        return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
    }
}

如果我将Page&lt;T&gt; 而不是Page 放在第一行,它根本不起作用。

我该如何实现?

非常感谢,

【问题讨论】:

    标签: angular typescript class generics interface


    【解决方案1】:

    我想你正在寻找这样的东西:

    export class PageAdapter<T> implements AdapterInterface<Page<T>> {
        adapt(item: any): Page<T> {
            return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
        }
    }
    

    因此,例如,PageAdapter&lt;string&gt; 可以用作AdapterInterface&lt;Page&lt;string&gt;&gt;。如果你真的需要泛型类型参数是Page-like 类型,你可以这样写:

    export class PageAdapter2<P extends Page<any>> implements AdapterInterface<P> {
        adapt(item: any): P {
            return new Page(item['count'], item['previous'], item['next'], item['results']) as P;
        }
    }
    

    在这里,PageAdapter&lt;Page&lt;string&gt;&gt; 可以用作AdapterInterface&lt;Page&lt;string&gt;&gt;。然而,这个版本的类型不是很干净,需要type assertions 来实现。

    希望有所帮助;祝你好运!

    Playground link to code

    【讨论】:

    • 第一段代码完成了我所需要的。非常感谢!
    猜你喜欢
    • 2014-08-02
    • 1970-01-01
    • 2021-12-25
    • 2021-05-05
    • 2021-10-31
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多