Consider the following code snippet:
app-config.json
{
"auth": {
"clientId": "acb610688b49",
},
"cache": {
"cacheLocation": "localStorage"
},
"scopes": {
"loginRequest": ["openid", "profile", "user.read"]
},
"resources": {
"gatewayApi": {
"resourceUri": "https://localhost:44351/api",
"resourceScope": ["api://0e01a2d8/access_as_user"]
}
}
}
authService.js
import { isInternetExplorer } from 'src/services/utils/utilsService'
import * as Msal from 'msal'
import * as configJson from 'src/app-config.json'
type resourceType = {
resourceUri: string
resourceScope: string | string[]
}
type resourcesType = {
[key: string]: resourceType
}
interface JsonConfigInterface extends Msal.Configuration {
scopes: {
loginRequest: string[]
}
resources: resourcesType
}
const config: JsonConfigInterface = configJson as JsonConfigInterface
function MSALConfigFactory(): Msal.Configuration {
return {
auth: {
clientId: config.auth.clientId,
},
cache: {
cacheLocation?: config.cache.cacheLocation as Msal.CacheLocation,
},
}
}
An error related to
cacheLocation?: config.cache.cacheLocation as Msal.CacheLocation
has been reported:
(property) cache?: CacheOptions | undefined Object is possibly 'undefined'.ts(2532)
Reference to the msal documentation reveals:
export type CacheLocation = "localStorage" | "sessionStorage";
export type CacheOptions = {
cacheLocation?: CacheLocation;
storeAuthStateInCookie?: boolean;
};
The presence of a question mark in cacheLocation?
implies its optional nature, which should be acceptable. It can either be defined or left undefined in the JSON file. Thus, it is puzzling why TypeScript raises an issue about potential undefined
value when it is a valid possibility. Although there is a TS null check implemented, shouldn't it permit this due to the question mark?
A temporary workaround that works for now is provided below, but I am uncertain if this is the correct solution:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
cacheLocation: config.cache!.cacheLocation as Msal.CacheLocation,
I am still learning, so any guidance you can offer would be greatly appreciated.