typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
34.22k stars 6.31k forks source link

loadRelationCountAndMap doesn't infer (Typescript) #9353

Open alielkhateeb opened 2 years ago

alielkhateeb commented 2 years ago

Issue Description

If my entities look like this:

@Entity({ name: 'libraries' })
export class Library {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @OneToMany(() => Book, (book) => book.library)
  books: Book[];
}

@Entity({ name: 'books' })
export class Book {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @ManyToOne(() => Library, (lib) => lib.books)
  @JoinColumn({ name: 'library_id' })
  library: Library;
}

And my Library Dto looks like this:

export class LibraryDto {
  @IsUUID()
  id: string;

  @IsNumber()
  bookCount: number;
}

How can I make this function work with typescript? async findLibraryById(libraryId: string): Promise<LibraryDto>

Running code like this:

    const library = await this.librariesRepository
      .createQueryBuilder('library')
      .loadRelationCountAndMap('library.bookCount', 'library.books')
      .where({ id })
      .getOne();

    console.log(library.bookCount); // This will not work, Typescript complains that bookCount doesn't exist on Library

Expected Behavior

I expect I'm able to reach the property I selected using loadRelationCountAndMap

Actual Behavior

There is absolutely no way I found to bypass the typescript issue: Property 'bookCount' does not exist on type 'Library'

My Environment

Dependency Version
Operating System
Node.js version 16.17.0
Typescript version 4.6.4
TypeORM version 0.3.9

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql I don't know
aurora-postgres I don't know
better-sqlite3 I don't know
cockroachdb I don't know
cordova I don't know
expo I don't know
mongodb I don't know
mysql I don't know
nativescript I don't know
oracle I don't know
postgres YES
react-native I don't know
sap I don't know
spanner I don't know
sqlite I don't know
sqlite-abstract I don't know
sqljs I don't know
sqlserver I don't know

Are you willing to resolve this issue by submitting a Pull Request?

denysovvl commented 1 year ago

+1

NicolasPotierA commented 1 year ago

+1