How do I create a new object of type "T" in a generic class in typescript?

I have the following service

@Injectable()
export class CollectionService<T> {    

    constructor(protected http: Http) {}

    factory<T>(item?: any): T {
        let type: new (item?: any) => T;
        return new type(item);
    }

    item(id): Observable<T> {
        return this.http.get(`${this.baseUrl}/${id}`)
            .map((resp: Response)=> this.factory(resp.json()))
            .catch((error: any) => {
                return Observable.throw(error);
            });
    }
}

      

Compilation completed successfully, but I have the following error in the browser console.

TypeError: type is not a constructor
at PortalVideoService.webpackJsonp.../../../../../src/app/services/collection/collection.service.ts.CollectionService.factory (http://localhost:4200/main.bundle.js:1568:16)
at http://localhost:4200/main.bundle.js:1580:64
at Array.map (native)
at MapSubscriber.project (http://localhost:4200/main.bundle.js:1580:29)
at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (http://localhost:4200/vendor.bundle.js:24034:35)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (http://localhost:4200/vendor.bundle.js:13455:18)
at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:101703:38)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2838:31)
at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:93420:37)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2837:36)

      

How do I create an object of type T?

+3


source to share


3 answers


The name T

only exists at compile time. You can use it for type checking, but you cannot create an object of type T unless you have access to the constructor.

Modify the definition factory

to use the runtime type constructor as an argument:



factory<T>(type: {new(): T}, item?: any): T {
    return new type(item);
}

      

Now the only problem will be where you get the type argument; you probably also need to pass it to the method item()

so the compiler knows what type to make Observable<T>

.

+4


source


No need to do what you do, just

.map((resp: Response)=> resp.json())

      

and if you want a custom response type to do



.map((resp: Response)=> resp.json() as CustomResponse) 

      

where CustomResponse

is the interface.

0


source


You can pass the constructor as a generic class rather than a method.

export class CollectionService<T, CT extends { new(item?: any): T }> {    

    constructor(protected http: Http, private type: CT) {}

    factory(item?: any): T {
        return new this.type(item);
    }

    // ...
}

class CustomClass {
    constructor(private item?: any) {
    }
 };


let cs = new CollectionService<CustomClass, { new(): CustomClass }>(http, CustomClass);
console.dir(cs.factory(123));

// UPDATE
class CustomClassService extends CollectionService<CustomClass, { new(): CustomClass }> {
    constructor(protected http: Http) {
        super(http, CustomClass);
    }
}

let ccs = new CustomClassService(http);
console.dir(ccs.factory(456));

      

0


source







All Articles