Search code examples
typescriptgenericstypeorm

How to initialize a TypeORM Repository based on a Generic Type "T"?


I would like to Initiate a TypeORM Repository based on a Generic Type.

for instance:

import { Connection, Repository } from 'typeorm';

export class GenericService<T> {
    private repository: Repository<T>;

    constructor(connection: Connection) {
        this.repository = connection.getRepository(T);
        // 'T' only refers to a type, but is being used as a value here.ts(2693)
    }

    public async list(): Promise<T[]> {
        return await this.repository.find();
    }

}

But I was not able to pass Generic Type to the ORM Repository Factory.

'T' only refers to a type, but is being used as a value here.ts(2693

How can I create this generic service based on the Generic Type?

PS. I did exactly this with C# and works like a charm. it saves me a lot of time


Solution

  • You can't use types as values in Typescript, so you'll need to use the generic to type check the value instead:

    import { Connection, Repository } from 'typeorm';
        
    export class GenericService<T> {
       private repository: Repository<T>;
        
       constructor(connection: Connection, repo: T) {
          this.repository: T = connection.getRepository(repo);
       }
        
       public async list(): Promise<T[]> {
          return await this.repository.find();
       }
        
    }