interface Bus {
id: number;
test?: string;
}
interface Area{
id: number;
load?: string;
}
type TypeMap= {
Bus: Bus,
Area: Area,
// etc
}
func1(){
const vehicleType1 = "Bus"
const vehicleType2 = this.getSelectedVehicleType()
type myType1 = TypeMap[typeof vehicleType1];
type myType2 = TypeMap[typeof vehicleType2]; // encountering an error stating "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"};
}
getSelectedVehicleType(){
return "Bus"
}
In my situation, I have various types like Bus, Area among others. My objective is to create variables based on the selected type. So if the vehicle type is Bus, I want to create a variable of type Bus. However, I aim to achieve this in a dynamic manner. Hence, when I declare vehicleType1 as const, I am able to do so because its type is automatically inferred as Bus. Conversely, for vehicleType2, its type is defined as a string resulting in an error. Despite needing to use it similar to vehicleType2. This is due to setting the vehicleType in another function, accessed through:
const vehicleType2 = this.getSelectedVehicleType()
I attempted using interface instead of Type but the outcome remained unchanged.
Hence, how can I accomplish this or is there a more efficient approach?
Appreciate your help in advance!