首页 > 解决方案 > Typescript:部分实体的最佳实践

问题描述

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

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

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。但是当从服务器加载实体时,我绝对想要所需的成员类型。

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

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

class PartialEntity extends Entity implements Partial<EntityInterface> {}

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

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

标签: typescripttypescript-partial

解决方案


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

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());


推荐阅读