Search code examples
javascripttypescripttypescript-class

Typescript inherit constructor param object


import hospital from "./hospital.json";


class Hospital {
    constructor(public hospital) {
   
    }
    ...other_methods

}

const SampleHospital = new Hospital(hospital);

I have raw data which is hospital.json.

I decided to create a class for a hospital to add some methods to the hospital.

The problem is

When I want to access to hospital's field there will always be extra access .hospital.

SampleHospital.hospital.contact

I want to make it SampleHospital.contact.

Of course, I can add another public field.

But to create every public field for hospital object will require a lot of effort.


I tried

type THospital = typeof hospital ;
class Hospital implements THospital {
    constructor(hospital: THospital) {
        [...Object.keys(hospital)].forEach(key => this[key] = hospital[key])
    }
}

But the typescript didn't understand my field assignment.

enter image description here

It says fields are missing


Solution

  • you can loop on all keys of parameter object and assign current object to parameter object value

    const hospital = {
      name: 'win',
      contact: 'test'
    };
    
    class Hospital {
      constructor(hospital) {
        [...Object.keys(hospital)].forEach(key => this[key] = hospital[key]);
      }
    }
    
    const SampleHospital = new Hospital(hospital);
    
    console.log(SampleHospital.name);

    In typescript you will have to say my type can have other property you have to use index signature for this [index: string]: any;

    const hospital = {
        name: 'win',
        contact: 'test'
      };
      
      class Hospital {
        [index: string]: any;
        constructor(hospital) {
          [...Object.keys(hospital)].forEach(key => this[key] = hospital[key]);
        }
      }
      
      const SampleHospital = new Hospital(hospital);
      
      console.log(SampleHospital.name);