1
votes

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!

2
Not sure will it work or not, but try let myObj: { [key: string]: any } = {}; - Commercial Suicide
Are u sure myObj is accessible in your template?.. because i see it declared as let inside the function. - Franklin Pious
why don't you do myObj.heading = 'My heading' ? - bugs
@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

2 Answers

1
votes

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 }}
0
votes

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