Incorporating properties of the parent class through Mixin techniques

I'm encountering an issue while trying to access a property from an inherited class within a mixin

class BaseItem{
     public id:string;
     constructor(id:string) {
        this.id =id;  
     }
} 

abstract class ConfigMixin<K extends BaseItem>{
        public saveConfig() {
            const repo = getRepository(Entity);
            repo.update(
                { 
                    id: this.id // Typescript error
                },
                {
                    ...this.getConfig(),
                },
            );
        }
}

class BaseDevice extends BaseItem{
     constructor(id:string) {
        super(id);   
     }
} 
export interface BaseDevice extends ConfigMixin<BaseDevice> {}
applyMixins(BaseDevice , [ConfigMixin]);

However, I am facing the following error message: TS2339: Property 'id' does not exist on type 'ORCASmartLightConfig'.

Answer №1

There are two different ways to approach this:

  1. Adhere strictly to the encapsulation of mixins. Mixins should stand alone and not have knowledge about where they will be mixed in. This means that a mixin should not assume it has been added to a class with an id field:
// Following this first approach maintains strict encapsulation of mixins
export abstract class ConfigMixin {
  // Your mixin will require all necessary information as parameters
    // Hence, whenever you call saveConfig, you must pass the id along
  public saveConfig(id: string) {
    console.log(id);
  }
}

// The base class
class BaseItem {
  constructor(public id: string) {}
}

// Implementing a subclass of BaseItem
export class BaseDevice extends BaseItem {}

// Specifying that BaseDevice includes ConfigMixin
export interface BaseDevice extends ConfigMixin {}

// Applying the ConfigMixin
applyMixins(BaseDevice, [ConfigMixin]);

Link to TypeScript playground

  1. Sidestep TypeScript's rules! This method results in code that is more aligned with your original strategy but does come with a downside:
// Utilizing an abstract class field characterizes the second option
export abstract class ConfigMixin {
  public abstract id: string;

  public saveConfig() {
    console.log(this.id);
  }
}

// The base class
class BaseItem {
  constructor(public id: string) {}
}

// Creating a subclass of BaseItem 
export class BaseDevice extends BaseItem {}

// Indicating that BaseDevice has ConfigMixin integrated
export interface BaseDevice extends ConfigMixin {}

// NEGATIVE ASPECT
//
// Unfortunately, using this technique, TypeScript will not raise errors when
// attempting to include ConfigMixin in a class lacking the id field
export class SomeDevice {}
export interface SomeDevice extends ConfigMixin {}

// Finally, applying the ConfigMixin
applyMixins(BaseDevice, [ConfigMixin]);
applyMixins(SomeDevice, [ConfigMixin]);

Link to TypeScript 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

Tips for sending class objects with Typescript/React

I need to establish an Array of items with different characteristics as a Prop on my component. My goal is to transmit an array of items with unique properties to a component. Here's an example of what my array of objects might look like: ` let dish ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: https://i.sstatic.net/Hl8Pv.png It appears that validate and formSubmit are being recognized as unused variables by typescript, result ...

The issue with the Angular 5 HttpClient GET-Request not closing persists

Currently, I am utilizing an Http-GET request to fetch JSON data from my backend service. Service: public storedCategories: BehaviorSubject<Category[]> = new BehaviorSubject(null); constructor() { const subscription = this.http.get&l ...

Ionic 2: Unveiling the Flipclock Component

Can anyone provide guidance on integrating the Flipclock 24-hours feature into my Ionic 2 application? I'm unsure about the compatibility of the JavaScript library with Ionic 2 in typescript. I have searched for information on using Flipclock in Ionic ...

Display various react components based on the value of the property

I am in the process of creating an input component in ReactJs with typescript. The input can vary in types such as text, date, select, or textarea. Depending on the type provided, the displayed control will differ. For example, if set to text, <input t ...

Create a three-dimensional tree array in Typescript/Javascript by transforming a flat array

Received data is structured as follows: const worldMap = [ { "name": "Germany", "parentId": null, "type": "Country", "value": "country:unique:key:1234", "id&qu ...

Using TypeScript to ensure the correct typing for the return type of AsyncThunk when utilizing the 'unwrapResult' method from Redux Toolkit

Struggling to determine the appropriate return type for an AsyncThunkAction in order to utilize it with the unwrapResult method from Redux Toolkit (refer to: Redux Tookit: Unwrapping Result Actions): Here is how the Async thunk is declared in the Slice: e ...

Inform the Angular2 Component regarding the creation of DOM elements that are placed outside of the

The Challenge In my Angular2 project, I am using Swiper carousel and building it with Webpack. However, Angular2 adds random attributes like _ngcontent-pmm-6 to all elements in a component. Swiper generates pagination elements dynamically, outside of Ang ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

When a MatFormFieldControl both implements ControlValueAccessor and Validator, it can potentially lead to a cyclic

I am attempting to develop a custom form control by implementing MatFormFieldControl, ControlValueAccessor, and Validator interfaces. However, I encounter issues when including NG_VALUE_ACCESSOR or NG_VALIDATORS. @Component({ selector: 'fe-phone-n ...

Pagination feature in MUI DataGrid table is malfunctioning

I'm struggling to get the pagination feature to work in my Material UI DataGrid component, but I'm hitting a roadblock: https://i.stack.imgur.com/eT7s7.gif The console is not showing any errors. Here is the code for my component: import { ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Passing a complex variable type in TypeScript to a function without the need to redefine the type

I'm fairly new to working with TypeScript and I've encountered this issue several times. When using tools like Prisma to retrieve data, I often come across values with incredibly complex types. These values contain many attributes, which is perf ...

The issue persists in Angular 5 and asp.net MVC where the ID number continues to increase despite being deleted

Currently, I am using Angular 5 (VS CODE) for the front-end and asp.net mvc/entity framework (VS2017) for the back-end. My CRUD methods are functioning properly; however, I have encountered an issue where the ID of a newly created row keeps increasing even ...

Exploring ways to exclude a column in a TypeORM entity while also providing the flexibility to make it optional for retrieval using the Find method

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } i prefer not to include the password here as I want it to be returned to the client: ...

Tips for implementing react-hook-form in an Ionic Modal?

I've been experimenting with implementing react-hook-form in my Ionic React project. Here's a simple form I created: const CustomForm: React.FC<{ color: string }> = ({ color }) => { const { handleSubmit, register } = useForm(); con ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

Is there a way to create a Typescript function that can automatically return either a scalar or array value without requiring the caller to manually cast the output

Challenge Looking for a solution to the following problem: save<T>(x: T | T[]) { if (x instanceof Array) { // save array to database } else { // save entity to database } return x } // client code let obj: SomeType = { // values here ...

The error message related to TupleUnion in TypeScript is indicating that the depth of type instantiation may be too deep and could

Recently, I've been delving into a TypeScript utility type known as TupleUnion. This useful type came to my attention through a fascinating Twitter post, and I've observed it being utilized in various Stack Overflow solutions. Here's how the ...

Develop an interface in TypeScript for intricate data structures

Displayed below is a variable that contains a collection of objects: scenes = { sky: { image: 'assets/1.jpg', points: { blue_area: { x: 1, y: 2 }, } }, blue_area: { image: & ...