3

i try to extend a React Component Class with generic Parameters but I cannot get it working. According to the TypeScript Docs and this TypeScript Class Generic Parameter Constraints, and this extending a class with a generic T I ended up in the following (not working) code:

Base Class:

class BaseView<P, S> extends React.Component<P, S> {
    public constructor(props: P, state: S) {
        super(props, state);
    }
}

const mapStateToProps = store => {
    console.log('store', store);
    return {
        store
    };
};

function mapDispatchToProps(dispatch) {
    console.log('dispatch', dispatch);
    return {
    };
}

export default connect(mapStateToProps, mapDispatchToProps)((BaseView as any));

export function subclass<P, S>(c): BaseView<P, S> {
    return c;
}

The class which extends the Base Class:

I tried different ways, using the factory like this:

export class Documents extends subclass(BaseView)<DocumentsProperties, DocumentsState> { 
// this leads into ""BaseView<{}, {}>" is no constructor function type

or without using the factory:

export class Documents extends BaseView<DocumentsProperties, DocumentsState> { 
// no base constructor has the specified number of type arguments

I also tried out several other ways but i feel like i was programming for the first time of my life....I cannot get it running for multiple Parameters. What am I missing here?

greetings Messerbill

6
  • The former doesn't work because you want subclass() to return typeof BaseView and not BaseView<P,S>. I don't understand why the latter doesn't work, though. I can't reproduce your error in the Playground. Can you reproduce the error in a self-contained (no libraries) example? If not you'll have to wait for someone with react installed in their environment Commented Oct 11, 2018 at 16:40
  • What are you expecting c to be? I'm guessing you want c to be some super constructor. Is it React? Commented Oct 11, 2018 at 16:53
  • @MinusFour yes it is react. I expected c to be a BaseView "Type" - not an instance. I also tried using new c() which did not work either Commented Oct 11, 2018 at 16:57
  • @messerbill have you tried (c : { new() : BaseView<P,S> }) for both c and the return type. Commented Oct 11, 2018 at 17:29
  • Higher-order components like connect and generic components do not mix easily. See this answer for the approach I recommend. Let me know if you have trouble applying it to your scenario. Commented Oct 12, 2018 at 4:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.