The specified property is not found within the type being referenced in the switch statement

Currently, I am attempting to implement something similar to the following (although it is much more complex):

interface Base {
    id: string;
    info: object;
}

interface A extends Base {
    example: boolean;
}

interface B extends Base {
    max: number;
}


interface ActionDataTypes {
    'for_a': A;
    'for_b': B;
}

function tryAction<A extends keyof ActionDataTypes>(id: string, action: A, data: ActionDataTypes[A]): boolean {

    switch(action){
        case 'for_a':
            //do stuff
            break;
        case 'for_b':
            //do stuff
            //this is a more complicated if statement
            if(data.max > 12){
                //do stuff
            }
            break;
    }

}

An issue arises in TypeScript where the error message states

Property 'max' does not exist on type 'A | B'. Property 'max' does not exist on type 'A'.

I am seeking insight on how to resolve this error. Any ideas?

The following inquiries did not provide a solution:

  • Typescript type safety in switch case statements
  • Typescript does not consider the 'case' of a switch statement as a typeguard?
  • Typescript is there a way to cast type for case in switch?
  • TypeScript: Type guard does not work with switch statement when putting object into variable
  • Why Typescript throw error message: Property does not exist on type?

Answer №1

At this moment, the compiler lacks the capability to narrow down independent arguments by type. Therefore, I propose transitioning to a union of the arguments using a mapped type:

// [action: "for_a", data: A] | [action: "for_b", data: B]
type Args = {
  [K in keyof ActionDataTypes]: [action: K, data: ActionDataTypes[K]];
}[keyof ActionDataTypes];

Then, redefine the function tryAction as follows:

function tryAction(id: string, ...args: Args) {}

Check out this playground example

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

Exploring Angular2 Guides: Understanding Hierarchical Dependency Injection with a Focus on Service Restoration

As I delved into the Angular2 documentation, a specific example caught my eye in the Hierarchical Dependency Injectors chapter. It introduced me to the Restore service, which enables save/cancel functionality for editing. The code for this service is as f ...

"Encountered an issue with Angular 2 when attempting to post data to an API -

After downloading a project from the link provided by ASP.NET on individual accounts in Web API, I managed to run it successfully on VS2015 and IIS Express. However, my goal now is to utilize Angular 2 to call the API. In order to achieve this, I set up a ...

Utilizing Angular 2's ngModel feature for dynamic objects and properties

Within my TypeScript file, I am dynamically generating properties on the object named selectedValsObj in the following manner: private selectValsObj: any = {}; setSelectedValsObj(sectionsArr) { sectionsArr.forEach(section => { section.questions. ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Type inference in TypeScript fails to capture inner level types

Looking at the code snippet below, I'm struggling to understand why FinalType is defined as { test: { test_inner: any } }. The presence of any is puzzling to me (especially since string seems to have disappeared). Interestingly, the return type of tes ...

Issue with dynamic imports and lazy-loading module loadChildren in Jhipster on Angular 8, not functioning as expected

When utilizing dynamic import, it is necessary to modify the tsconfig.json file in order to specify the target module as esnext. ./src/main/webapp/app/app-routing.module.ts 14:40 Module parse failed: Unexpected token (14:40) File was processed with these ...

What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conve ...

Exploring API information in Ionic 4

Looking to retrieve data from the API, specifically using PHP on the backend. While I can access the data successfully, I'm running into an issue with *ngFor and the search bar functionality. The search button only appears when the input in the search ...

Is there a built-in feature in npm or yarn that automatically installs @types when they are present in Typescript projects?

Is there a feature in npm or yarn that automatically installs @types/* for packages without their own types, in Typescript projects? For example: //package.json { // ... "installTypes": true } // installing package yarn add ABC <- will install A ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Unable to assign properties in TypeScript

export function updateAttributes(attributes: string[][], data: Object, element: HTMLElement): void { attributes.forEach(([attr, value]) => { let parsed = parseString(value, data) if (value !== element.attributes[attr]) { ...

When I use the shift method on one array, it alters the contents of that array

I am encountering a peculiar issue with two arrays of objects in my program. One array is named "Responses" and the other is called "Questions." The problem arises when I remove the first element from an object in the "Questions" array using shift() meth ...

Tips for patiently waiting to receive a value from Useselector

I have been working on a basic MyPage implementation. When Mypage.tsx is initially rendered, Redux saves user information using useEffect. However, when I attempt to retrieve data with UseSelector right after that, an error message stating that the value c ...

Add an additional boolean attribute called `_ro` as a suffix to a property

Is it possible to add an additional property using a property decorator? The current approach I am taking seems to be incorrect. const RoProp = () => { return <T>(target: T, memberName: keyof T) => { const roPropName = `${String(memberNa ...

Utilizing AWS Websockets with lambda triggers to bypass incoming messages and instead resend the most recent message received

I am facing an issue when invoking a lambda that sends data to clients through the websocket API. Instead of sending the actual message or payload, it only sends the last received message. For example: Lambda 1 triggers Lambda 2 with the payload "test1" ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

A function that accepts an array of strings as a parameter and returns a typed map with the same keys as

I have a function that takes an array of strings and returns a map with each element of the array as a key. I want the returned type to reflect this. This is my current implementation (Playground): function register<T extends string>(name: string, e ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

Issue: The browser.newPage function is expecting to receive either accept, deny, or internal-browser-default for download permissions

Utilizing playwright automation, I currently have tests running on browser stack with playwright version 1.37.1. Error: browser.newPage: acceptDownloads: expected one of (accept|deny|internal-browser-default) at src/base/fixtures.ts:62 60 | ...