0

I've created a "load" function that will take a JSON format of data and load the attributes into properties of my class. I'm trying to use typescript for the first time and have managed to fix most errors, however there are some I can't work out.

load(id): void{
  let item:object = this.items.find(item => item.id == id);
  if(typeof(item) != 'undefined'){
    for(let k in item){
      if(item.hasOwnProperty(k)){
        this[k] = item[k];
      }
    }
  }
}

This gives the following error:

    Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
    No index signature with a parameter of type 'string' was found on type '{}'.
    386 |       for(let k in item){
    387 |           if(item.hasOwnProperty(k)){
  > 388 |               this[k] = item[k];
        |                         ^
    389 |           }
    390 |       }
    391 |       }

How would I go about fixing this? Is the issue with the pattern that I am using, or can I just declare the types differently to stop the error showing up?

1 Answer 1

1

type object (confusingly, I'll admit), has no index signature meaning you can't read or write value to it with the brackets accessor [].

You can work around this by declaring let item:any but that will turn off any type checking.

Or something like this let item: {[propName: string]: any} which is not much better.

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

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.