【问题标题】:Typescript:force method to accept given Class reference打字稿:强制方法接受给定的类引用
【发布时间】:2020-09-21 01:38:17
【问题描述】:

如果我有这个:

export class JobFields implements EntityFields {}如果有帮助,它也可以从 EntityFields 扩展

我可以让我的方法只接受实现/扩展EntityFields 的类的引用吗?喜欢:

private test(entity: EntityFields) {} //this does not work, it accept anything

我正在创建自动从包含后端实体信息的类中读取的组件。我只是想强制/诱导开发者给它正确的类引用。

this.test(JobFields); //this should work
this.test(JobView);   //while this shouldn't

【问题讨论】:

    标签: typescript class types interface


    【解决方案1】:

    您可以在 Typescript 中编写自定义保护函数

    这是一个例子。考虑以下几点:

    IEntityFields {
        prop1: string,
        fieldprop2: {prop: string},
        metaData: {azureFilePath: string}
    }
    
    export const instanceOfEntityFields = (_o: any): _o is EntityFields => {
      return 'prop1' in _o && 'fieldprop2' in _o.metaData && 'azureFilePath' in _o.metaData;
    };
    

    然后在您的方法调用中,您可以使用检查...

    private test(entity: EntityFields) {
        return instanceOfEntityFields(entity)
            ? //...do work here
            : false;
    }
    

    这是一个很酷的模式,因为您可以堆叠支票; 例如

    export const instanceOfJobFields = (_o: any): _o is JobFields => {
          return 'jobprop1' in _o && instanceOfEntityFields(_o);
        };
    

    【讨论】:

    • 我喜欢这样,但是当我用其他东西(如字符串或数字)调用“测试”方法时,tslint 仍然不会说任何东西,所以它对我没有帮助
    • tslint 应该捕获调用具有错误输入对象类型的方法。您确定 IDE 安装并启用了 tslint 和/或 eslint 吗?此外,还要仔细检查项目的 tslint 配置。
    • 在您的示例中,它在运行时中断,没有 tslint 告诉我我给了它错误的实体,抱歉,如果我不够清楚
    • 如果你真的用一些属性定义了接口,它会告诉你类型不匹配。看来我可以编辑stackblitz.com/edit/typescript-biuvvg
    猜你喜欢
    • 2022-01-26
    • 2023-03-23
    • 2017-09-29
    • 1970-01-01
    • 2017-05-16
    • 2022-09-23
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多