Utilizing an object's value as a key for a separate object

Here's an overview of my current object structure:

import {
    imageOne,
    imageTwo
} from "./images";

export const imageKeyMap = {
    "one": imageOne,
    "two": imageTwo
}

The definitions for imageOne and imageTwo are as follows

import treeImage from "assets/images/tree.jpg";
import sunImage from "assets/images/sun.jpg"

interface Image {
    alt: string,
    src: any,
}

export const imageOne: Image = {
        alt: '...',
        src: treeImage
}

export const imageTwo: Image = {
        alt: '...',
        src: sunImage
}

My goal is to access the value of imageKeyMap using a key (a string) provided by another object.

interface BarProps {
    key: string,
    headline: string,
    subtitle: string
}

interface FooBarProps {
    image: Image,
    headline: string,
    subtitle: string,
}

someArray.map((element: BarProps) => {
     const {key, headline, subtitle } = element
     return { 
         image: imageKeyMap[key], // <- this is highlighted
         headline: headline,
         subtitle: subtitle
     } as FooBarProps 
})

However, I encounter the following error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: Image; two: Image; }'. No index signature with a parameter of type 'string' was found on type '{ one: Image; two: Image;}'.

Why am I unable to use the provided key to access the values in the imageKeyMap?

Answer №1

The section that is highlighted reads (emphasis added)

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: Image; two: Image; }'. No index signature with a parameter of type 'string' was found on type '{ one: Image; two: Image; }'

Therefore, it is necessary to specify that there is a string indexer available for your imageKeyMap.

There are multiple options (some more type-safe than others), but at the very least, this should suffice:

const imageKeyMap : {[key:string]: Image} = {
    "one": imageOne,
    "two": imageTwo
}

Typescript playground example

Answer №2

When working with the `imageKeyMap` object, it's important to note that the keys are limited to either `"one"` or `"two"`. However, in the context of `BarProps`, the key is expected to be a `string`, which does not align with the specified keys.

To resolve this inconsistency, you have two options: either adjust the key to be one of the keys from `imageKeyMap` using `keyof typeof imageKeyMap`, or update the type of the `imageKeyMap` object to `Record`.

Check out an example here.

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

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...

Unexpected JSON end causes issue with DELETE request in Next.js version 13

I am currently working on a web app using Next 13 and I have a route.ts file located in the api folder. This file contains two different methods, POST and DELETE. While both methods successfully receive the request, I am facing an issue with JSON parsing ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Exploring TypeScript's Conditional Types

Consider this scenario: type TypeMapping = { Boolean: boolean, String: string, Number: number, ArrayOfString: Array<string>, ArrayOfBoolean: Array<boolean> } export interface ElemType { foo: keyof TypeMapping, default: valueof T ...

Passing a React functional component with SVG properties to another component as a prop

My goal is to import a React functionComponent from an SVG and pass it as a prop to another component for rendering the svg. The code below compiles without errors, but crashes when trying to display the svg in the browser with the following message: Er ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

The lib.dom.d.ts file is seriously lacking in many key components

Are there any updated versions of lib.dom.d.ts? The current one is missing a lot of essential information, causing numerous compilation errors. For example, consider this line: window.File && window.FileReader && window.FileList && ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

The Mat-slide-toggle resembles a typical toggle switch, blending the functionalities of

I am facing an issue with a `mat-slide-toggle` on my angular page. Even though I have imported the necessary values in the module, the toggle is displayed as a normal checkbox once the page loads. HTML: <div style="width:100%;overflow:hidden"> < ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

"Using TSOA with TypeScript to return an empty array in the response displayed in Postman

I have successfully implemented CRUD operations using TSOA in TypeScript. However, I am facing an issue where I receive an empty array when making HTTP requests, despite adding data to the 'Livraison' table in MongoDB. https://i.sstatic.net/7IWT ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...

Issue when utilizing TypeScript MongoDB Definitions (Unable to locate namespace)

I am currently working on implementing MongoDB typings that I installed using the following command: npm install @types/mongodb -D Now, I want to utilize these types within a function like this: export default async function insertOne(collection:any, da ...