Achieving the desired type of value within a nested record

I am trying to create a unique function that can manipulate values of a nested Record, based on the collection name. However, in my current implementation, I am facing difficulty in attaining the value type:

type Player = { name:string }
type Point = { x:number, y:number }


const collections = {
    players: {} as Record<string, Player>,
    positions: {} as Record<string, Point>,
}

type Collections = typeof collections;


function handleEntity<
    Key extends keyof Collections,
    Col extends Collections[Key],
    Val extends Col[keyof Col],
>(name:Key, value:Val){
    switch(name){
        case 'positions': value.x++ // <-- Not valid :(
    }
}

Can you tell me why TypeScript is not able to infer Val in this scenario? Is there any possible workaround?

Answer №1

The TypeScript compiler sometimes struggles to accurately narrow down the types of generically typed variables. While the relationship between name and value is recognized by the compiler during function calls, narrowing the type of value based on name within the implementation is currently not feasible, especially when name and value are generic types.

To address this issue, one approach is to remove the generic types and establish a union type for the parameters.

function handleEntity(...[name, value]: { 
    [K in keyof Collections]: [K, Collections[K][keyof Collections[K]]] 
  }[keyof Collections]
){
    switch(name){
        case 'positions': value.x++ // type narrowed successfully :)
    }
}

handleEntity("players", { name: "abc" })
handleEntity("positions", { x: 1, y: 0 })

By treating the name, value tuple as a discriminated union, the compiler can effectively narrow down the type of value by examining the value of name.

If it's necessary for handleEntity to remain generic, you can include the generic signature as an overload.

function handleEntity<
    Key extends keyof Collections,
    Col extends Collections[Key],
    Val extends Col[keyof Col],
>(name:Key, value:Val): void
function handleEntity(...[name, value]: { 
    [K in keyof Collections]: [K, Collections[K][keyof Collections[K]]] 
  }[keyof Collections]
){
    switch(name){
        case 'positions': value.x++ // type narrowed successfully :)
    }
}

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

Decoding enum interface attribute from response object in Angular 4 using typescript

From an API response, I am receiving an enum value represented as a string. This enum value is part of a typescript interface. Issue: Upon receiving the response, the TypeScript interface stores the value as a string, making it unusable directly as an en ...

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

What is the best way to treat each TS file as its own independent module?

Just starting out in the world of TS and feeling like a newbie. I've noticed that in Dart, each file in a directory can run independently and you have to explicitly import objects from other files if needed. For example: file1.dart int myFunc() => ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Using Angular Form Builder to assign a value depending on the selected option in a dropdown menu

My approach to Angular Form Builder initialization includes a group that looks like this: contactReason: this.formBuilder.group({ description: '', source: this.sourceType() }) For the 'description' field, I hav ...

The bespoke node package does not have an available export titled

No matter what I do, nothing seems to be effective. I have successfully developed and launched the following module: Index.ts : import ContentIOService from "./IOServices/ContentIOService"; export = { ContentIOService: ContentIOService, } ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...

Creating dynamic dxi-column with different data types in dxDataGrid

Our team is currently working on an angular application that involves displaying records in a dxdatagrid. The challenge we are facing includes: Different schema each time, with data coming from various tables. The need to add/edit records. Displayi ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

"Utilizing the power of Angular 6's JSON pipe

Looking for a well-structured formatted JSON, but all I get is confusion and this strange image: Does anyone have any insights on what might be causing the issue? HTML <span style="font-weight: 500;">Payload Data: </span> <pre><co ...

"Dealing with conflicts between RMQ and TypeORM in a NestJS

Every time I try to use TypeOrm, RMQ crashes. I can't figure out why. Utilizing the library golevelup/nestjs-rabbitmq has been a struggle for me. I've spent 7 hours trying to resolve this issue. @Module({ imports: [ ConfigModule.f ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

Using promises in TypeScript index signature

Can you help me find the correct index signature for this particular class? class MyClass { [index: string]: Promise<void> | Promise<MyType>; // not working public async methodOne (): Promise<void> { ... } public async methodTwo () ...

Angular 6 offers a versatile multi-select dropdown feature

Looking to select multiple values in Angular 6 using checkboxes. When selecting a department from the dropdown, a list of employees related to that department is displayed in another dropdown with checkboxes. However, only the last value of the array app ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

Tips for effectively utilizing the drag and drop feature with the Table Component in Ant Design

Recently, I received a new project from another team, and my client is requesting some changes to the admin page. Specifically, they want to customize the order of data pulled from the database. For instance, they would like to arrange the job positions in ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

Explanation on How to utilize the $( document ).ready() jQuery function within the ngAfterViewInit() on a Component class using Angular 2

This is the code snippet: constructor(private el: ElementRef) { } ngAfterViewInit() { this.loadScript('app/homepage/template-scripts.js'); } ...