'User' 类型的参数不可分配给 'EntityTarget<BaseEntity>' 类型的参数

Argument of type 'User' is not assignable to parameter of type 'EntityTarget<BaseEntity>'

我正在向函数发送一个 “实体” 并在函数内部使用它。但它给了我这个错误。

export type Entities = User | Blog | Service
import AppDataSource from '../database'
import { Entities } from '../entity/index'
import User from '../entity/User'

const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

Argument of type 'Entities' is not assignable to parameter of type 'EntityTarget'. Type 'User' is not assignable to type 'EntityTarget'.

enter image description here

您需要从 EntityTarget 扩展:

export interface User extends EntityTarget<unknown> {}
export interface Blog extends EntityTarget<unknown> {}
export interface Service extends EntityTarget<unknown> {}

export type Entities = User | Blog | Service

import AppDataSource from '../database'
import { Entities } from '../entity/index'
import User from '../entity/User'

const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

我在上面的代码中遇到这样的错误“'X' type argument cannot be assigned to 'X' type parameter” 我这样做是为了解决问题:

import { EntityTarget } from 'typeorm'
import AppDataSource from '../database'

export type _User = EntityTarget<'User'>
export type _Blog = EntityTarget<'Blog'>
export type _Service = EntityTarget<'Service'>

export type Entities = _User | _Blog | _Service

export const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

但我不确定它是否健康

我这样解决了问题,似乎更符合逻辑。 谢谢

import { EntityTarget } from 'typeorm'
import AppDataSource from '../database'

const getList = async <E>(entity: EntityTarget<E>) => {
  const list = await AppDataSource.manager.find(entity)
}