1

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

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

1

2 Answers 2

2

You can create an interface to describe your data shape

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');
Sign up to request clarification or add additional context in comments.

Comments

2

Because of the obj that you have created, the keys are inferred by typescript.

There are two ways of solving this:

  1. Give type to the obj
const obj: Record<string, string> = {
 user_name: 'user2',
 user_desc: 'desc 2'
}

---- OR -----

  1. Give type to your function param
function myFunction (key_name : keyof typeof obj) {
 console.log(obj[key_name])
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.