简体   繁体   中英

TypeScript type assertions doesn't fail on incorrect value

We're using the library msal and are trying to convert our javaScript code to TypeScript.

The following picture indicates that TS correctly knows the type expected for cacheLocation . This can be either the string localStorage , the string sessionStorage or undefined . However, when trying to wire this together with a variable that holds one of the expected values it fails:

在此处输入图像描述

The issue would be fixed by using the following syntax. The only problem in this case is that a wrong value is not flagged as incorrect:

在此处输入图像描述

When reading the TS docs on Type Assertions it says that this is by design and the developer knows that the type will be correct. I did however expect TS to throw an error if an unknown value would've been used.

Is there a better way for doing this? Or is this simply how it's done? Sorry if this is a stupid question, I'm still learning TS.

Code

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,
    },
  }
}

I think it's just a typo: in your first image you have LocalStora n ge (note the extra n)

在此处输入图像描述

Type '"localStorange"' is not assignable to type '"localStorage" | "sessionStorage" | undefined'

Storange

TypeScript is very good at catching simple typos, but not so good at telling you what exactly is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM