2

I have this:

  public getFriends() : IUser[] {
    let friends: IUser[];
    friends[0].Id = "test";
    friends[0].Email = "asdasd";

    return friends;
  }

Could sound stupid, but why am I getting friends[0] undefined? What am I supposed to do if I don't have a class of type User in this case.

3
  • 1
    Only the type is declared for the field but not initialized. e.g. let friends: IUser[] = []. Commented Aug 20, 2017 at 19:35
  • 1
    you need to push into friends. Commented Aug 20, 2017 at 19:35
  • 1
    At no point are you creating the array, and much less an object in that array. Commented Aug 20, 2017 at 19:38

1 Answer 1

6

In this statement:

let friends: IUser[];

You are declaring friends and its type IUser[], you aren't initializing it yet, so friends's value is undefined at this point.

So, the first step is to initialize it:

let friends: IUser[] = [];

Now it is an array, you have to push some content into it. First you have to create a IUser:

// this is one (likely) way of creating a IUser instance, there may be others
let friend: IUser = {Id: "test", Email: "asdasd"};

And then add it to the array:

friends.push(friend);

So your final code would be:

public getFriends() : IUser[] {
    let friends: IUser[] = [];

    let friend: IUser = {Id: "test", Email: "asdasd"};
    friends.push(friend);

    return friends;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.