【发布时间】: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