How to create generic function in TS and TypeORM?

2.4k views Asked by At

How to create generic function in TS and TypeORM?

I have a multiple functions like this:

    async getOrderName(id: number): Promise<string> {
        const order = await this.conn.getRepository(Order).findOne(id);
        return `${order.name}`;
    }
    async getServiceName(id: number): Promise<string> {
        const service = await this.conn.getRepository(Service).findOne(id);
        return `${service.name}`;
    }

and another ... another... another...

so, i need to create one generic function to use with the many entities

can somebody tell me how to create that function?

3

There are 3 answers

2
concat On BEST ANSWER

You should be able to take advantage of duck typing to generalize the functionality over EntityTargets:

interface NamedThing {
    name: string
}
async getName<Entity extends NamedThing>(id: number, target: EntityTarget<Entity>): Promise<string> {
    const named = await this.conn.getRepository<Entity>(target).findOne(id);
    return `${named && named.name}`;
}

// equivalent calls are now `getName(id, Order)`, `getName(id, Service)`, etc.
2
MGot90 On

I highly recommend checking out https://www.typescriptlang.org/docs/handbook/generics.html

You can pass in type T (and return type T) if you'd like.

  async getServiceName<T>(id: T): Promise<string> {
            const service = await this.conn.getRepository(Service).findOne(id);
            return `${service.name}`;
        }

Obviously you would have to overload findOne function to take any number of type T's. Or you could be super lazy and use any keyword in the lowest level.

0
Benjamin Merchin On

You can use

const a = MyRepositoryName

and pass a as an argument to the function