mminnie
mminnie

Reputation: 152

Call static function of Generic Type from Generic Type in typescript

I have a function in a service class that is passed a generic type extending my Bean class. I want the function to call a static function in the Bean class to create an array of Beans. My code in the playground compiles, however I get a runtime browser error of

Uncaught TypeError: ctor.constructor.fromEntryList is not a function

If I remove the .constructor I get the array of beans created, however there is a typescript error without .constructor.

I am lost at how to correctly typescript code this function. Any help is much appreciated as I have unsuccessfully found a prior answer on SO.

Code:

// Base class that will be extended
class Bean {
    id: number;

    static fromEntryList<T1>(ctor: new (p: number) => T1, numbers: Array<number>): Array<T1> {

        let result: Array<T1> = [];
        for (let anumber of numbers) {
            result.push(new ctor(anumber));
        }
        return result;
    }


    constructor(p: number) {
        this.id = p;
    }
}

// Base service class that will be extended
class BeanService {


    constructor() { }

    get_entry_list<T extends Bean>(ctor: new (p: number) => T): T[] {
        let x: T[] = (<typeof Bean>ctor.constructor).fromEntryList(ctor, [1, 2, 3, 4]);
        return x;
    }
}

let service = new BeanService();
let beans: Bean[] = service.get_entry_list(Bean);

code in playground

Thanks.

Upvotes: 0

Views: 1383

Answers (1)

OJ Kwon
OJ Kwon

Reputation: 4641

in your param definition in get_entry_list, it only defines type of ctor but missing static method interface, so accessing it raises compiliation error while runtime can access those property correctly works.

You may able to define constructor interface,

interface XXX<T> {
  new(p: number): T;
  fromEntryList<U>(ctor: new (p: number) => U, numbers: Array<number>): Array<U>;
}

which is basically representation of Bean then use it for param's signature

get_entry_list<T extends Bean>(ctor: XXX<T>): Array<T>

allows ctor supplied in get_entry_list can access static method.

playground

Upvotes: 2

Related Questions