user1027620 user1027620 - 1 month ago 16
Javascript Question

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, 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.

Answer Source

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