[这里,我使用此BaseRepository
方法具有readOneDirect
类。 BaseRepository
具有此可选方法readOneByRelation
。 OrganizationRepository
从BaseRepository
扩展并实现readOneByRelation
。
我正在BaseRepository
中创建一个函数,该函数是此方法和其他可选基本方法的组合。
这是我的尝试:
type maybeProps2<T> = T extends (...args: any) => any ? Parameters<T>[0] : never
export interface BaseRepository<T> {
readOneByRelation?(props: any): Promise<T | undefined | typeof NOT_RUN>
readOneByUnique?(props: any): Promise<T | undefined | typeof NOT_RUN>
readOneByJoin?(props: any): Promise<T | undefined | typeof NOT_RUN>
}
export abstract class BaseRepository<T> extends Repository<T> {
async readOneDirect(_props:
maybeProps2<BaseRepository<T>['readOneByRelation']> |
maybeProps2<BaseRepository<T>['readOneByUnique']> |
maybeProps2<BaseRepository<T>['readOneByJoin']>
) {
const props: StrictUnion<typeof _props> = _props
if (this.readOneByRelation) {
const entity = await this.readOneByRelation(props)
if (entity !== NOT_RUN) return entity
}
if (this.readOneByUnique) {
const entity = await this.readOneByUnique(props)
if (entity !== NOT_RUN) return entity
}
if (this.readOneByJoin) {
const entity = await this.readOneByJoin(props)
if (entity !== NOT_RUN) return entity
}
return NOT_RUN
}
}
@EntityRepository(Organization)
export class OrganizationRepository extends BaseRepository<Organization> {
name = Organization.name
relations = []
async readOneByRelation(_props: { plan: Plan }) {
const props: StrictUnion<typeof _props> = _props
if (props.plan?.organization) return props.plan.organization
return undefined
}
}
const or = new OrganizationRepository()
or.readOneDirect({ })
出于某些原因,将鼠标悬停在readOneDirect
_props上是any
。是否可以将其设为{plan: Plan}
的期望值?
将可选界面中的道具从props: any
更改为props: never
就可以了。
export interface BaseRepository<T, S extends BaseRepository2<T, S>> {
readOneByRelation?(props: never): Promise<T | undefined | typeof NOT_RUN>
readOneByUnique?(props: never): Promise<T | undefined | typeof NOT_RUN>
readOneByJoin?(props: never): Promise<T | undefined | typeof NOT_RUN>
}