Using TypeScript to Populate a Map with Predicates and Strings from a Map of String to String and String to Predicate

My data structure includes a Map that maps one string to another string:

const strToStr = new Map<string, string>([
    ['foo', 'foo'],
    ['bar', 'qux'],
]);

I also have a different Map where each key is a string and the value is a function that takes a string as input:

const strToFnc = new Map<string, (_: string) => boolean>([
    ['baz', (_: string) => true],
    ['buz', (_: string) => false],
]);

In the third Map, I intend to store these predicate functions according to their respective keys:

const predicates = new Map<string, (_: string) => boolean>();

To assign the functions to the keys in the first set of data (strToStr), I use the following approach:

strToStr.forEach((k) => predicates.set(k, (_) => (k == strToStr.get(k))));

This method works correctly. However, I encounter an issue when attempting to do the same for the second set of data:

strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k)));
temp.ts:11:40 - error TS2345: Argument of type '(_: string) => boolean' is not assignable to parameter of type 'string'.

11 strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k)));
                                          ~

temp.ts:11:56 - error TS2345: Argument of type '(_: string) => boolean' is not assignable to parameter of type 'string'.

11 strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k)));
                                                          ~

Found 2 errors in the same file, starting at: temp.ts:11

I am puzzled by the fact that strToFnc.get('...') returns a predicate function but fails to be added this way. What could be causing this discrepancy?

Answer №1

When using the forEach() method of Map objects, it's important to note that the callback function parameters may not behave as expected. In the type definitions:

interface Map<K, V> {
  forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
}

it is clear that the first parameter of the callback receives the value and the second parameter receives the key.

If you find yourself mistakenly using the value instead of the key, make sure to adjust your code accordingly. For example:

strToStr.forEach((_, k) => predicates.set(k, (_) => (k == strToStr.get(k))));
strToFnc.forEach((_, k) => predicates.set(k, strToFnc.get(k)!);

In cases where you need to operate on both the key and value, there is no need to call get() since both are already available:

strToStr.forEach((v, k) => predicates.set(k, (_) => (k == v)));
strToFnc.forEach((v, k) => predicates.set(k, v));

You can test out the code in this online playground.

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

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

The error message "this.startLoginAnimatioon is not defined as a function" popped up

I've been developing a login system using TypeScript but I keep encountering an error that I can't figure out. Here's the issue in detail: https://i.sstatic.net/PN4N8.png The problem arises when the this.startLoginAnimation() function ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Improving the method to change a string into a string literal in TypeScript

Utilizing a third-party tool that has specified editorStylingMode?: 'outlined' | 'underlined' | 'filled'; I have set the value in my environment.ts file (in Angular) as shown below export const environment = { productio ...

At a specific duration of inactivity on the website, I am automatically redirected to the login page due to session expiration

When I navigate through the URL based on the session, the session will expire if the user is inactive on the site. The issue arises when a user is considered inactive because the session expires after a certain period of inactivity and then redirects to th ...

Angular 2 Validation Customizer

Recently, I created a web API function that takes a username input from a text field and checks if it is already taken. The server response returns Y if the username is available and N if it's not. For validating the username, I implemented a Validat ...

Introducing a variety of services into the system

From my understanding, services must be provided and injected, meaning each service needs to be placed inside the constructor like this: constructor (private a: AService, private B: BService) {} In my scenario, I have multiple services that all follow th ...

Tips for integrating personalized arrow buttons into Alice-Carousel

Currently, I am in the process of creating a carousel component using alice-carousel (https://github.com/maxmarinich/react-alice-carousel/blob/master/README.md), but I am encountering some difficulties when trying to customize the arrows. The code snippet ...

Using TypeScript, one can easily employ a jQuery element within Vue's 'data' option

Is there a way to store a reference of a jQuery element in the Vue 'data' object without causing TypeScript errors? Any suggestions on how to resolve this issue? [EDIT] I managed to work around the TypeScript error by setting a non-existing jQu ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Tips for resolving the unmounted component issue in React hooks

Any suggestions on resolving this issue: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect ...

Make sure to include a property that is indexed when typing

I am currently working on defining a type to represent a list (hash) of HTTP headers. This type is supposed to be a hash that only contains key / string pairs: type TStringStringHash = { [key: string]: string } However, the issue I am facing is that i ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

How to detect changes in Angular 2 using a separate service

Within my AuthService, I store real-time user data and a method for logging in. When the 'Login' button is clicked, the AuthService is called to retrieve updated user data from the server and update the value of 'this.user'. As a resul ...

The type 'Observable<false>' cannot be assigned to the type 'Observable<boolean>'

Our team had been using Knockout.js (v3.5.0) along with its TypeScript definitions without any issues until TypeScript 4.6.2 came along. It seems that the problem goes beyond just the definitions file, possibly due to a change in how TypeScript handles boo ...

What's the best way to implement an NPM package in a Deno application?

I am curious about integrating the NPM package into my Deno application. Can anyone guide me on how to achieve this? ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...