【问题标题】:Typescript: Best practices for partial entitiesTypescript:部分实体的最佳实践
【发布时间】:2020-08-29 20:04:58
【问题描述】:

我有一个非常基本的问题,但找不到任何关于它的信息,也许我错过了关键字。

想象一个基本的实体接口和类:

interface EntityInterface {
  id: number;
  name: string;
}

class Entity implements EntityInterface {
  id: number;
  name: string;

  constructor(data: EntityInterface) {
    this.id = data.id;
    this.name = data.name;
  }
}

当我从服务器加载数据时,我只需创建一个实体

const entity = new Entity(serverData); //serverData looks like {id: 1, name: 'foo'}

当然,我也想创建一个新实体并将其发送到服务器以将其持久化。 我无法实例化空实体并填充它,因为必须定义成员:

const entity = new Entity(); // => Error: constructor needs parameter
const entity = new Entity({}); // => Error: EntityInterface requires an existing id and name

我知道 Typescript 中的 Partial 实用程序,但我不知道如何在当前用例中使用它。 我想过将构造函数中的EntityInterface参数设置为Partial。 但是,当从服务器加载实体时,我绝对想要 required-members-typings。

然后我想有一个“ServerEntity”类(带有必需成员)和一个带有可选成员的“PartialEntity”类。 但我不想为每个类定义成员,因为成员的不同之处仅在于它们是必需的还是可选的。

我考虑过从 Entity 类扩展“PartialEntity”,但这仍然需要构造函数的正确数据:

class PartialEntity extends Entity implements Partial<EntityInterface> {}

const entity = new PartialEntity({}); // => Error: EntityInterface requires an existing id and name

我很确定这个问题有解决方案/最佳实践,但我自己无法弄清楚。 非常感谢任何帮助!

【问题讨论】:

    标签: typescript typescript-partial


    【解决方案1】:

    如何使用静态方法创建一个“空”对象,然后可以持久化?类似下面的东西

    class Entity implements EntityInterface {
      id: number;
      name: string;
    
      public static EMPTY(): Entity {
         return new Entity({id: node-uuid.v4(), name: defaultValue });
      }
    
      constructor(data: EntityInterface) {
        this.id = data.id;
        this.name = data.name;
      }
    }
    

    然后你就可以这样使用了

    someService.persist(Entity.EMPTY());

    【讨论】:

    • 是的,我也想过简单地提供一些虚拟/默认值,但这是正确的方法吗?你会为 id 输入什么?在实体被持久化之前,根本就没有 id。我可以将 id 设置为 null,但是我必须将 EntityInterface 修改为 id: number | null,这听起来很乱,不是吗?我认为 Partial 实用程序适用于这种用例,但也许我错了
    • 是否可以将 id 标记为可选字段? (为了清楚起见,在界面中我们会有 id?: number
    • 是的,这是可能的,但是这些字段有时会不必要地是可选的:持久化实体总是有一个 id,但是对于可选字段,我必须编写像 entity.id as number 或 if (entity.id !== undefined) {} 这样的代码。这是可能的,但我不认为这是要走的路。事实上,这就是我目前的做法;)
    • 我能想到的另一种方法是简单地分配一个随机唯一值,如果它没有提供,比如 node-uuid,(因为我假设第一次保存到服务器是一个新实体,它会有意义)唯一的缺点是使用 node-uuid 创建的唯一 id 是字符串而不是数字
    • Sido 注意:我的 ID 实际上是字符串,我在这个例子中选择了ǹumber。所以你基本上会在前端为新实体设置 ID?我认为这是一种反模式,因为后端负责在数据库中持久化并生成 ID,即使 ID 是随机 guuid。此外,您会将name 设置为什么?如果name 是新实体,我不想将其设置为初始值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多