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

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • The former doesn't work because you want `subclass()` to return `typeof BaseView` and not `BaseView

    `. I don't understand why the latter doesn't work, though. I can't reproduce your error in the [Playground](http://www.typescriptlang.org/play//). 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

    – jcalz Oct 11 '18 at 16:40
  • What are you expecting `c` to be? I'm guessing you want `c` to be some super constructor. Is it React? – MinusFour Oct 11 '18 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 – messerbill Oct 11 '18 at 16:57
  • @messerbill have you tried `(c : { new() : BaseView

    })` for both `c` and the return type.

    – MinusFour Oct 11 '18 at 17:29
  • Higher-order components like `connect` and generic components do not mix easily. See [this answer](https://stackoverflow.com/a/52573647) for the approach I recommend. Let me know if you have trouble applying it to your scenario. – Matt McCutchen Oct 12 '18 at 04:25
  • thank you for your advises....at least I could not get it running the way i wanted to. I now have my generic BaseView without the high order component (`connect()`). So i Have to call the connect method in each of those components.... – messerbill Oct 12 '18 at 13:00

0 Answers0