Implement a class in Typescript that allows for the addition of properties at runtime

I'm currently in the process of incorporating Typescript definitions into an existing codebase that utilizes the Knockout library. Within the code, there is a prevalent pattern that appears as follows:

interface SomeProperties {
    // Assorted properties
}

class ViewModel {
    // Specific properties...

    constructor(data: SomeProperties) {
        AddAllPropertiesToThis(data);
    }
}

The function AddAllPropertiesToThis essentially takes the data object and dynamically appends all its properties to this.

I am struggling to identify how to convey this pattern accurately in Typescript. It seems logical to state something along the lines of

class ViewModel implements SomeProperties

however, this necessitates manually transcribing all the properties from the interface definition to the class.

Is there any alternative method to achieve the desired outcome here without the need to repetitively list out properties?

Answer №1

One approach could be to create a member variable data: SomeProperties within the ViewModel.

interface SomeProperties {
    // Various properties
}

class ViewModel {
    data: SomeProperties;

    constructor(data: SomeProperties) {
        // Perform a deep copy of the data
        this.data = { ...data };
    }
}

In my opinion, utilizing composition as shown in the code above is more logical than using inheritance. The ViewModel includes (has) SomeProperties, rather than being an extension of SomeProperties ("is a" relationship).

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

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

Saving data to a database using knockout.js and JSON objects: A step-by-step guide

I have been assigned a task to work with knockout.js. In my project, I have a model called "employee" with fields such as name, country, and state. However, the issue I am facing is that I am unable to save any changes made during the editing process. Her ...

Exploring the functionality of Knockout Observable Arrays

In the midst of working on an MVC project, I've incorporated knockout on the client side to handle data manipulation tasks. Upon receiving data from the server, it is promptly passed to an observableArray after being converted to JSON. The data arrive ...

Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples. function (times: Array<number> | Array<[number, number]>) { if (Array.isArray(times[0]) ...

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

Is it possible to invoke Cucumber stepDefinitions from a separate project at the same directory level?

Currently, I have a project called integration_test that includes all test projects utilizing cucumberjs, typescript, and nodejs. Project1 contains the login implementation, and I would like to use this implementation in Scenarios from Project2 and Projec ...

Using React.Fragment in VS Code with TypeScript error 2605 while having checkJs enabled

While utilizing the JS type checking feature in VScode, I encountered an issue with React.Fragment that is being linted with an error: JSX element type 'ReactElement<any>' is not a constructor function for JSX elements. Type 'ReactEle ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Reactjs-ffsevents does not exist as a function

An error occurred: TypeError: fsevents is not a function. This issue is located in the FSEventsWatcher file at line 162. A new FSEventsWatcher was attempted to be created in jest-haste-map, triggering this error. The watcher creation process involved map ...

Tips for defining the type of any children property in Typescript

Currently, I am delving into Typescript in conjunction with React where I have a Team Page and a slider component. The slider component is functioning smoothly; however, my goal is to specify the type of children for it. The TeamPage import react, { Fragm ...

Transforming an array of flat data into a hierarchical tree structure

I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj. The Rules are: If an object has a higher depth, it should be a child of an object with a l ...

Angular Owl Carousel doesn't slide horizontally, it slides vertically

Within my Angular project, I incorporated an Owl Carousel into the home-component.html file. Here is a snippet of the code: <section> <div class="container"> <h1 class="products-title">New Arrivals</h1> ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

Can fields from one type be combined with those of another type?

Is it possible to achieve a similar outcome as shown below? type Info = { category: string } type Product = { code: string, ...Info } Resulting in the following structure for Product: type Product = { code: string, category : string } ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

Encounter a problem while running `ng build` due to a module not

I was looking to automate the building of my Angular project on a separate CentOS 7 machine. Here are the versions being used: Angular CLI: 8.3.23 Node: 13.14.0 OS: linux x64 Angular: 8.2.14 ... animations, common, compiler, compiler-cli, core, forms ... ...