0.3 generic findOneBy typescript error
Problem
Issue Description With the upgrade to the new syntax in 0.3 there is a typescript issue with using `findOneBy` on a generic repro. [code block] Expected Behavior The code above should compile fine, no issues Actual Behavior I get the following typescript error. [code block] - ✖️ Yes, I have the time, and I know how to start. - ✅Yes, I have the time, but I don't know how to start. I would need guidance. - ✖️ No, I don’t have the time, but I can support (using donations) development. - ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix TypeScript Error with findOneBy in TypeORM 0.3
The TypeScript error occurs due to changes in the type definitions of the `findOneBy` method in TypeORM 0.3. The method now expects a more specific type for the arguments, which may not match the generic type used in the previous version.
Awaiting Verification
Be the first to verify this fix
- 1
Update Type Definitions
Ensure that the entity type used in the `findOneBy` method matches the expected type in TypeORM 0.3. If using a generic type, specify the exact type for the entity.
typescriptconst user = await repository.findOneBy<User>({ id: 1 }); - 2
Check TypeORM Configuration
Verify that your TypeORM configuration is correctly set up to use the new syntax. Update any outdated configurations that may conflict with the new version.
typescriptimport { DataSource } from 'typeorm'; const dataSource = new DataSource({ /* your config */ }); - 3
Install Type Definitions
Ensure that you have the latest type definitions installed for TypeORM. Run the following command to install the necessary types.
bashnpm install --save-dev @types/typeorm - 4
Refactor Generic Usage
If you are using generics in your repository, refactor the code to explicitly define the type of the entity being queried. This will help TypeScript infer the correct types.
typescriptclass User { /* user properties */ } const userRepo = dataSource.getRepository<User>(User); - 5
Test the Changes
Run your TypeScript compiler to check if the error persists. If the code compiles without errors, the issue is resolved.
bashtsc --noEmit
Validation
To confirm the fix worked, ensure that the TypeScript compiler runs without errors when executing the code that uses `findOneBy`. Additionally, verify that the expected data is returned from the database.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep