Combining a plain object with a TypeScript class

I am currently working on developing a function that dynamically defines a class extending another class based on a passed object. Here is an example of what I am aiming to achieve:

const ObjectMixin = function<T>(obj: T): new () => T {
    return class extends BaseClass {
        ...obj // pseudo code illustrating the concept 
    }
}

The purpose of this function is to streamline the process of creating Vue class components with mapped state inclusion. An example implementation would look like this:

class MyComponent extends ObjectMixin(smartModule.mapState(['someState'])) {
    created() {
        this.someState // should not result in any errors
    }
}

I have made some progress using workarounds such as the following:

interface ObjMixinI {
    <T>(obj: T): new () => T
}

const ObjectMixin: ObjMixinI = obj =>
//@ts-ignore
    function() {
        //@ts-ignore
        Object.assign(this, obj)
    }

However, I am facing challenges in making it extend Vue and acknowledge that this current method is not ideal.

Answer №1

If you need to utilize the constructor, try implementing it in this manner:

const ObjectMerging = function<T>(obj: T) {
    return class extends BaseClass {
        constructor() {
            super();

            Object.assign(this, obj);
        }
    } as { new (): BaseClass & T }
}

class Y extends ObjectMerging({ example: 42 }) { }
const y = new Y();
console.log(y.example);

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

You cannot assign type void to type any

I'm currently working on a component that involves some code: export class AddNewCardComponent { public concept = []; constructor( private _router: Router, private _empDiscService: empDiscService) { } ngOnIni ...

"Efficiently storing huge amounts of data in MySQL in just 5

Interested in my tech stack: express + typeorm + mysql Seeking a solution for the following task: I have a csv file with over 100000 rows, where each row contains data such as: reviewer, review, email, rating, employee, employee_position, employee_unique_ ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

Choosing the right configuration file for your project's entry point can be crucial. Should you

Within the webpack.config.js file, we can specify the entry file as shown below: module.exports = (env = {}, argv = {}) => { const config = { entry: { main: './src/js/main.js' ...

Tips for optimizing template customization and maximizing reusable code snippets

There are various ways in which a post can be rendered, such as full page, modal view, collapsed view, edit mode, etc. These methods share many similarities and are all kept as templates within Post.vue. A context prop is passed on to render a specific var ...

What is the best way to limit the date picker to only accept numbers and hyphens in the input field while blocking any other input in Vue?

I have been utilizing the vue2-datepicker npm package for handling dates. The date input currently accepts all alphabets, numbers, and special characters but I only want it to allow numbers, hyphens, and forward slashes. It's simple to achieve this us ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Obtain an instance of a class within a function that is contained within an instance object in TypeScript/Angular

There is a separate object responsible for managing a specific dialog box in my application. The challenge lies in accessing the instance of the class, even though the functions are self-explanatory. I attempted to use the conventional method of that = thi ...

Error in Angular Typescript: Utilize the return value of "filter" function to fix the issue

Encountering a sonar error: The return value of "filter" should be utilized Despite using the filter, the error persists. What might be the issue here? array.filter(item => { item.value.split(' ').forEach( i => { if ( doSomething(i) ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

Tips for using jest toHaveBeenCalled with multiple instances

Currently, I am in the process of writing a test case for one of my functions. This function calls another function from a library, and I am attempting to mock this function (saveCall). Below is a snippet of the sample code in question: import { Call } fro ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

Issue with Angular filtering when utilizing pipe and mapping the response

Code snippet from shop.service.ts getProducts(brandId?: number, typeId?: number) { let params = new HttpParams(); if (brandId){ params = params.append('brandId', brandId.toString()); } if (typeId){ params = params.append('typeId', ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Capturing the file path reference from subsribe and saving it in Firebase

Currently, I have a script that is responsible for uploading my image once the form is submitted. updateUser(user: User, privateUser: PrivateUser, dob) { //store img in storage if(this.file){ var path = `users/${this.userID}/${this.file.name}` var ...

The import map is not being recognized by Supabase Edge Functions when passed in the command `npx supabase functions serve`

My situation involves two edge functions, namely create-payment-link and retrieve-payment-link. However, they are currently utilizing the import map located at /home/deno/flag_import_map.json, rather than the import_map.json file within the functions folde ...

What are some methods for altering ReadOnly values?

I am encountering an issue with the value fetchOptions: Readonly<HttpFetchOptionsWithPath> and my attempt to overwrite one of its properties. Here is the method I have tried: ((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Wr ...

Storing geolocation information in local variables for future use

I am completely new to Nativescript (with Angular 2/TypeScript). My goal is to utilize the Nativescript geolocation plugin to track a user's location and store the data (latitude and longitude) for future use. Here is a snippet of my code: export cla ...