3

I run into a strange behavior in my angular app today.

ERROR in src/main(A,B): error TS2339: Property 'XXX' does not exist on type '{}'.

The error occured at the following line of code

xxx.subscribe(data => {
    this.var = data.XXX
});

So basically i subscribe to an observable and map the data from the observable to an global var. My angular App works as intended, so this error seems to have no effect on the app itself, but I still can't figure out whats wrong here. Below is the console log of data:

console.log(data)
//{"XXX": "test"}
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
sHamann
  • 789
  • 3
  • 10
  • 36
  • what if you use `data['XXX']` instead ? type `{}` does not hold `XXX` attribute, that's why. – Florian Jul 17 '18 at 08:59
  • Possible duplicate of [Property '\_body' does not exist on type 'Response'](https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response) – koninos Dec 14 '18 at 13:06

2 Answers2

6

Typescript complains that you do not have the property inside the data, you can either use any or create an inteface with that property,

xxx.subscribe((data:any) => {...}
Jack
  • 1
  • 21
  • 118
  • 236
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2

You have instantiated data as just an object example : data = {}. As object doesn't have XXX property it gives this error. So solution will be data: {XXX: string, YYY: number ....} = {}

Else you can access XXX with data['XXX'] which is the easiest option

Malindu Sandaruwan
  • 1,477
  • 2
  • 13
  • 27
  • 1
    `data['XXX']`should be the answer here. There is no need to interface, model, or specific type. There is absolutely no benefit to use such things for a simple object. Maybe rename `data` to a more specific data type if needed. – Florian Jul 17 '18 at 09:07
  • Yes you can achieve the required behavior in that way. But as a best practice better to use Interface kind of things. Else you will rarely get the real benefits of Typescript. – Malindu Sandaruwan Jul 17 '18 at 09:10
  • As best practise, do not return a data object type with one attribute in first place. returns the attribute directly. – Florian Jul 17 '18 at 09:11