The switch statement and corresponding if-else loop consistently produce incorrect results

I'm currently facing an issue where I need to display different icons next to documents based on their file types using Angular framework. However, no matter what file type I set as the fileExtension variable (e.g., txt or jpg), it always defaults to returning file-text as the iconType.

    public getIcon(document: Document): string {
        let mimeType = document.fileType;
        let fileExtension = mimeType.split('.')[1];
        let iconType = '';

        switch (fileExtension) {
            case fileExtension === 'jpeg' || 'gif' || 'png' || 'svg' || 'xml'  || 'bmp' || 'jpg'|| 'tif' || 'tiff':
                iconType = 'picture';
                break;
            case fileExtension === 'avi' || 'mpg' || 'wmv' || 'mpeg' || 'mp4' || 'mov':
                iconType = 'video-folder';
                break;
            case fileExtension === 'cda' || 'mp3' || 'mpa' || 'wav' || 'wma':
                iconType = 'volume';
                break;
            case fileExtension === 'pdf' || 'ai' || 'pptx':
                iconType = 'article';
                break;
            default:
                //includes: .docx , .odt, .rtf, .txt, .xml, .xps
                iconType = 'file-text';
                break;
        }
        console.log(iconType);
        return iconType;
    }

Despite setting fileExtension to be "jpg", it always returns the default icon-type of "file-text" upon debugging. Debugging with breakpoints can be seen here.

I also attempted a simple if-else loop approach, but it still returned the first if case value for all scenarios (e.g.: picture even when fileExtension is "txt"):

        if (fileExtension === 'jpeg' || 'gif' || 'png' || 'svg' || 'xml' || 'bmp' || 'jpg' || 'tif' || 'tiff') {
            iconType = 'picture';
        } else if (fileExtension === 'avi' || 'mpg' || 'wmv' || 'mpeg' || 'mp4' || 'mov') {
            iconType = 'video-folder';
        } else if (fileExtension === 'cda' || 'mp3' || 'mpa' || 'wav' || 'wma') {
            iconType = 'volume';
        } else if (fileExtension === 'pdf' || 'ai' || 'pptx') {
            iconType = 'article';
        } else {
            iconType = 'file-text';
        }
        console.log(iconType);
        return iconType;

I am quite perplexed as to why it does not enter the correct case. Any assistance would be highly appreciated!

Answer №1

To ensure accuracy, remember to reiterate the left side of your conditional check within each if statement; alternatively, consider creating separate cases for each unique file extension type in your switch.

if(fileExtension === “jpg” || fileExtension === “png” …) {…}

If you are looking for additional approaches, here are some alternatives:

Utilize an array to store each picture type and then verify if the value is present in the array:

pictureFileExtensions = [“jpg”, “gif”, …]
videoFileExtensions = […]

If (pictureFileExtension.includes(fileExtension)){
        iconType = “picture”
    } else if (videoFileExtension.includes(fileExtension)){
        iconType = “video”
    } else if …

Another option is to create an object with the file extension as the key and the corresponding icon type as the value:

const iconTypes = {jpg: “picture”, avi: “video”, …}

iconType = iconType[fileExtension]

Answer №2

You might want to reconsider how you're utilizing the switch case statement. The correct syntax is as follows:

    switch (fileExtension) {
        case 'jpeg':
        case 'gif':
        case 'png':
        case 'svg':
        case 'xml':
        case 'bmp':
        case 'jpg':
        case 'tif':
        case 'tiff':
            iconType = 'picture';
            break;
        case 'avi':
        case 'mpg':
        case 'wmv':
        case 'mpeg':
        case 'mp4':
        case 'mov':
            iconType = 'video-folder';
            break;
        case 'cda':
        case 'mp3':
        case 'mpa':
        case 'wav':
        case 'wma':
            iconType = 'volume';
            break;
        case 'pdf':
        case 'ai':
        case 'pptx':
            iconType = 'article';
            break;
        default:
            //includes: .docx , .odt, .rtf, .txt, .xml, .xps
            iconType = 'file-text';
            break;
    }

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

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

Error in parsing: Unexpected token encountered. Expected a comma instead. Issue found in React with Typescript

I'm encountering a new error message that I haven't seen before... I've checked my code thoroughly and it seems to be correct, yet the error persists. Here is my code snippet: interface AuthState { token: string; user: User; } interfac ...

Exploring the method of including a mat-chip-list within a form

Can't submit form with mat-chip-list elements, even though they are present. How to send the tag array? Please assist! View my form here Here is the code I have so far: <mat-form-field class="example-chip-list"> <mat-chip-list #c ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

During the installation of npm in my angular project directory, an error occurred

Encountered an error while installing packages (npm)...npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Received an invalid response when trying to fetch https://registry.npmjs.org/@babel%2fplugin-proposal-nullish-coalesc ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

One method for deducing types by analyzing the function's return value within a react prop

There is a component definition that accepts two generics: function AsyncFlatList<ApiResponse, Item>({}: { url: string; transformResponse: (response: ApiResponse) => Item[]; keyExtractor: (item: Item) => string; }) { // the implementati ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Using React.js to compare values in a switch statement

I've made some changes to the code, removing breaks, leaving one at the bottom, and altering the order of cases. I've also switched between greater than/less than comparisons. Including breaks will determine whether it hits the first or last case ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Utilizing Font Awesome in the header of an Ag-Grid table

Having trouble adding an icon to my header using fa-icon. In my app.component file, I have imported: import { faImages } from '@fortawesome/free-solid-svg-icons'; and added: faImages = faImages; Within my columnDefs, I am using: { field : & ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Unable to change the name of the file using ngx-awesome-uploader

Currently, I am utilizing https://www.npmjs.com/package/@sleiss/ngx-awesome-uploader and facing an issue regarding renaming files before uploading them. Upon reviewing the available methods, it appears that there is no option for file renaming. While I c ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

How can a date range validation be implemented with two distinct ngx date picker fields in Angular 10?

Click here to view the image description In the illustration provided, I am seeking a solution to restrict users from selecting dates in the end date picker that occur before the chosen start date. ...

The process of running npx create-react-app with a specific name suddenly halts at a particular stage

Throughout my experience, I have never encountered this particular issue with the reliable old create-react-app However, on this occasion, I decided to use npx create-react-app to initiate a new react app. Below is a screenshot depicting the progress o ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...