1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Passing class as parametr with generics

Discussão em 'Angular' iniciado por Eggy, Junho 12, 2025.

  1. Eggy

    Eggy Guest

    Here is live example(Sorry, had to use url shortener, link characters break markup) TypeScript version 1.6.2

    I have two services across my angular2 application. Let's name them ServiceA and ServiceB. Each one of them, have similar data structure, so I decided to use extends to not write same code twice. The class which will provide data structure is called Pages and looks like this:

    class Pages {
    public pages = [];
    private active: number = 0;

    get current() {
    return this.pages[this.active];
    }

    constructor(private page, public name: string) { }

    changeActive(page: number): void {
    this.active = page;
    }

    addPage(): void {
    this.pages.push(
    new this.page(this.name + (this.pages.length + 1))
    );
    }
    }


    pages array will contains class instances unique for each service. Here is an example of one for ServiceA:

    // ServiceA.pages will be filled with instanced of this class.
    // ServiceB.pages will use different class but the constructor
    // will be simmilar(will take only one argument name: string)
    class PageA {
    public uniquePropertyA: string = 'Hello World!';
    constructor(public name: string) { }
    // unique methods of PageA
    }


    Services will look quite similar. Here preview of ServiceA:

    class ServiceA extends Pages {
    constructor() {
    super(PageA, 'ServiceA #');
    }
    }

    // demo
    var sA = new ServiceA();
    sA.addPage();
    sA.current. // Hey there is no auto complete!


    This example works fine, however I do not get autocomplete each page because its type is any. I was trying to use "generics" to make it work, sadly with no success but here it is. Basicly I want to know which constructor I passed to Pages class, so I can get right types.

    I hope you guys can help me with this one.

    Continue reading...

Compartilhe esta Página