【问题标题】:Flowtypes, how to reduce duplication in Model-like class definitionsFlowtypes,如何减少类模型类定义中的重复
【发布时间】:2018-02-08 22:58:58
【问题描述】:

我们目前正在采用流程,我遇到了一个有趣的问题。在我们的一个代码库中,我们使用的模式大致如下。

我们有“模型”,代表“值对象”或“数据传输对象”。所以我们的“模型”保持着单一的记录。这是最简单的模型之一:

class UserModel extends BaseModel {

}

BaseModel 定义了一个构造函数,大致如下:

class BaseModel {

  constructor(properties: Object) {
    for (let key in properties) {
      this[key] = properties[key];
    }
  }
}

这允许你做这样的事情:

const user = new UserModel({
  firstName: 'Evert',
  lastName: 'Pot'
});

我正在寻找一种优雅的方式来为此添加类型安全性。我面临的一个问题是,我希望在传递 UserModel 实例的地方以及在构造 UserModel 期间的类型安全。理想情况下,我希望 UserModel 不允许以不完整/无效的形式实例化。

我第一次通过这个(达到这个目标)是这样的:

/* @flow */

interface UserInterface {

  firstName: string;
  lastName: string;

}

class UserModel extends BaseModel implements UserInterface {

   firstName: string;
   lastName: string;

   constructor(props: UserInterface) {
      this.firstName = props.firstName;
      this.lastName = props.lastName;
   }

}

const user = new User({
   firstName: 'Evert',
   lastName: 'Pot'
});

我将 UserInterface 重新用作构造函数的类型以及类本身。

这可行,但缺点是我将每个属性名称重复 4 次。定义接口时,定义类时,在构造函数中设置属性时。

对于流量来说还很新,我想知道是否有办法减少这种情况。我可以删除重复的属性名称吗?

【问题讨论】:

  • 我想知道您是否真的需要所有这些课程? const user: UserInterface = { firstName: 'Evert', lastName: 'Pot' }; 有什么问题?
  • @AlekseyL。好问题。我们的真实用例在各种模型类上有许多方法。

标签: javascript node.js flowtype


【解决方案1】:

您可以更改您的 BaseModel 以拥有一个用于以下属性的内部字典:

class BaseModel {
  props: Object = {}

  constructor(props: Object) {
    this.props = props
  }
}

您甚至可以使用代理来设置动态 getter/setter,例如 this answer 或迭代您的属性并使用 defineProperty(类似于 this fiddle I whipped up。您也可以添加 get 方法或其他东西为您访问这些值(类似于Backbone)。

然后,如果您愿意,您可以将 UserInterface 作为类型并执行以下操作:

type UserInterface = {
  firstName: string;
  lastName: string;
}

class UserModel extends BaseModel {
  // The constructor is only necessary for flow to limit the values allowed
  constructor(props: UserInterface) {
    super(props)
  }
}

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2011-06-27
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多