Provide a dictionary-style object parameter that contains properties of type T to the class<T>

My approach involves using the concept of inheritance to initialize properties of a class<T> with an Object that implements all T properties passed to the constructor

export default abstract class DatabaseObjectModel<T> extends JSONModel<T> {
  constructor(json: T) {
    super();
    this.fromJSON(json);
  }
}

export default abstract class JSONModel<T> extends ModelValidation {
  // abstract toJSON(): Object;
  // abstract fromJSON(json: Object): T;

  toJSON() {
    // Default toJSON
    return JSON.parse(JSON.stringify(this));
  }

  fromJSON(json: Object) {
    // For each key of json, assign value to this.key
    for (let key in json) {
      this[key] = json[key];
    }
  }
}

An issue arises when trying to initialize classes inheriting from DatabaseObjectModel like so:

new ImplementingDatabaseObjectModel({
    id: randomUUID(),
    name: "MASTER",
    permissions: [],
    assignedRoles: undefined,
})

This results in the following error message:

Argument of type '{...}' is not assignable to parameter of type 'ImplementingDatabaseObjectModel'

I am seeking guidance on how to modify the constructor of DatabaseObjectModel<T> to accept an Object that implements all properties of type T, without requiring its instance.

Answer №1

Discovered the answer right here:

How can I make a type that excludes instance methods from a class in TypeScript?

export type DTO<T> = {
    [P in {
        [K in keyof T]: undefined extends T[K] ? never : T[K] extends (...args) => any ? never : K;
    }[keyof T]]: T[P] extends object ? DTO<T[P]> : T[P];
} &
    Partial<
        {
            [P in {
                [K in keyof T]: undefined extends T[K] ? K : never;
            }[keyof T]]: T[P] extends object ? DTO<T[P]> : T[P];
        }
    >;

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

In TypeScript, how to refer to the type of the current class

Is there a way to reference the current class type in the type signature? This would allow me to implement something like the following: export class Component{ constructor(config?: { [field in keyof self]: any }) { Object.assign(this, config) ...

Acquire the property that broadens the interface

I'm currently working on a TypeScript function that aims to retrieve a property from an object with the condition that the returned property must extend a certain HasID interface. I envision being able to utilize it in this manner: let obj = { foo ...

Creating OpenAPI/Swagger documentation from TypeScript code

I am in search of a solution to automatically create OpenAPI/Swagger API definitions based on my Node.JS/Express.JS/Typescript code. It would be perfect if I could simply add annotations to my Express Typescript base controllers and have the OpenAPI/Swagg ...

Utilizing a generic type with the useReducer hook for an output parameter

I am currently working on developing a custom hook to retrieve data from an API. My main goal is to ensure that the returned data maintains type safety. Is it possible to achieve this using generics? type Action = { type: 'PENDING' } | { type: &a ...

Showing a whole number formatted with exactly three decimal places in Angular

I am working on an Angular project that includes an input field for users to enter numbers. My goal is to show the number with exactly 3 decimal places if the user submits a whole number. For instance, if the user inputs 6, I want it to be displayed as 6.0 ...

I'd like to know how to retrieve a total count of all the documents within a Firebase collection using Angular

My code currently fetches documents from a collection, but it's only bringing back 15 at a time (from what I can gather). This is causing an issue as I need to accurately determine the total number of documents in the collection for a program I'm ...

Retrieve the calling method's context within an exported function

In my codebase, there exists a file called utils which houses various utility functions that are utilized by different classes and components. Currently, there is a test-utils class designed specifically for karma unit tests to perform common tasks. One ...

The control of the ThreeJS TransformControl has been relinquished

I am currently working on a project using Typescript within the Autodesk Forge Viewer environment. My goal is to restrict the movement of the ThreeJS transform control to a specific area defined by min and max values for X, Y, and Z coordinates. Additional ...

Locate the initial occurrence of a duplicated element within an array

I need to check for duplicate values in an array element. Within my array, I have multiple objects like {S:1,R:2,V:3}. My goal is to display an alert message if there are duplicate values for the "S" element in that array. My Approach: var arr=[{S:1,R:2 ...

Encountering parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

The variable 'module' is required to be of type 'any', but it is currently identified as type 'NodeModule'

I am currently working on a project using Angular and have just installed version 1.0.5 of ng2-dropdown-treeview. After installation, I restarted my server by running npm start. Upon checking the server log, I encountered the following error message: [PA ...

How can I detect click events on SVG path element using Angular?

Is it possible to detect click events on SVG elements such as path or g using Angular? To see an example of this, check out this demo. Right now, if a (click) event binding is added to the svg elements, the click() event handler will trigger. However, how ...

Binding objects and properties from Angular2/Typescript to a template

Disclaimer: Seeking insight on the correct approach or any additional information _____________________________________________________________________ ANGULAR1 When working with angular1, we had the option to define our objects in the following ma ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Setting values to variables within a component to enable universal access throughout the component in Angular 2

In my Angular 2 project, I have a function that retrieves data from a database using an API. I've created a function that stores the data successfully in a variable named "ReqData", which is of type "any". this._visitService.getchartData().subscrib ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...