从可选抽象方法的参数构建抽象类函数参数

问题描述 投票:0回答:1

[这里,我使用此BaseRepository方法具有readOneDirect类。 BaseRepository具有此可选方法readOneByRelationOrganizationRepositoryBaseRepository扩展并实现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}的期望值?

typescript class abstract-class es6-class
1个回答
0
投票

将可选界面中的道具从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>
}
© www.soinside.com 2019 - 2024. All rights reserved.