Home > Mobile >  (Typescript) Automatically access child object properties
(Typescript) Automatically access child object properties

Time:01-28

I am new to TS and have a question:

Say I have the following:

interface FolderInterface {
   name: string;
   source: {
     type: 'usb'
   },
   // many more properties
}

class FolderImpl {
   folder: FolderInterface
}

I have an instance of FolderImpl, called folderImpl.

What I would like to do is that if folderImpl.name is called, it automatically calls folderImpl.folder.name.

I am guessing one way would be to copy over the properties, but is there a better way than that?

Thank you for your kind help.

CodePudding user response:

In Typescript an implements clause can be used to verify that a class conforms to a specific interface

this is not what you are doing, if your class FolderImpl has a proprety of type FolderInterface it does not have to implement any other class.

class FolderImpl {
   constructor(
    public folder: FolderInterface, public otherProp: string
   ) {
    this.folder = folder;
    this.otherProp = otherProp;
  }
}

is there a way to automatically map everything to the appropriate field on the folder

you don't have to map nothing if you want to declare a const of type FolderImpl you do it this way :

const test : FolderImpl =  new FolderImpl({name: 'zab', source: { type : 'usb'}},'ahmed');

and you acces your properties like this :

const myFolder = test.folder

CodePudding user response:

It seems that what you are wanting can also be achieved simply with inheritance, which is native to javascript. You can create a "parent" class with properties that can be shared between all its "children".

Your parent class:

class Folder {
  name: string;
  source: {
    type: 'usb'
  };
  
  constructor(name: string) {
    this.name = name;
  }
}

Now you extend this class to your implementation "child" class:

class FolderImp extends Folder {
  constructor(name: string) {
    super(name);
  }
  
  // add methods that would be specific to the FolderImp class
  // you can access all the properties of the parent class
  printName() {
    console.log(this.name);
  }
}

Notice the super call, this allows you set the properties of the parent class without declaring them in the child class. So now this will work:

const folderImp = new FolderImp("bin");
folderImp.printName() // prints bin
  • Related