What is the method for retrieving keys from an object that contain hyphens within them?

Presented here is an object:

{
    "type": "fill",
    "id": "asdf",
    "paint": {
        "fill-color": "#440d0d"
    }
}

I am aiming to retrieve the fill-color property. My attempted method is as follows:

if (mapStyle["paint"]){
    const fillColor = mapStyle['paint']["fill-color"]
}

However, I encounter this error:

Element implicitly has an 'any' type because expression of type '"fill-color"' can't be used to index type '{ "fill-antialias"?: PropertyValueSpecification<boolean> | undefined; "fill-opacity"?: DataDrivenPropertyValueSpecification<number> | undefined; ... 4 more ...; "fill-pattern"?: DataDrivenPropertyValueSpecification<...> | undefined; } | ... 7 more ... | { ...; }'.
  Property 'fill-color' does not exist on type '{ "fill-antialias"?: PropertyValueSpecification<boolean> | undefined; "fill-opacity"?: DataDrivenPropertyValueSpecification<number> | undefined; ... 4 more ...; "fill-pattern"?: DataDrivenPropertyValueSpecification<...> | undefined; } | ... 7 more ... | { ...; }'.ts(7053)
(property) "paint"?: {
    "fill-antialias"?: PropertyValueSpecification<boolean> | undefined;
    "fill-opacity"?: DataDrivenPropertyValueSpecification<number> | undefined;
    ... 4 more ...;
    "fill-pattern"?: DataDrivenPropertyValueSpecification<...> | undefined;
} | ... 8 more ... | undefined

What could be causing this issue? I find the error message rather confusing. Thank you for your assistance!

Answer №1

To address the issue of implicitly setting the type to 'any' for the constant fillColor, I suggest defining a specific type for it. When looking at the error message, it indicates that there is an ambiguity in the type being used.

if (mapStyle["paint"]){
    const fillColor: string = mapStyle['paint']["fill-color"];
}

Alternatively, you can specify the type explicitly using a type assertion like this:

if (mapStyle["paint"]){
    const fillColor = mapStyle['paint']["fill-color"] as string;
}

Answer №2

After some investigation, I managed to identify the accurate types:

import {
  CircleLayerSpecification,
  FillLayerSpecification,
  LayerSpecification,
  LineLayerSpecification,
  RasterLayerSpecification,
} from 'mapbox-gl'

Finally, everything is properly typed...

Apologies for my previous silly question! ;)

Answer №3

Method 1: Setting constant for string definition

if (mapStyle["paint"]){
    const fillColor: string = mapStyle['paint']["fill-color"];
}

Method 2: Utilizing Casting

if (mapStyle["paint"]){
    const fillColor = mapStyle['paint']["fill-color"] as string;
}

Method 3: Introducing Typing (preferred approach) Implement an interface to specify the element. This is a reliable way to steer clear of using any data type consistently.

export interface YourModel{
    type?: string;
    id?: string,
    paint?: YourChildModel;
}

export interface YourChildModel{
    "fill-color"?: string;
}

Next

const mapStyle:YourModel = methodToRecoverValues();

[...]

if (mapStyle.paint){
    const fillColor = mapStyle['paint']["fill-color"];
}

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

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Updating React state dynamically with a stringUsing a dynamic string

Is it possible to dynamically set an existing state field in a React component? I've attempted the following approach, but I'm encountering issues with TypeScript: export interface MaskCompanyDetailState { fieldId: number; } export class M ...

A guide on leveraging typeof within function parameters to ensure accurate variances

Let's create a simple class hierarchy and a list of instances. The goal is to filter items from the list of instances based on their class. There are a couple of challenges: We cannot use the typeof T syntax. How can this be written? We cannot decla ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

Leveraging string interpolation in Typescript with a string sourced from a file

After diving into Typescript, I came across some intriguing information on template strings. One question that popped into my mind is whether these template strings can be utilized when reading a string from a file, just like this: let xmlPayloadTemplate ...

The Angular Component utilizes the ng-template provided by its child component

I am currently facing an issue that involves the following code snippet in my HTML file: <form-section> <p>Hello</p> <form-section> <ng-template test-template> TEST </ng-template> ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

Thorough exploration of a collection of varied, categorized items

My goal is to have TypeScript ensure that all cases are covered when mapping over a union like this: type Union = { type: 'A', a: string } | { type: 'B', b: number } The handler for the Union: const handle = (u: Union): string = ...

Guide to making a custom type by extending a union type in TypeScript

Looking to define a new structure here type DataTableCol<T, K extends keyof T> = { title: string; key: K; render?: (value: T[K]) => ReactElement; }; In need of creating a type called DataTableRow<T> based on the above. For instance, w ...

Is the communication between Angular service and component failing when using ngFor?

I am currently using Angular to create a video game page. When a specific title is clicked, the id is sent to make an API call with that specific id. I am able to retrieve the data in the selected-games component where I intend to use it, but when I use ng ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

Customizable mongoDB database collection

Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case. Currently, I have this code and the goal is to have a u ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Angular: What is the best way to pass usersearch-input data to a different component and use it to generate a list of search results?

Seeking assistance as a beginner in Angular, I am currently working on my first project with Angular 8 for the frontend of an application. The challenge I faced was creating an HTML page (...stuff/searches) where users can input search criteria to find sp ...

Prohibit communication by any means

Let's take a look at the following function overloads: function f(key: undefined); function f(key: string | undefined, value: object | undefined); I want to allow calls with a single explicit undefined argument f(undefined), but require two argument ...

Issue encountered with express-jwt and express-graphql: TypeScript error TS2339 - The 'user' property is not found on the 'Request' type

Implementing express-jwt and graphql together in typescript has been a challenge for me. import * as express from 'express' import * as expressGraphql from 'express-graphql' import * as expressJwt from 'express-jwt' import s ...

The entity known as Sentry has not been specified

After following a tutorial by JSMastery, I successfully created a portfolio website using Next.js. We also integrated Sentry into our app to allow users to report bugs. Everything was working perfectly fine on my local machine and even after deploying it o ...

Can we stop Angular components from being destroyed during navigation?

Consider the scenario where I have two distinct Angular 2 components known as ComponentA and ComponentB. My goal is to navigate from ComponentA to ComponentB and then return to ComponentA without needing to reinitialize it. In the current setup of Angular ...