1

I am trying to create a Typescript function that returns an object. However, I keep getting the following error:

ERROR in src\app\components\model\model.component.html(3,30): : Property 'heading' does not exist on type '{}'.

My function looks like this:

getTestObject(): { [key: string]: any } {
    let myObj = {};

    myObj = {
        'heading': 'My heading',
        /* Other properties here */
    };

    return myObj;
}

Then I use it in my html file like this: {{ myObj.heading }}. I was reading the answer over here: Typescript property does not exist on type {} and changed the following line:

let myObj = {}; 

changed to:

let myObj = {} as { [key: string]: any };

but I get the same error. What am I doing wrong? Any help would be appreciated, thank you!

o.o
  • 3,563
  • 9
  • 42
  • 71
  • Not sure will it work or not, but try `let myObj: { [key: string]: any } = {};` – P.S. Apr 18 '18 at 12:27
  • 1
    Are u sure myObj is accessible in your template?.. because i see it declared as let inside the function. – Franklin Pious Apr 18 '18 at 12:35
  • why don't you do `myObj.heading = 'My heading'` ? – bugs Apr 18 '18 at 12:36
  • @CommercialSuicide Unfortunately, it didn't work that way either. @FranklinPious I have a variable called `myObj` outside of the function as well which I assign by calling that function. Sorry should have been more clear. – o.o Apr 18 '18 at 12:45

2 Answers2

1

So you need to ensure you are calling the function getTestObject() while your view of your component is loading.

I was able to get this to work with a simpler verison of the getTestObject() function and a class member defined as myObj:any = {}

here my Class below

export class MySampleClass{
    myobj:any={};
    getTestObject(){
        this.myobj = {heading:'My heading'};
        return this.myobj;
    }
    void ngOnInit() {
        this.getTestObject();
    }
} 

And here's my template interpolation

{{ myObj.heading }}
vofili
  • 91
  • 8
  • This worked, I had to forgot to assign a type to `myobj` outside of the function. I only had `myobj = {}`. Thank you very much! – o.o Apr 18 '18 at 12:44
0

I've test your code here and it works.

function getTestObject(): { [key: string]: any } {
  let myObj = {};

  myObj = {
    'heading': 'Works !!'
    /* Other properties here */
  };

  return myObj;
}

let a = getTestObject();
console.log(a.heading);
marojbor
  • 191
  • 10