Is your variable being assigned the incorrect type by a Typescript enum?

Within my codebase, I have defined an enum called AlgorithmEnum:

export enum AlgorithmEnum {
    SHA1,
    SHA256,
    SHA512
}

This enum is utilized as the Algorithm property of a class named Authenticator:

export class Authenticator {
    Type: Type = Type.TOTP;
    Icon: string = '';
    Issuer: string = '';
    Username: string = '';
    Secret: string = '';
    Pin: null = null;
    Algorithm: AlgorithmEnum = AlgorithmEnum.SHA1;
    // Additional properties omitted for brevity 

    constructor() {

    }
}

However, when attempting to apply a switch statement with this enum in one of the components, an error is encountered:

exportUriList() {
    const authData = this.authDataService.authData;
    let uriList: string[] = [];

    authData.Authenticators.forEach(auth => {
      let issuerAndUsername = `${auth.Issuer}:${auth.Username}`;
      let secret = `?secret=${auth.Secret}`;
      let issuer = `&issuer=${auth.Issuer}`;
      let algorithm = '';

      if (auth.Algorithm) {

        switch (auth.Algorithm) {
          case AlgorithmEnum.SHA1:
            break;
          case AlgorithmEnum.SHA256:
            break;
          case AlgorithmEnum.SHA512:
            break;
        }

        algorithm = `&algorithm=${auth.Algorithm}`;
      }

      let uri = 'otpauth://totp/';

    });
}

The error message suggests a comparison issue between the enums:

Type 'AlgorithmEnum.SHA1' is not comparable to type 'AlgorithmEnum.SHA256 | AlgorithmEnum.SHA512'.

Answer №1

The code explicitly filters out the SHA1 value due to a specific condition indicated by the comment:

exportUriList() {
    const authData = this.authDataService.authData;
    let uriList: string[] = [];

    authData.Authenticators.forEach(auth => {
      //otpauth://totp/IBM%20Security%20Verify:@USER_NAME@?secret=@SECRET_KEY@&issuer=IBM%20Security%20Verify&algorithm=@ALGORITHM@

      let issuerAndUsername = `${auth.Issuer}:${auth.Username}`;
      let secret = `?secret=${auth.Secret}`;
      let issuer = `&issuer=${auth.Issuer}`;
      let algorithm = '';

      // THIS FILTERS OUT THE VALUE 0, WHICH IS SHA1
      if (auth.Algorithm) {

        switch (auth.Algorithm) {
          case AlgorithmEnum.SHA1:
            break;
          case AlgorithmEnum.SHA256:
            break;
          case AlgorithmEnum.SHA512:
            break;
        }

        algorithm = `&algorithm=${auth.Algorithm}`;
      }

      let uri = 'otpauth://totp/';

    });
}

The reason behind this is that in the enum, SHA1 is assigned the numeric value 0. When evaluated in an if condition, the numeric value 0 (similar to an empty string) is considered false. As a result, TypeScript excludes SHA1 from the type.

To resolve this issue, modify the if condition to

if (typeof auth.Algorithm === "number") {

instead.

Answer №2

The AlgorithmEnum enum in your scenario does not have specific numerical values assigned. Therefore, when using AlgorithmEnum.SHA1, it will be considered as 0, AlgorithmEnum.SHA256 will be 1, and AlgorithmEnum.SHA512 will be 2. To address this, simply update your enum as follows:

enum AlgorithmEnum {
  SHA1 = 'SHA1',
  SHA256 = 'SHA256',
  SHA512 = 'SHA512',
}

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

Definitions for d3-cloud

I am trying to create a word cloud using d3-cloud in my Angular2 application. However, I am struggling to find the correct typings to install. I attempted to use this package @types/d3.cloud.layout from npm but encountered an issue when importing it into ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

How to modify the appearance of the md-tab-header component in Angular2

Currently, I am working on a project that was passed down to me by a former colleague. It is a gradual process of discovery as I try to address and resolve any issues it may have. One particular element in the project is a md-tab-header with a .mat-tab-he ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Using Typescript to import functions

TLDR - I need help understanding the difference between these imports in ReactJs using Typescript: setState1: (numbers: number[]) => void, setState2: Function Hello everyone, I've encountered some strange behavior when importing functions with Typ ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Challenges with font files in ionic 3 ngx-datatable data table

Hello everyone, I encountered 2 errors when running an ionic 3 app with ngx-datatable: (1) GET http://localhost:8100/build/fonts/data-table.woff net::ERR_ABORTED index.js:5465 (2) GET http://localhost:8100/build/fonts/data-table.ttf net::ERR_ABORTED :81 ...

The requested resource does not have an 'Access-Control-Allow-Origin' header

- ISSUE: The XMLHttpRequest to 'https://*.execute-api.*.amazonaws.com/api' from 'http://localhost:4200' is blocked by CORS policy. The preflight request doesn't have the necessary 'Access-Control-Allow-Origin' header. ...

"Enhance your user experience with seamless drag and drop functionality for transferring items between

I am currently working on transferring items between a list and table using the drag-and-drop feature of PrimeNG. Both elements should be able to act as both drag sources and drop destinations. My project is based on PrimeNG-9.0.0 and Angular 9.0.2 https ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Combining two arrays in typescript using the map method

I have an array of heart rate, height, and weight values. { "heart_rate": 27, "height": 82, "weight": 78 } There is also a second array containing information about each value, such as ID, label, and description. ...

Experimenting with viewProvider in a component test

@Component({ selector: 'app-entity-details', templateUrl: './entity-details.component.html', styleUrls: ['./entity-details.component.scss'], viewProviders: [{ provide: ControlContainer, useFactory: (container: ...

Invoke the method saved as a class attribute

Within my codebase, there exists a class named Process. This class has a constructor that takes in a type of object () => void. Initially, everything seemed to be working perfectly fine when I passed this object into the class. However, issues arose whe ...

Tips for deleting a specific choice with Angular

Having recently started working with Angular2 / TS / ES6, I am struggling to find a solution to my issue. I have a select element with dynamically rendered options using ngFor from an array. These options are meant for selecting attributes for a product. ...

Get the most recent two files from a set

I am currently facing a challenge in retrieving the first 2 documents from a collection in google cloud firestore. My current approach involves using the timestamp of the latest document and then calculating the time range to fetch the desired documents. l ...

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the foll ...

Create a Bar Graph Using a List

Looking to generate an Angular Barchart from a JPA query in Spring: public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) { String hql = "SELECT SUM(amount) AS sum_volume, ...

Angular 2 Rapid Launch: Incorrect Encoding of JavaScript Files

I am brand new to learning angular 2, so I am currently attempting to get things up and running following this guide: https://angular.io/guide/quickstart The issue I am facing has left me quite puzzled. Whenever I receive any JS files as a response, they ...