oop - Extending React components in TypeScript -


i'm using react.js typescript. there way create react components inherit other components have additional props/states?

what i'm trying achieve this:

interface basestates {     a: number; }  class genericbase<s extends basestates> extends react.component<void, s> {     protected getbaseinitialstate(): basestates {         return { a: 3 };     } }  class base extends genericbase<basestates> {     getinitialstate(): basestates {         return super.getbaseinitialstate();     } }  interface derivedstates extends basestates {     b: number; }  class derived extends genericbase<derivedstates> {     getinitialstate(): derivedstates {         var initialstates = super.getbaseinitialstate() derivedstates; // unsafe??         initialstates.b = 4;         return initialstates     } } 

however, fail if call this.setstate in derived, typescript error (parameter of type derivedstates not assignable type s). suppose not typescript-specific thing, general limitation of mixing inheritance generics (?). there type-safe workaround this?

update

the solution settled on (based on answer of david sherret):

interface basestates {     a: number; }  class genericbase<s extends basestates> extends react.component<void, s> {     constructor() {         super();         this.state = this.getinitialstate();     }      getinitialstate(): s {         return { a: 3 } s;     }      update() {         this.setstate({ a: 7 } s);     } }  interface derivedstates extends basestates {     b: number; }  class derived extends genericbase<derivedstates> {     getinitialstate(): derivedstates {         var initialstates = super.getinitialstate();         initialstates.b = 4;         return initialstates;     }      update() {         this.setstate({ a: 7, b: 4 });     } } 

you can set few properties of state @ once in derived using type assertion:

this.setstate({ b: 4 } derivedstates); // this.setstate({ a: 7 } derivedstates); // or this.setstate({ a: 7, b: 4 });            // or 

by way, no need have different names getinitialstate... do:

class genericbase<s extends basestates> extends react.component<void, s> {     constructor() {         super();                 this.state = this.getinitialstate();     }      protected getinitialstate() {         return { a: 3 } basestates s;     } }  class derived extends genericbase<derivedstates> {     getinitialstate() {         var initialstates = super.getinitialstate();         initialstates.b = 4;         return initialstates;     } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -