Accessing a defined type from a variable in an Angular project using Typescript

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!

Answer №1

To access the index type, you need to specify keyof TypeMap for the variables.

interface Car {
  id: number;
  model?: string;
}

interface House {
  id: number;
  color?: string;
}

type TypeMap = {
  Car: Car,
  House: House,
  // etc
}

function getSelectedItemType(): keyof TypeMap {
  return 'House';
}

function func2(){
  const itemType1: keyof TypeMap = "Car"
  const itemType2: keyof TypeMap = getSelectedItemType()
  type myType1 = TypeMap[typeof itemType1];
  type myType2 = TypeMap[typeof itemType2]; // This line causes an error saying "Type TypeMap does not have a matching index signature for type string"
  let item1: myType1 = {id: 1};
  let item2: myType1 = {id: 1, model: "Audi"};
  let item3: myType2 = {id: 1, color: 'blue'};
}

Typescript Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating containers in Angular using *ngFor

As a beginner in Angular, Bootstrap, and front-end programming, I am looking to create multiple boxes that reveal detailed information when clicked. This is the desired outcome: https://i.sstatic.net/Ak0eA.png After clicking on box number 1: https://i.s ...

Tips for reducing redundant API requests while using NgRx

I'm facing an issue with my application that has 2 menu items; Teams and Players. Every time I switch between them, an unnecessary API call is made even though the data is already stored. Here is the effects file: loadTeams$ = createEffect(() => { ...

Comparing the installation of TypeScript on Ubuntu utilizing npm versus native packages (via apt)

I'm looking to incorporate Typescript into my Ubuntu system and have come across two different methods to do so: Using sudo apt update && sudo apt install node-typescript -y Running sudo npm install -g typescript My main question revolves ar ...

Error: Property 'content' is not defined and cannot be read

I encountered an issue with a config file while attempting to build with AOT using the command ionic cordova build android --prod Error: ./src/config/.env.ts Module build failed: TypeError: Cannot read property 'content' of undefined at Object ...

I am seeking a way to access the child infoWindow within a Google Maps marker in Angular 5

I am working on an Angular 5 application that utilizes the Angular Google Maps(AGM) library available at . I have implemented functionality where clicking on an item in a list within one component triggers the display of a child infoWindow associated with ...

Sorting and dividing an Array using Angular

Forgive me in advance if this sounds like a naive question, as Angular and Typescript are not my strong suits. I am assisting a friend with an issue that I can't seem to overcome. I have an array of players that includes details such as first name an ...

Tips for effectively utilizing the 'or' operator when working with disparate data types

One of my functions requires an argument that can have one of two different types. If you're interested in TypeScript functions and types, take a look at the official documentation, as well as these Stack Overflow questions: Question 1 and Question 2 ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Having trouble solving the problem. Implementing a 3D glTF model using threejs and Angular

I've been struggling for quite some time now to grasp the concept of three.js and how to incorporate 3D models into it using Angular. Despite looking through the documentation and searching everywhere, I just can't seem to pinpoint where I' ...

Tips for implementing validators for both domestic and international phone numbers in Angular

Using the following code in a TS file, the first argument always works before the "||". However, only the regex needs to be manipulated. phoneNumber: ['', [Validators.required, Validators.pattern(('^[0]{1}[1-9]{9}$')||('^\&bs ...

Opting out of notifications using Angular's NGXS

I'm new to NGXS in Angular and have recently learned that you don't need to manually unsubscribe when using the async pipe. However, I am currently subscribing to both query parameters and dispatched actions. Do I still need to manually unsubscri ...

Angular: a technique for creating customized error messages and modifying fields

When an error occurs in a form, the text fields are cleared and the errors are set as shown below switch(result){ case "SUCCESS": // handle success case case "ERROR1": this.Form.controls.text1.setValue(''); ...

Troubleshooting: Resolving the Error "Cannot find Property htmlFor on Custom React Component"

I am currently working with a custom component that looks like this: import React from "react"; import classnames from 'classnames'; import { ButtonVariantColor } from '../types/button'; export type IconButtonProps = { e ...

Omit the timezone details when initializing a new Date object in Angular

Encountered a problem while testing the following line of code console.log(JSON.stringify(new Date('2016-06-15 10:59:53.5055'))); The result I'm getting is "2016-06-15T08:59:53.505Z", but I was expecting "2016-06-15T10:59:53.505Z" Is ther ...

Experiencing difficulties implementing a Sign in with Google feature with .NET Core 2.1 and Angular 2

Currently, my tech stack consists of Angular 2, Net Core 2.1, and Identity. I've been exploring the option of enabling Google authentication, but have encountered some limitations while using client side gapi libraries - particularly when dealing with ...

Angular automatically substitutes a string with the location of an image

I am currently working on developing a frame data application for a fighting game in angular/ionic, which is still relatively new to me. The app will consist of individual spreadsheets for each character showcasing the attributes of all their moves. Check ...

Can the dimensions of a dialog be customized in Angular Material Design for Angular 5?

I am currently developing a login feature for an Angular 5 application. As part of this, I have implemented an Angular Material Design popup. Within the dialog screen, I have a specific process in place: The system checks the user's email to determi ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Challenge with AngularJS: Dynamic Table Total not Updating

I am having trouble updating the total prices and quantities when adding an item to my table. The total is not refreshing correctly. Can someone help me identify the error in my code? $scope.updateTotals = []; function ExampleCtrl ($scope){ $scope. ...

Issue with Angular nested observable & forkJoin failing in one scenario, while it functions correctly in another

UPDATE The simulation for OtherService was incorrect. You can check the detailed explanation on this answer. I am trying to identify the issue in the test file that causes it to behave differently from the component. I am puzzled as to why the next: state ...