Home > Net >  typescript same data type return from different classes
typescript same data type return from different classes

Time:06-12

Hi so I have this structure for typescript, In the class implementer, I'm trying to return different classes but I have been told that it should work since they have the wrapper class takes care of the abstraction needed. There is an error that states this,

Type 'MyGrandPa | MyGrandPa2' is not assignable to type 'ISomething'. Property 'doSomething' is missing in type 'MyGrandPa' but required in type 'ISomething'.

class MyGrandPa 
{
    private name;
   constructor(name: string){
        this.name= name;
   }
   get myName():string
    {
        return this.name;
    }


//   check what is returned here can be accepted as well
 
}

class MyGrandPa2
{
    private name;
   constructor(name: string){
        this.name= name;
   }
   get myName():string
    {
        return this.name;
    }


//   check what is returned here can be accepted as well
 
}




  class Parent 
{
    private dictVal= 'hey';
    private grandpa =new MyGrandPa('eric');
   
  get value():MyGrandPa
    {
        return this.grandpa;
    }
//   check what is returned here can be accepted as well
 
}
interface ISomething 
{

    doSomething(): MyGrandPa2; 
 
}

class Wrapper extends Parent implements ISomething{

    
   


    doSomething()
    {
        //Do something
        return new MyGrandPa2('new');
    }
    decider(message: string){
        if (message=="hey"){
            return new MyGrandPa2('new');
        }
        else{
              return super.value;
        }
    }

}


// import Wrapper
class myImplementer {

// why doesn't this work?
constructor(){
let myReturnValue: ISomething;
let wrapper= new Wrapper();
myReturnValue=wrapper.decider('hey');
}

Here is the error error

Add more comments, Add more commentsAdd more commentsAdd more commentsAdd more commentsAdd more comments

CodePudding user response:

This is because myReturnValue is of type ISomething which is structurally different to MyGrandPa or MyGrandPa2 that can be returned by wrapper.decider('hey') as neither of them have a doSomething(): MyGrandPa2; method - which ISomething requires.

To resolve this, you either need to add a doSomething(): MyGrandpa2 method inside the MyGrandPa and MyGrandPa2 classes, or assert myReturnValue to an interface that would have a { get myName():string }; type.

To sum it all up, the core of the problem is that myReturnValue type is structurally different to the type being returned by wrapper.decider('hey') which breaks TypeScript's type compatibility rules.

  • Related