Skip to content

Generics and extending an abstract class #25606

Closed
@mshoho

Description

@mshoho

Hi, I want to have a function (with generics) which takes an abstract class and returns a derived class with the implemented abstract methods.

The example of what I have now:

interface ComponentConstructor<T, P> {
  new (props: P, context?: any): T;
}

type GetSomething<R, P> = (props: P) => R;

// The function.
function extend<P, R, T extends React.Component<P>>(Component: ComponentConstructor<T, P>, getSomething: GetSomething<R, P>) {
    return class extends (Component as React.ComponentClass<P>) {
        getSomething(): R {
            return getSomething(this.props);
        }
    }
}

interface MyProps {
    prop1: string;
    prop2: number;
    prop3: boolean;
}

interface MySomething {
    prop4: string;
    prop5: string;
}

// How I have it now.
class MyClass extends React.Component<MyProps> {
   // I want to have this as abstract method.
   getSomething!: (props: MyProps) => MySomething;

   render() {
        const something = this.getSomething(this.props);
        return <div>{ something.prop4 + ' ' + something.prop5 }</div>;
    }
}

function getMySomething(props: MyProps): MySomething {
    return { prop4: 'hello ' + props.prop1, prop5: 'world' };
}

const MyDerivedClass = extend(MyClass, getMySomething);

// This works ok.
<MyDerivedClass prop1={ 'wonderful' } prop2={ 1 } prop3 />

But it allows to instantiate MyClass and I'd like to have it like this:

abstract class MyClass extends React.Component<MyProps> {
   abstract getSomething: (props: MyProps) => MySomething;

   render() {
        const something = this.getSomething(this.props);
        return <div>{ something.prop4 + ' ' + something.prop5 }</div>;
    }
}

Is there a way to make it work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions