Typescript枚举为变量提供了错误的类型?

jogvjijk  于 2023-08-07  发布在  TypeScript
关注(0)|答案(2)|浏览(133)

我有一个enum:

export enum AlgorithmEnum {
    SHA1,
    SHA256,
    SHA512
}

字符串
我把它用于一个类的属性Algorithm:

export class Authenticator {
    Type: Type = Type.TOTP;
    Icon: string = '';
    Issuer: string = '';
    Username: string = '';
    Secret: string = '';
    Pin: null = null;
    Algorithm: AlgorithmEnum = AlgorithmEnum.SHA1;
    Digits: number = 6;
    Period: number = 30;
    Counter: number = 0;
    CopyCount: number = 0;
    Ranking: number = 0;

    constructor() {

    }
}


然后在其中一个组件中,我尝试将其与开关一起使用:

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 = '';

      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/';

    });
}


似乎应该工作,对不对?它不:

为什么会出现这个错误?它看起来像 typescript 错过了一个枚举,没有适当的类型?

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

qvk1mo1f

qvk1mo1f1#

由于注解标记的条件,您的代码显式筛选出值SHA1:

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/';

    });
}

字符串
这是因为枚举中的SHA1获得分配的数值0。在if条件中,数值0(类似于空字符串)的计算结果为false。所以TypeScript将类型缩小到排除SHA1。
将if条件更改为

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


得双曲余切值.

v1l68za4

v1l68za42#

在您的示例中,AlgorithmEnum枚举没有定义显式数值,因此AlgorithmEnum.SHA1的数值为0,AlgorithmEnum.SHA256的数值为1,AlgorithmEnum.SHA512的数值为2。因此,只需将枚举更改为:

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

字符串

相关问题