Code Bug Fix: Object is possibly undefined is not accepted with question mark

Original Source Link

Consider the following ocde:

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

The reported error for cacheLocation?: config.cache.cacheLocation as Msal.CacheLocation is:

(property) cache?: CacheOptions | undefined Object is possibly
‘undefined’.ts(2532)

When looking at the msal documentation it says:

export type CacheLocation = "localStorage" | "sessionStorage";

export type CacheOptions = {
    cacheLocation?: CacheLocation;
    storeAuthStateInCookie?: boolean;
};

The question mark in cacheLocation? indicates that this parameter is optional, which is fine. It can or cannot be defined within the JSON file. So I do not understand why TypeScript complains that it can be undefined when that is an accepted value? Of course, the TS null check is in place, but should it not allow this as there is a question mark?

The current workaround for now is below, but I don’t know if that is the correct approach:

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
cacheLocation: config.cache!.cacheLocation as Msal.CacheLocation,

I’m still a beginner, so thank you for your help.

Typescript is trying to tell you that this property access might result in an error:

config.cache.cacheLocation

If either config or config.cache turn out undefined, an exception will be raised.

You can do this:

config?.cache?.cacheLocation

It seems this is the type:

export type Configuration = {
    auth?: BrowserAuthOptions,
    cache?: CacheOptions,
    system?: BrowserSystemOptions
};

Tagged : /

Leave a Reply

Your email address will not be published. Required fields are marked *