javascript - TypeScript Interface Undefined -


i have this:

  public getfriends() : iuser[] {     let friends: iuser[];     friends[0].id = "test";     friends[0].email = "asdasd";      return friends;   } 

could sound stupid, why getting friends[0] undefined? supposed if don't have class of type user in case.

in statement:

let friends: iuser[]; 

you declaring friends , type iuser[], aren't initializing yet, friends's value undefined @ point.

so, first step initialize it:

let friends: iuser[] = []; 

now is array, have push content it. first have create iuser:

// 1 (likely) way of creating iuser instance, there may others let friend: iuser = {id: "test", email: "asdasd"}; 

and add array:

friends.push(friend); 

so final code be:

public getfriends() : iuser[] {     let friends: iuser[] = [];      let friend: iuser = {id: "test", email: "asdasd"};     friends.push(friend);      return friends; } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -