0
votes

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);
2

2 Answers

1
votes

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.

0
votes

You can iterate object using for in loop like this

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