Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid.

export const theme = {
  headers: {
    h1: {
    },
    h6: {
      color: '#828286'
    },
  },
}
console.info(theme?.headers?.['h6']?.color ?? '#000') //will pass
console.info(theme?.headers?.['h1']?.color ?? '#000') //will fail

Error

Identifier expected.  TS1003

    10 |   const StyledTypography = styled.div`
    11 |     margin: 0;
  > 12 |     color: #000; ${({theme}) => theme?.headers?.[variant]?.color ?? '#000'}
       |                                                ^
    13 |   `
    14 |   return (
    15 |     <StyledTypography as={variant}>

It seems that the optional chaining only applies to the optional [] as a type and not the values inside.

Is there a way to make this optional without resorting to [undefined || someDefaultValue]?

Answer №1

If you want to ensure your theme object is correctly mapped and passes compiler type checking, you can create an interface for it.

interface HeadersMap {
    [key: string]: {
        [key: string]: string
    }
}

interface ThemeObject {
    headers: HeadersMap
}

const customTheme: ThemeObject = {
  headers: {
    h1: {
    },
    h6: {
      color: '#828286'
    },
  },
}
console.info(customTheme?.headers?.['h6']?.color ?? '#000') //this will be valid
console.info(customTheme?.headers?.['h1']?.color ?? '#000') 

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

Clicking on an element- how can I find the nearest element?

Encountering an issue with my next js app where I am attempting to assign a class to an element upon clicking a button. The problem arises when trying to access the next div using the following code snippet: console.log(e.target.closest('.request_quot ...

Determine the presence of a Facebook user by using JavaScript

I am trying to find a method to verify the existence of a Facebook user based on their ID. As far as I understand, there is a Graph API that can provide a Facebook user's profile picture using their ID in this format: I have noticed that if an inval ...

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

Having trouble setting the `variant='dense'` for material-ui Toolbar – it remains at a height of 64px no matter what

Implemented a hello world AppBar/Toolbar with the variant='dense' style. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWo ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...

EventListener cannot be removed

My TypeScript class is structured like this: class MyClass { let canvas: any; constructor(canvas: any) { this.canvas = canvas; this.canvas.requestPointerLock = this.canvas.requestPointerLock; document.exitPointerLock = ...

The functionality of lazy loading and routing in Angular 10 appears to be malfunctioning

I recently attempted to implement routing and lazy loading in Angular 10.1.6, but for some unknown reason, I've encountered issues where the routing and lazy loading of a module simply isn't functioning as expected. Despite referring to the offic ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

To search for specific data in a Mongoose schema by specifying an attribute of type ObjectId

Here are the schemas I am working with: UserLike const UserLikeSchema = Schema({ user: { type: Schema.Types.ObjectId, ref: "User", required: [true, "User is required"], }, game: { type: Schema.Types.ObjectId, ...

Design a customizable overlay with a moveable and size-adjustable layer below it

After working with kineticjs, I successfully created an app that allows images to be draggable and resizable, which is great progress; Now, I am facing a challenge: I want to have an overlay in the center with a block of variable height/width that display ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

Leveraging JavaScript to extract data from a dropdown menu and apply it to a different section

I am working on a project that involves an HTML section where a user can choose a billing term from a drop-down list. I am in the process of writing JavaScript code to capture the selected option value and use it in another part of the webpage. Here is a ...

Encountering a random MS JScript runtime error message after a few alerts

Encountering this issue when clicking the "Ok" button on an alert window. Error message: Unhandled exception at line 1, column 1 in a lengthy URI Error code: 0x800a138f - Microsoft JScript runtime error: Object expected This problem is occurring within ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Trigger the function upon successful completion of Stripe Checkout

I have a requirement in my Nodejs/Express API to execute a series of confirmation code once the checkout process is successfully completed in Stripe by the client. Below is the checkout function responsible for handling the checkout phase: // Checkout con ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...