Search code examples
angulartypescriptdynamic

Typescript reach defined type from variable in Angular


interface Bus  {
  id: number;
  test?: string;
}

interface Area{
  id: number;
  load?: string;
}

type TypeMap= {
  Bus: Bus,
  Area: Area,
  // etc
}



  func1(){
    const equipmentType1 = "Bus"
    const equipmentType2 = this.getSelectedEquipmentType()

    type myType1 = TypeMap[typeof equipmentType1];
    type myType2 = TypeMap[typeof equipmentType2]; // this line throw an error which is "Type TypeMap has no matching index signature for type string"


    let myObj1: myType1 = {id:1};
    let myObj2: myType1 = {id:1,test:"1"};
    let myObj3: myType1 = {test:"1"};


  }


  getSelectedEquipmentType(){
    return "Bus"
  }


In my case, I'll have different types like Bus, Area an etc. I want to create variable in this types according to selected type. So if my equipment type is Bus I want to create a variable in type Bus. But I want to do it dynamic way. So I have selected type as a string like "Bus". When I create equipmentType1 as const I can do that because equipmentType1's type is automatically defined as a Bus. But for equipmentType2, its type defined as a string and it throws an error. But I need to use it like equipmentType2. Because I'll set equipmentType in another function and I'll reach like

 const equipmentType2 = this.getSelectedEquipmentType()

I also tried interface instead of Type but result hasn't changed.

So how can achieve this or is there a better way?

Thanks in advanced!


Solution

  • You have to set keyof TypeMap for the variables, then it will access the index type.

    interface Bus  {
      id: number;
      test?: string;
    }
    
    interface Area{
      id: number;
      load?: string;
    }
    
    type TypeMap= {
      Bus: Bus,
      Area: Area,
      // etc
    }
    
    function getSelectedEquipmentType(): keyof TypeMap {
      return 'Area';
    }
    
    function func1(){
      const equipmentType1: keyof TypeMap = "Bus"
      const equipmentType2: keyof TypeMap = getSelectedEquipmentType()
      type myType1 = TypeMap[typeof equipmentType1];
      type myType2 = TypeMap[typeof equipmentType2]; // this line throw an error which is "Type TypeMap has no matching index signature for type string"
      let myObj1: myType1 = {id:1};
      let myObj2: myType1 = {id:1,test:"1"};
      let myObj3: myType2 = {id:1, load: 'test'};
    }
    

    Typescript Playground