Unable to determine the type of an array using TypeScript

Here is the code snippet I'm working with:

interface ItemA{
  x:number
  y:string
}

interface ItemB{
  z:boolean
}

interface Data{
  a:ItemA[]
  b:ItemB[]
  bool:boolean
}

type ItemType=keyof Data&('a'|'b')

function f<K extends ItemType>(data:Data,key:K):void{
  type T=Data[K] extends (infer TT)[]?TT:never
  const values:T[]=data[key]

  values.forEach(
    (t:T):void=>{
      console.log(t)
    }
  )
}

I want to assign T variable to be of type ItemA when the key parameter is equal to 'a', and of type ItemB when it's 'b'. This way, the values array could either be of type ItemA[] or ItemB[]. How can I make this work?

When trying to implement this functionality, I encountered the following TypeScript error:

20:9 Type 'ItemA[] | ItemB[]' is not assignable to type 'T[]'.
  Type 'ItemA[]' is not assignable to type 'T[]'.
    Type 'ItemA' is not assignable to type 'T'.

Answer №1

Is this how you do it?

interface ItemA{
  x:number
  y:string
}

interface ItemB{
  z:boolean
}

interface Data{
  a: ItemA[]
  b: ItemB[]
  bool: boolean
}

type ItemType = 'a' | 'b';

function f(data: Data, key: ItemType): void
{
  type T = Data[typeof key]
  const values: T = data[key]
  values.forEach(
    (t: ItemA | ItemB) => {
      console.log(t)
    }
  )
}

Try it out in the 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

Unexpected Behavior: Angular App Retrieving Entire Collection, Instead of Limited Number of Results

Incorporating observables in my Angular application to fetch data from our API has been a challenging task. Due to the substantial amount of data to be retrieved, we implemented ng2-pagination for efficient pagination handling. The objective was to load sp ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects. moment.service.ts The get method success ...

Execute an Angular application that triggers a Python cloud function

I have successfully deployed a Python cloud function on GCP. from flask import escape import functions_framework @functions_framework.http def hello_http(request): """HTTP Cloud Function. Args: request (flask.Request): The r ...

Error occurs because the declaration for `exports` is missing in the compiled TypeScript code

I am currently venturing into the world of typescript and I've encountered a problem while attempting to run my application. An error is popping up, stating ReferenceError: exports is not defined The code I have written is rather straightforward: / ...

TS2532 Error: Potential uncertainty of an object being 'undefined' even after verifying its definition

Below is the implementation of a helper class that generates a hash: export default class PageUtil { private size: number; private step: PageUtilStep; private cursor: unknown[] | undefined; public constructor(size: number, step: PageUtilSt ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

The metadata for Company#companyTypesLinks could not be located. Please verify that the entity object has been correctly specified

I am facing an issue with the relationship between my entities. I have tried everything, but I still encounter the same problem. Here are my scripts: Company.entity.ts export class Company extends AppBaseEntity { @Column('text', { name: ' ...

create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Pl ...

Guide on merging paths in distinct modules within an Angular project

I am looking to merge two sets of routes from different modules in my application. The first module is located at: ./app-routing.module.ts import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; i ...

Adding a property during runtime to an object does not display in the current "this" context

Can anyone explain why the dynamic property added using Object.defineProperty does not show up when printing 'this' on the console? Here is a Decorator example. It seems to be working fine, but the success and error properties do not appear in & ...

Retrieving the inner text of a dragged element using Angular Material's DragAndDrop feature

Can the inner text of a dragged element be retrieved and utilized in the "onDrop" function within Angular's cdkDragAndDrop feature? onDrop(event: CdkDragDrop<string[]>) { if (event.previousContainer === event.container) { moveItemIn ...

The specified property is not present in the type '{}'

I've been incorporating Typescript into my React application Within my mapStateToProps, this is the code I'm using const mapStateToProps = (state: AppState) => { console.log(state) return { ...state.player, position: ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

incorrect indexing in ordered list

I am facing an issue with the ngIf directive in Angular. My objective is to create a notification system that alerts users about any missing fields. Here's a stackblitz example showcasing the problem: https://stackblitz.com/edit/angular-behnqj To re ...

Having trouble compiling my project with Typescript, Jest, @types/jest, and ts-jest

I'm currently utilizing jest for mocking my axios requests. Here is an example of my test implementation: // External imports import axios, { AxiosPromise } from 'axios' // Personal imports import { getProgramApplications } from '#sto ...

Access the PrimeNG context menu in Angular 2 by using code to open it

I am trying to open the context menu provided by PrimeNG in a table by using a button and right click. Although I have found the methods 'toggle' and 'show' in the component, the menu is not opening. Even after setting a new position fo ...

Having trouble retrieving data from a json file using a GET request in Angular?

As a novice in dealing with json objects, I am having trouble extracting data from the GroupResult object. Below is the structure of my classes: export class GroupResult { Id!: number; Lecturer!: string; GroupName!: string; Subjects!: SubjectStats ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...