Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript is giving error when getting object using a variable/constant

I have an object like this:

const obj = {
user_name: 'user2',
user_desc: 'desc 2'
}


Now I’m calling an onclick function that specifies which parameter to get from the object

function myFunction (key_name : string) {
// as my constant is of type object, I can get data from keys as
console.log(obj[key_name])
}

My function is running fine but typescript is giving me an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{}’

How do I go about getting rid of this error?
Thanks

>Solution :

You can create an interface to describe data shapes

interface Obj {
  user_name: string;
  user_desc: string;
}

const obj: Obj = {
  user_name: 'user2',
  user_desc: 'desc 2',
};

function myFunction(key_name: keyof Obj) {
  console.log(obj[key_name]);
}

myFunction('user_name');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading