Mapping values of 2 objects in TypeScript through an interface

I am currently working with two objects, objA and objB.

There is a function that I have, which takes a value from objB and a key from objA as arguments.

const objA = {
  a:"a",
  b:"b"
}
const objB = {
  a:"a",
  b:"b"
}
checkValues = (type:string,key:keyof typeof objA)=>{
 return  objA[key] === type;
}

checkValues("A",objA.a)

However, I am encountering a type error message stating:

Argument of type 'string' is not assignable to parameter of type '"a" | "b"'

Answer №1

By defining your function in this way, it can only check the object's entries (so 'a' or 'b'), rather than calling the function with objA.a, which refers to the value of the property a on the object.

To address this, you can:

// Call the function and pass only 'a' or 'b'
checkValues("A", 'a');
checkValues("A", 'b');
// Declare object properties with specific types using interfaces:
interface MyObj {
    a: 'a' | 'b';
    b: 'a' | 'b';
}

const objA: MyObj = {
  a:"a",
  b:"b"
}
const objB: MyObj = {
  a:"a",
  b:"b"
}

Since your requirements were not clearly defined, this is a suggestion that might be helpful. I hope it assists you!

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

Passing a global variable as an argument to a jQuery function is not allowed

I am attempting to display local weather information using an API. The API URL is generated based on the user's current position. var lat, lon = null; var key = "mykey"; var api = ""; function setApi(position){ lat = Math.round(position.coords.lati ...

What is the best way to modify a large portion of JSON data in a nodejs environment?

I am currently working with two separate JSON files - data.json and dataForUpdate.json The contents of data.json are as follows: [{"name": "test", "isDefault": true, "settings": { "type": "Separation", "scanner": { "brightness": 0 ...

Efficiently Embedding Images into Canvas Elements

I am struggling with loading individual photos from an array into "canvas" tags. In my function, I generate multiple sets of "div" tags with a "canvas" tag inside them, but I'm facing difficulties in inserting images from an array into these "canvas" ...

Indeed, verification of an array - values are mandatory only when the array exceeds a length of 1

In my form, each row contains 2 dropdowns and I have the ability to dynamically add or remove rows except for the first one. My goal is to allow form submission only if there is one pre-rendered empty row, otherwise the form should not be able to submit if ...

Search a database for a specific set of ObjectID using Mongoose

I'm currently developing an API using node.js, express, and mongoose. As I am still new to mongosse, I have been exploring different approaches to achieve what I need. In my database, I have two collections: users and expenses. Here's an exampl ...

"Chrome experiences issues with onmouseover functionality when navigating away from a page or posting content

I'm experiencing an issue with a page where I have onmouseover and onmouseout attributes set for pictures. When submitting, the onmouseover and onmouseout events cause the images to fail, resulting in the image source not found icon being displayed. ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...

Navigating the Spine

Struggling to get routing to function properly in Backbone, I have tried my best but it still seems quite confusing. Here is a snippet of what I currently have: routes: { '' : 'home', 'home' ...

Creating an HTML list based on the content of a textarea input

Looking for some guidance in creating a dynamic list using JavaScript. The goal is to have user input data into a textarea, and upon clicking the submit button, generate a list in HTML. HTML: <body> <div class="container"> <di ...

The operation of fetching multiple documents within a transaction loop is not functioning as anticipated

I am encountering an issue where I am attempting to retrieve multiple documents within a transaction and then update them all in the same transaction (due to their interdependence). Despite following the rule of ensuring all reads occur before any writes, ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

Refine current attributes of an object in Typescript

In typescript, I have an object of type any that needs to be reshaped to align with a specific interface. I am looking for a solution to create a new object that removes any properties not defined in the interface and adds any missing properties. An exam ...

Debug in Webstorm 7.0.3 by smoothly switching out Node.js files

Recently, I've embarked on a journey with Node.js and Webstorm 7.0.3. After creating a basic Node.js app using express and running it locally, I encountered an issue: I couldn't seem to make changes in a .js file, save it, refresh the browser, an ...

How do I attach an event listener to a select box that is created dynamically using JavaScript?

I'm new to web development and I'm currently working on a project where I need to create a select box dynamically within a div that is also created dynamically when the page loads. However, I'm facing an issue with adding an onchange Event L ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

What is preventing me from returning the result of $.ajax, but I can return the result of $http.post?

I am facing an issue with having 2 return statements in my code: return $http.post({ url: CHEAPWATCHER.config.domain + 'api/Authenticate', contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: data }); re ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Issue with Google Maps API v3 failing to load map consistently after frequent use of the setCenter

It's finally my turn to contribute after years of lurking in this amazing community. I have a project where I am using the Google Maps API v3 to display nearby emergency services on a television connected to a Raspberry Pi in a pharmacy. To achieve th ...

Difficulty with making HTTP Requests in Node.js

It's like I'm stuck in a maze trying to find my way out. I could use some guidance on unraveling the mystery behind the appearance of "[object Object]" and understanding the error message. Any assistance in steering me towards the correct path w ...