【问题标题】:AngularJS class type check solutionAngularJS 类类型检查解决方案
【发布时间】:2015-11-20 01:23:13
【问题描述】:

总之

如何对用户定义类的构造函数和函数进行类型检查,通常是在 AngularJS 的依赖注入环境中?

背景

我有一个带有大量数据对象的遗留 angularjs 代码。代码文件中有很多(大约 50 个)简单的 angularjs 工厂,例如:

    .factory('ContainerTypeModel', function () {
        var ContainerTypeModel = function (name, constantCode) {
            this.name = name || "";
            this.constantCode = constantCode || "";
        };
        return ContainerTypeModel;
    })

    .factory('ContainerTypeFactory', ['ContainerTypeModel', function (ContainerTypeModel) {
        var ContainerTypeFactory = {
            newByModel: function (/** ContainerTypeModel */model) {
                return new ContainerTypeModel(
                    model.name,
                    model.constantCode
                );
            }
        };
        return ContainerTypeFactory;
    }])

遗憾的是,由于业务原因,我可能需要大量更改模型的属性(如ContainerTypeModel)。这肯定会导致构造函数和工厂函数调用参数不匹配。所以我

我的调查

打字稿:

可能需要重写所有遗留代码=.=

Facebook 流量:

可能由于依赖注入而无法工作。

JSDoc:

(我目前在 WebStorm 10 中工作)仍在研究如何进行对象类型检查,例如检查 ContainerTypeFactory.newByModel(model) 中的参数。

【问题讨论】:

  • 在上个月,我将前端模型类迁移到了 typescript。结果是我几乎使用了我在模型之外的其他地方设计的接口,可能是因为所有代码都工作得很好(目前)并且日程安排很紧。所以我不能在整个项目中使用类型检查,这使得迁移几乎没有用。最后,我删除了模型中的所有特定属性定义。如果没有真正的类型检查,为什么存在。此外,我可以在这样做后快速响应模型更改。

标签: javascript angularjs typescript jsdoc


【解决方案1】:

可能需要重写所有遗留代码=.=

考虑转换:

.factory('ContainerTypeModel', function () {
    var ContainerTypeModel = function (name, constantCode) {
        this.name = name || "";
        this.constantCode = constantCode || "";
    };
    return ContainerTypeModel;
})

到:

class ContainerTypeModel {
    name: string;
    constantCode: string;
    constructor (name, constantCode) {
        this.name = name || "";
        this.constantCode = constantCode || "";
    };
}
 // later
.service('ContainerTypeModel', ContainerTypeModel)

好消息是您可以逐步做到这一点。当您进行转换时,它会开始突出显示错误……因此转换将主要由编译器引导

更多

结帐why typescriptmigrating from JavaScript to TypeScript

【讨论】:

    【解决方案2】:

    您可以使用接口来描述您的业务模型,并使用工厂来创建您的领域对象

    类似:

    interface IContainerTypeModel {
      name : string;
      constantCode: string;
    }
    
    interface IContainerTypeFactory {
      (name:string, constantCode:string) : IContainerTypeModel; 
    }
    
    angular.factory('ContainerTypeFactory', function():IContainerTypeFactory {
        var containerTypeFactory : IContainerTypeFactory = function (name, constantCode) {
            return {
               name : name,
               constantCode : constantCode
            }
        };
        return containerTypeFactory;
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2012-11-26
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 2015-04-05
      • 2022-11-01
      • 2015-04-16
      • 1970-01-01
      相关资源
      最近更新 更多