首页 > 解决方案 > 如何在 Typescript 中动态设置类的函数?

问题描述

我有一个带有函数a和b的基类blah。

我想扩展(或创建可能具有函数 a 或 b(或两者)的此类的实例),这样如果我创建BaseClassWithA并尝试调用,instance.b()我将收到编译错误。

具体来说,这是针对 Base CRUD Api 的,我将使用各种特定的 API 实例对其进行扩展,例如“UsersAPI”。让我们假设用户 API 可能只有“GET”作为允许的方法。所以如果我/另一个开发者去调用UsersAPI.delete,他们会得到一个编译错误。

下面是 Base API 类的示例:

export class CRUDBaseAPI<T extends ApiBaseType> {

    constructor(
        protected apiConfig: ApiConfig,
        protected http: HttpClient,
        protected errorService: ErrorService,
        protected allowedMethods: Method[] = ['get', 'update','delete'],
        protected httpConfig?: HttpConfiguration,
    ) {
    }

    public get(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
        return this.http.get<T>(`${this.apiConfig.url}/${entity.id}`, this.getFullHttpConfiguration(httpConfig)).toPromise()
            .then(returnData)
            .catch(this.handleError(`Unable to retrieve ${this.apiConfig.entityName} record.`));
    }


    public update(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
        return this.http.post(`${this.apiConfig.url}/${entity.id}`, entity, this.getFullHttpConfiguration(httpConfig)).toPromise()
            .then(returnData)
            .catch(this.handleError(`Unable to update ${this.apiConfig.entityName} record.`));
    }

    public delete(entity: T, httpConfig?: HttpConfiguration): Promise<T> {
        // TODO open confirm modal here and delete only if user confirms
        return this.http.delete(`${this.apiConfig.url}/${entity.id}`, this.getFullHttpConfiguration(httpConfig)).toPromise()
            .then(returnData)
            .catch(this.handleError(`Unable to delete ${this.apiConfig.entityName} record.`));
    }
}

function returnData(httpResponse: any) {
    return httpResponse;
}

标签: angulartypescript

解决方案


您可以在每个子类中保护 、 和 方法getupdate然后使用仅调用超级方法的简单包装器覆盖您希望公开的方法。deleteCRUDBaseAPI


推荐阅读