在TypeScript

时间:2017-07-15 12:46:54

标签: angular typescript

我正在使用Angular 4开发应用程序。在我的代码中,我想从嵌套泛型类创建一个实例,如下代码所示:

export class Page<T>
{
    constructor(c: { new(): T; }){
       this.FilterData = new c();
    }
    TotalItems: number;
    PageSize: number;
    CurrentPage: number;
    TotalPage: number;
    FilterData: T;
}

export class Filter<T>
{
    constructor(c: { new(): T; })
    {
        this.AdvanceData = new c();
    }
    AdvanceData: T
    IsAdvance: boolean;
    OrderMeThod: string;
    OrderBy: string;
    KeyWord: string;
}
export class Client
{
Name:string;
}

我不知道如何从Page<Filter<Client>>初始化FilterClient在构造函数中初始化的对象。我尝试过如下:new Page<Filter<Client>>();但它没有用。 请帮我解决这个问题。感谢

1 个答案:

答案 0 :(得分:0)

让您传递的函数返回新实例,而不是调用new。 示例:

interface Generator<T> {
    generate(): T
}

export class Page<T> {
    constructor(c: Generator<T>) {
        this.FilterData = c.generate();
    }

    TotalItems: number;
    PageSize: number;
    CurrentPage: number;
    TotalPage: number;
    FilterData: T;
}

export class Filter<T> {
    constructor(c: Generator<T>) {
        this.AdvanceData = c.generate();
    }

    AdvanceData: T;
    IsAdvance: boolean;
    OrderMeThod: string;
    OrderBy: string;
    KeyWord: string;
}

export class Client {
    Name: string;
}

const clientGenerator: Generator<Client> = {
    generate: () => new Client()
};

const filterGenerator: Generator<Filter<Client>> = {
    generate: () => new Filter(clientGenerator)
};

const pageOfFilterOfClient: Page<Filter<Client>> = new Page(filterGenerator);