How to create generic function in TS and TypeORM?

Tags: , ,



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?

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.


Source: stackoverflow