The concept of an undefined object without a question mark is frowned upon

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.

Answer №1

Typescript is warning you that accessing this property may lead to an error:

config.cache.cacheLocation

If either config or config.cache are undefined, it will cause an exception.

To handle this, you can use optional chaining like so:

config?.cache?.cacheLocation

This is the type definition for Configuration:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to create an element that changes upon hovering over it?

I am attempting to implement a mechanism similar to this: https://i.sstatic.net/wZctM.png Here is my current approach: $(document).ready(function(){ $('a').bind('mouseenter', function() { var self = $(this); this.iid ...

The instance is referencing the property or method "sendResetMail" during render, but it is not defined

I'm pretty new to Vue and struggling with an error message while trying to get a reset email modal working in my Vue project: The error says that the property or method "sendResetMail" is not defined on the instance but referenced during render. I ...

Pressing a button will display a div element, which will automatically be hidden after 5 seconds

I'm working on an email submission form that displays a confirmation message below the input field when a user submits their email address. The confirmation text should fade out after 5 seconds. Here's the code snippet: <div class="input-gro ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

Showing skeleton placeholders while waiting for the completion of an Array map function in React

I am currently working on a country list component that includes phone codes, country names, and flags. The use of the map() function is causing some delay in loading time. I am looking for a way to determine if the map() function has finished executing or ...

JavaScript redirect following the successful assignment of a session variable through AJAX

I've recently been tackling a project that involves executing a JavaScript redirect to a specific page. This is achieved by establishing a session variable in PHP through an AJAX request, and then confirming that the session has been properly set. Onc ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

What is the best way to transfer login information to the next stage in Angular 4?

I am currently developing a project in Angular 4 and have encountered an issue with passing login information to the next state upon successfully changing states. In AngularJS, we could achieve this using stateParams, but I'm unsure of how to implemen ...

After transitioning to TypeScript, the CRA app is encountering issues loading CSS files compiled by SASS

My React application was originally created using create-react-app and I had been successfully loading scss files with the node-sass package. However, after deciding to switch to TypeScript following the steps outlined in , my css files are no longer being ...

Create a JavaScript function that adds two separate events to an input field

I need assistance with adding two events on an input field: onkeyup and onchange. The goal is to prevent users from entering characters other than numbers, as the field is for zip code entry. Currently, only one event is working - either keypress or onchan ...

show a function written in JavaScript

I’m currently developing an API and looking to demonstrate a JavaScript code example for invoking this API. While writing a test function in JavaScript, I aim to execute and showcase the code for the JavaScript functions. However, my preference is to ha ...

Make sure to tick off the checkboxes when another checkbox is marked

When a specific condition is met, I want my checkboxes to automatically be checked through Javascript code in MVC. @if (str_item != "" && str_checkroles != "" && str_item == str_checkroles) { <script> src = "https://ajax.googl ...

Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this: app.component.ts: import { Component, OnInit } from "@angular/core"; import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from ...

Using JavaScript, locate the previous and next elements in the JSON array of objects based on the given current event ID

Task: To retrieve and display data based on the current event ID from a JSON file: var _getEventById = function(eventId) { var __findEvent = function(event) { return event.id === eventId; }; return _.find(data.meeting ...

What is the best way to extract specific data from a JSON file based on a chosen property using AngularJS and the $http.get method?

I am working with a JSON file that contains color information like this: { "colorsArray":[{ "colorName":"red", "hexValue":"#f00" }, { "colorName":"green", "hexValue":"#0f0" }, { "colorName":"blue", "hexValue":"#00f" }, ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

Dynamic commenting with AJAX and jQuery

I've been working on implementing live comments on my website using AJAX with jQuery alongside PHP and HTML. Despite my best efforts, the code I'm using doesn't seem to be functioning properly. In this code snippet, comments.php is responsib ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...