0

Iam new in typescript language I tried to iterate the object using typescript. but it's throwing an error how to handle this error.
[typescript] Element implicitly has an 'any' type because type '{ a: string; b: string; c: string; }' has no index signature.

Code

var obj = {
  a: ' a',
  b: 'b ',
  c: ' c '
};

Object.keys(obj).map(k => obj[k] = obj[k].trim());
console.log(obj);
0

2 Answers 2

1

You can try creating an interface for your variable obj, such that TypeScript compiler will know the typings of your keys/properties and values.

interface TheObject {
    [key: string]: string;
}

const obj: TheObject = {
  a: ' a',
  b: 'b ',
  c: ' c '
};

The reason why the following error ([typescript] Element implicitly has an 'any' type because type '{ a: string; b: string; c: string; }' has no index signature.) is showing is because TypeScript is unaware of the index signature since your original obj is not typed, hence it was defined as any, which means it might not be iterable.

Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate object using for in loop like this

for (var key in obj){
    obj[key] = obj[key].trim()
    console.log(obj[key])
}

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.