Unlocking the potential of partial entities in Typescript: A guide to best

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!

Answer №1

Consider implementing a static method in your Entity class to create an object that can be saved persistently. Here is an example:

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;
  }
}

You can then utilize it like so:

someService.persist(Entity.EMPTY());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the return type based on the parameter type

Here is an example of my function: const safeIdCastToNumber = (id: string | null | undefined) => isNil(id) ? id : Number(id) When calling safeIdCastToNumber, I can use an id parameter with a type union string | null | undefined, as well as one with a t ...

After importing this variable into index.ts, how is it possible for it to possess a function named `listen`?

Running a Github repository that I stumbled upon. Regarding the line import server from './server' - how does this API recognize that the server object has a method called listen? When examining the server.ts file in the same directory, there is ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Using `await` or `then` with a Promise object can lead to varying results

Here is an example of code that compiles successfully import yargs from "yargs"; const parser = yargs(process.argv.slice(2)). usage("$0 [filename]"). demandCommand(1); async function main() { const argv = await parser.argv ...

Tips for creating a person card like the one seen in MS Teams' WhoBot

Is there a way to create a person card with status and icons that resembles the fluent UI react persona component in MS adaptive cards for a bot framework project? I am looking to achieve something like the whobot person card shown below, including all att ...

ES6 Setters | warning TS2300: Identical identifier detected

Currently, I am developing a class for an Angular 2 component that involves the use of Input/Output decorators along with a setter as shown below: export class ItemDetails { // Assigning 'item' to a locally scoped property @Input(' ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

Is it possible to selectively disable the <span> tag in Angular?

I have encountered a situation where I need to dynamically disable a button and show a tooltip based on specific conditions in an Angular application. Here is the current code that I am using: <span *ngIf="(hourEnabled && theTest && ...

Changes made in the Firestore console do not automatically activate the snapshotChanges subscription

I'm facing an issue with subscribing to a document in Firestore using AngularFire. Even after making changes to the document through the Firestore console, I don't see any updates reflected in the pulled data, even after refreshing locally. The D ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Positioning of SVG text along the y-axis

https://i.sstatic.net/FkBRo.png In my project, I am creating a population pyramid using d3 in combination with react. While d3 handles the calculations, react is responsible for rendering the DOM elements. Everything is going smoothly so far, except for p ...

Error in BehaviorSubject<any[]>: Unable to assign type 'any[] | null' to type 'any[]'

When I try to pass a BehaviorSubject from my CacheService to a component @Input() that expects an array, I encounter an error stating that 'any[] | Type 'any[] | null' is not assignable to type 'any[]'. This occurs even though the ...

Checking the types for object literals returned from Array.map functions

Check out this demonstration I made in the TypeScript playground: interface Test{ a: string b: string } const object: Test = { a: 'b', b: 'c', } function testIt(): Test[] { const data = [{b: '2', c: &apo ...

Can you point me to the location where the 'req' parameter is specified?

I've been exploring a new authentication approach detailed in this article. One issue I'm encountering is locating where the req parameter is declared in the snippet below. It seems like my code won't compile because this parameter isn&apos ...

determine the keys of the object properties stored in an array

Is there a method to generate an array-like list of potential values consisting of object property values within an array? Here is an example object: const columns: SomeType[] = [ { name: "first", someProp: true }, { name: "second", ...

What is the best way to define this.someProperty in a React component using TypeScript?

I'm encountering an issue with TS2339: Property 'someProperty' does not exist on type ''. I am attempting to add a new property to my React component using this.someProperty. interface MyComponentState { allClear: boo ...

Tips for asynchronously subscribing to an observable from an array in Angular

I am facing a scenario where I have an array containing IDs and I need to subscribe to observables for each ID in a sequential order. I attempted to use a foreach loop but the responses were not in the desired order. Then, I tried to implement a for loop a ...

What is the best way to create a dynamic icon using React and TypeScript?

Excuse me, I am new to using React and TypeScript. I'm having trouble getting the icon to change based on the status in AppointmentType. The body color is working fine, but the icons are not changing. Can someone please help me solve this issue? const ...

Tips for updating the class of the body in an Angular 2 and Typescript project

When it comes to managing different classes for the login page versus other pages in an application, there is a need to change the body element's class once the user has logged in. Here is how I am attempting to achieve this: index.html <body [ng ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...