A class B that shares identical field characteristics with Class A

I'm currently exploring methods to define a second class that mirrors the fields of the first one. It seems that this may not be feasible, as I discovered during compilation time that class fields are not allowed. Even at runtime, utilizing Object.keys for fields is only achievable after initialization and would return defined values.

Situation:

class Entity {
  public id!: string;

  public uuid!: string;

  public firstname!: string;

  public lastname!: string;
}

Now, I aim to introduce weights (potentially requiring minor adjustments on client code).

Logically, I either need to include weights within the same class if feasible or in a separate similar class like:

class EntityWeights {
  public id!: number;

  public uuid!: number;

  public firstname!: number;

  public lastname!: number;
}

Subsequently, it would be essential to manage both classes to maintain consistent code (although not ideal).

If I opt for modifying solely the Entity class to incorporate weights, I would proceed as follows:

class Entity {
  public id!: [string, number];

  public uuid!: [string, number];

  public firstname!: [string, number];

  public lastname!: [string, number];
}

Upon attempting this, it became evident that in client code - where I pass const entity = new Entity({___}) to other segments such as putInDB(entity) - I encountered difficulties refactoring to exclusively utilize either weights or values.

How would you approach this scenario?

Answer №1

Utilizing the implements keyword allows you to restrict EntityWeights to include all properties of Entity with type

Record<keyof Entity, unknown>
. Each property is required, while their types can be defined freely.

class EntityWeights implements Record<keyof Entity, unknown> {
  public id!: number;
  public uuid!: number;
  public firstname!: number;
  public lastname!: number;
}

An error will occur if any properties are missing:

class EntityWeights2 implements Record<keyof Entity, unknown> {
//    ^^^^^^^^^^^^^^ Error: Type 'EntityWeights2' is missing the following properties from type 'Record<keyof Entity, unknown>': firstname, lastname(2420)
  public id!: number;
  public uuid!: number;
}

Playground

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

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

Ways to dynamically alter the appearance of a conditionally displayed element in Svelte

Currently experimenting with SvelteKit 1.0 by building a simple to-do app, but I'm having trouble implementing conditional text strikethrough. My goal is to have the text style change to include a strikethrough when the user clicks on the checkbox nex ...

"Unexpected token l in JSON at position 0" is causing an error, yet miraculously the code still functions - how is this possible?

Recently delving into the world of websockets with Go for the first time and encountering a strange error that does not disrupt the program flow. The client in use is a ReactJS single page application. JavaScript Client: const socket = new WebSocket(&quo ...

Running into issues while trying to establish a connection to MongoDB using Mongoose in a NextJS Typescript environment. Getting

Here is a code snippet attempting to connect to a MongoDB using Mongoose: file: app/utils/db.ts import connect from "@/app/utils/db.ts"; import * as dotenv from 'dotenv' import * as mongoose from "mongoose"; import endpointsCo ...

TypeScript integration for express-validator

Recently, I made an attempt to switch my NodeJS project with ExpressJS to TypeScript for better organization and type safety. However, I encountered an issue with the 'express-validator' middleware during this conversion process. To resolve thi ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

What is the best way to pass createdDt and updatedDat values in an Angular form without displaying them on the template?

I am working on a message creation form in Angular where I need to include createdDt and updatedDt as hidden values. These values should not be visible in the template. I want to automatically set the current date and time for both createdDt and updatedD ...

Navigating the complexities of generic types in Typescript involves understanding how to work

Having an issue with my React + TypeScript application. I am trying to write a function to filter some data: function matchesFilter(element: T, filter: Filters) { const { name, options } = filter; return options.filter(selected => select ...

Unable to alter the input data within the LCJS chart

I have been utilizing LightningChart JS to create scrolling line charts. After following an official tutorial by the developers on YouTube, I was able to successfully implement the automatic generated data. Now, I am looking to modify the input to a JSON f ...

Solidjs: Implementing a Map in createStore does not trigger updates upon changes

As a beginner in solidjs, I might have missed something important. In the code snippet below, I am trying to understand an issue: const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string> In a component, suppose I want ...

"Hmm, the React context's state doesn't seem to be changing

I have been working on a next.js app and I encountered an issue related to using react context to export a state. Despite my efforts, the state doesn't seem to update and it remains stuck at the initial value defined by the createContext hook, which i ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

TS: Deduce explicit typing through method chaining

After overcoming all obstacles, I am finally ready to unleash the first version of my form validation library. Below is a snippet of the code (simplified for clarity) interface Validation { name: string message: string params?: Record<string, any ...

The disappearance of ngx-charts lines is observed when the chart is rendered within a PrimeNG dialog that gets closed and reopened

In my TypeScript Angular application, I am currently incorporating PrimeNG. Specifically, I am utilizing the dialog component from PrimeNG to display charts using ngx-charts, specifically the ngx-charts-line-chart module. Initially, when I open the dialo ...

Can we create an intersection type of Records by pairing keys with tuples or unions of values in a one-to-one correspondence?

If I have tuples similar to this for keys and values: type Keys = ['North', 'East', 'South', 'West']; type Values = ['n', 'e', 's', 'w']; Is there a way to achieve a structure ...

I was wondering if there is a method to define custom types similar to the Array type in

Is there a way in TypeScript to create a custom type with methods that can access the variable's value directly, similar to how Array methods work without passing the value as a parameter? For example: const arrayVar: Array = [1,2,3]; array.find(el ...

Error code 0x800a1391 - JavaScript runtime error: 'module' has not been defined

My background is in C++ and I am just beginning to explore TypeScript. I'm facing a runtime error while trying to implement a design (interface/class) that spans multiple files. The error message reads: 0x800a1391 - JavaScript runtime error: 'mod ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...