Write a TypeORM @Transaction method, when use this method the IDE report error as "Invalid number of arguments, expect 2"

Viewed 3746

I write a Transaction method as typeorm offical document(https://github.com/typeorm/typeorm/blob/master/docs/decorator-reference.md#transaction-transactionmanager-and-transactionrepository)

the code is below:

@Transaction('some-db-connection')
public async savePhoto(record: DeepPartial<Photo>, 
                       @TransactionManager() manager: EntityManager) {
    return await manager.save<DeepPartial<Photo>>(record)
}

When I use this method in some where as below:

await someRepo.savePhoto(record)

Both VS Code and WebStorm report error as "Invalid number of arguments, expect 2". Can anyone knows how to let IDE do not report this error? Thanks!

P.S.

Although IDE report error, the code can be execute without error

All my code are TypeScript code in .ts files

2 Answers

Many of my service methods accept an optional EntityManager with a default of getManager(). This way, the calling method can decide if everything should be wrapped in a transaction or not. No decorators needed.

import { getManager, getConnection } from "typeorm"

async function savePhoto(photo: Photo, manager = getManager()): Promise<Photo> {
  return manager.save(photo)
}

async function savePhotoWithTransaction(photo: Photo): Promise<Photo> {
  return getConnection().transaction((manager) => {
    // do some other stuff inside the transaction
    return savePhoto(photo, manager)
  })
}

async function savePhotoWithoutTransaction(photo: Photo): Promise<Photo> {
  return savePhoto(photo)
}

Two solutions work for me:

  • Make 2nd argument optional should works fine, as already mentioned.

    @Transaction()
    public async savePhoto(
        photo: Photo, 
        @TransactionManager() manager?: EntityManager
    ): Promise<Photo> {
        return manager.save(photo);
    }
    
  • Also, you can suppress errors in your .ts files

    // @ts-ignore
    await savePhoto(photo);
    
Related