Encountering TypeScript Issue with switch case discrimination (TS2367)

Am I making a mistake in my logic or is the compiler having trouble understanding my intentions?

Error - Line i4:

This condition will always return true since the types SubjectType.Both | SubjectType.A and SubjectType.B have no overlap.

j1  enum SubjectType {
j2      BOTH,
j3      A,
j4      B,
j5  }

i1  switch ( subjectType: SubjectType ) {
i2      case SubjectType.BOTH
i3      case SubjectType.A:
i4          if( subjectType !== SubjectType.B ) {
i5              //Do operation A
i6          }
i7      case SubjectType.B:
i8          if( subjectType !== SubjectType.A ) {
i9              //Do operation B
i10         }
i11 
i12         break;
i13      default:
i14          throw new TypeError( `Unknown SubjectType ${subjectType} provided` );
i15  }

UPDATE: I have realized that there was an error in my logic.

i1  switch ( subjectType: SubjectType ) {
i2      case SubjectType.BOTH
i3      case SubjectType.A:
i4          //Do operation A, if type A | BOTH
i5
i6      case SubjectType.B:
i7          if( subjectType !== SubjectType.A ) {
i8              //Do operation B
i9          }
i10 
i11         break;
i12      default:
i13          throw new TypeError( `Unknown SubjectType ${subjectType} provided` );
i14  }

Answer №1

subjectType variable can only be in one of three states: A, B, or BOTH. Here's an example to illustrate:

enum SubjectType {
    BOTH,
    A,
    B,
}
const subjectType: SubjectType = null as any

function foo() {
    switch (subjectType) {
     case SubjectType.BOTH:
     case SubjectType.A:
        if (subjectType !== SubjectType.B) {
            //Do thing A
        }
     case SubjectType.B:
        if (subjectType !== SubjectType.A) {
            //Do thing B
        }

        break;
      default:
        throw new TypeError(`Unknown SubjectType ${subjectType} provided`);
    }
}

In these two lines within the switch statement:

case SubjectType.BOTH:
case SubjectType.A:

it is implied that subjectType should be either BOTH or A, but not B.

Therefore, attempting to compare subjectType with B using

if (subjectType !== SubjectType.B) {
, is unnecessary because it is known that subjectType cannot be B in this scenario.

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

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

Activate the mat-menu within a child component using the parent component

Incorporating angular 6 along with angular-material, I am striving to trigger the matMenu by right-clicking in order to utilize it as a context menu. The present structure of my code is as follows. <span #contextMenuTrigger [matMenuTriggerFor]="context ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

QueryBuilder in TypeORM can be utilized to select solely a particular key-value pair from a column with the JSONB

Consider a basic queryBuilder implementation: const workout = await this.workouts .createQueryBuilder('workout') .select(['workout.uuid', `workout.name ->> 'it'` as name]) .where(&apos ...

What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next(). However, I am looking for a way to push items into this array without having to assign a full copy ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

When employing a string union, property 'X' exhibits incompatibility among its types

In my code, I have two components defined as shown below: const GridCell = <T extends keyof FormValue>( props: GridCellProps<T>, ) => { .... } const GridRow = <T extends keyof FormValue>(props: GridRowProps<T>) => { ... & ...

Discovering the proper way to infer type for tss-react withParams and create

Greetings to everyone and a huge thank you in advance for your generous help. I have a desire to utilize the tss-react library for styling, particularly because I will be implementing Material UI components. As I delve into some documentation, the latest A ...

Feathers.js - Error: Property 'feathers' is missing from the 'Socket' type

Trying to include a property in a socket connection to identify the user and send a response solely to that individual. Came across a potential solution at: How to add parameters to a FeathersJS socket connection Unfortunately, the solution doesn't s ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Extending the Request type from Express with Typescript

Having a NodeJs app with Express and Typescript, I am attempting to extend the Request type from Express. I have created an index.d.ts file with the following code snippet: import { User } from "models/user"; declare global { namespace Expres ...

imitationImplementation function syntax

I'm currently working on simulating the output of the sendToDevice function from the Firebase library, but I'm facing a challenge with the return value of MessagingDevicesResponse (refer to HERE in the code snippet below) import MessagingDevicesR ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

Checking to see if a string meets the criteria of being a valid ARGB value

How do I verify that a string represents a valid ARGB value, such as #ffffffff for ARGB 255,255,255,255? Is there a way to validate this using TypeScript and C#? ...

What is the method for implementing a custom layout for the items within a Select component?

I want to customize the options of a Select component by adding HTML elements. Here is an example: <mat-select [(ngModel)]="items"> <mat-option *ngFor="let item of ($items | async)" [value]="item.id"> <span>{{item.name}}</span&g ...

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Retrieving data from Redis cache may not always yield the exact same data

I have been working on creating a small Express app that retrieves data from a PostgreSQL query and caches the result in a Redis database. Here is my approach: app.get('/query_tile/:z/:x/:y', async (req: Request, res: Response) => { const ...