I have a query that is quite simple, but I couldn't find any information on it. It's possible that I am overlooking the right keywords.
Think of a basic entity interface and class:
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;
}
}
When fetching data from the server, I usually create an Entity like this:
const entity = new Entity(serverData); //serverData resembles {id: 1, name: 'foo'}
However, I also need to generate a new Entity and send it to the server for persistence. I can't simply instantiate an empty entity and populate it because the properties must be defined:
const entity = new Entity(); // => Error: constructor needs parameter
const entity = new Entity({}); // => Error: EntityInterface requires an existing id and name
I am aware of the Partial utility in Typescript, but I'm struggling with how to apply it in this scenario. I considered changing the EntityInterface parameter in the constructor to Partial. Yet, I still want the required member typings when working with entities retrieved from the server.
Then, I pondered on having a "ServerEntity" class (with mandatory members) and a "PartialEntity" class with optional members. Nevertheless, I don't want to define the members separately for each class since they only differ in their requirement status.
I thought about extending the "PartialEntity" from the Entity class, but this approach would still necessitate proper data for the constructor:
class PartialEntity extends Entity implements Partial<EntityInterface> {}
const entity = new PartialEntity({}); // => Error: EntityInterface requires an existing id and name
I believe there is a solution or best practice to tackle this issue, but I am unable to uncover it myself. Any assistance provided would be greatly appreciated!