1

data is an array of type Object...

{
    id: 1,
    name: 'test'
},
{
    id: 2,
    name: 'test 2'
}

How can I access element.id when doing a forEach on data? In the below example it doesn't like element.id. It says Property 'id' does not exist on type Object.

// Need to make sure this code completes
data.forEach(element => {
    this.myservice.delete(element.id).subscribe();
});
2
  • What doesn't it like, actual errors are better than vague statements, also what type is data ? Commented Jun 26, 2018 at 16:21
  • @TitianCernicova-Dragomir data is an array of type Object. The error is: Property 'id' does not exist on type Object. Commented Jun 26, 2018 at 16:24

2 Answers 2

1

To type an object whose structure is not fully known or which you want to access in a type unsafe way you should use any.

declare var data: any[];
data.forEach(element => {
    this.myservice.delete(element.id).subscribe();
});

However in this case the structure is known and is pretty simple, I would actually use a proper type:

declare var data: Array<{ id: number, name: string}>;
data.forEach(element => {
    this.myservice.delete(element.id).subscribe();
});
Sign up to request clarification or add additional context in comments.

2 Comments

In my case I can't declare data. It is a response from an observable subscription. So I am inside of an observable using res => res.data. I believe I need to use map, but am unsure of how.
sure you can, just do let data: Array<{ id: number, name: string}> = res.data or (res.data as any[]).forEach(..). How are you creating the observable ? It might be possible to pass in a type argument to the call creating the observable to tell it the type of data. Postin a more complete example will get better answeres
0

Give it a type of any

data.forEach(element => {
    this.myservice.delete((element as any).id).subscribe();
});

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.