TypeScript类型断言不会因错误的值而失败

时间:2020-05-12 12:21:03

标签: javascript typescript

我们正在使用库msal,并试图将我们的javaScript代码转换为TypeScript。

下图表明TS正确知道cacheLocation的类型。可以是字符串localStorage,字符串sessionStorageundefined。但是,当尝试将其与包含期望值之一的变量连接在一起时,它将失败:

enter image description here

将使用以下语法解决此问题。在这种情况下,唯一的问题是没有将错误的值标记为不正确:

enter image description here

在阅读TS docs on Type Assertions时,它表示这是设计使然,开发人员知道该类型将是正确的。但是我确实希望TS如果使用未知值会抛出错误。

有更好的方法吗?还是这仅仅是它的完成方式?抱歉,如果这是一个愚蠢的问题,我仍在学习TS。

代码

import * as config from 'src/app-config.json'
import { Configuration, CacheLocation } from 'msal'

const test = 'wrongValue'

export function MSALConfigFactory(): Configuration {
  return {
    auth: {
      clientId: config.auth.clientId,
      authority: config.auth.authority,
      validateAuthority: true,
      redirectUri: config.auth.redirectUri,
      postLogoutRedirectUri: config.auth.postLogoutRedirectUri,
      navigateToLoginRequestUrl: true,
    },
    cache: {
      cacheLocation: test as CacheLocation,
      storeAuthStateInCookie: false,
    },
  }
}

2 个答案:

答案 0 :(得分:1)

我认为这只是一个错字:在您的第一张图片中,您有LocalStora n ge(请注意多余的n)

enter image description here

答案 1 :(得分:0)

类型'“ localStorange”'不能分配给类型'“ localStorage” | “ sessionStorage” |未定义”

Storange

TypeScript非常擅长捕捉简单的错字,但不擅长告诉您确切的错误所在。