Angular2 object cannot set property of undefined

So I have this little app in Angular2, and I'm trying to define an object. This is the main component.

export class ContactComponent  {
    person: {
    firstname: string;
    lastname: string;
}
constructor(private PeopleService: PeopleService){
}

ngOnInit(){

this.PeopleService.fetchData().subscribe(
    data=> {
        this.person.firstname=data.results[0].name.first;
        console.log(this.person.firstname);
    });
  }
}

Then in the console log I get:

Cannot set property 'firstname' of undefined

I can't figure it out. Thanks.


ANSWERS:


You are just defining the type of person here (the colon stands for type annotations eg:propertyName:Type) :

person: {
    firstname: string;
    lastname: string;
}

You should assign a value first, otherwise, it will be undefined

interface Person = {
    firstname ? : string; // the "?" makes the property optional, 
    lastname ? : string; //  so you can start with an empty object
}
export class ContactComponent {

    person: Person = {}; // initializing with an empty object

    constructor(private PeopleService: PeopleService) {}

    ngOnInit() {

        this.PeopleService.fetchData().subscribe(
            data => {
                this.person.firstname = data.results[0].name.first;
                console.log(this.person.firstname);
            });
    }
}

Create a class and inherit in component. For Example see the below code

       export class Person{

            firstname: string;
            lastname: string;
        }
        export class ContactComponent  {
        person=Person[];
        constructor(private PeopleService: PeopleService){
        }

        ngOnInit(){

        this.PeopleService.fetchData().subscribe(
            data=> {
                this.person.firstname=data.results[0].name.first;
                console.log(this.person.firstname);
            });
          }
        }


 MORE:


 ? Undefined index: HTTPS in /XXX/index.php on line 35 at post
 ? NameError: name 'linec' is not defined
 ? TypeError: arrayal[i] is undefined but it is defined
 ? Creating a Random Number Generator srand and rand undefined
 ? Undefined Variable Name for Class Variable
 ? how to avoid getting error because of undefined in React-Native
 ? Notice: Trying to get property of non-object error
 ? Cannot access matlab function output - variable undefined
 ? Undefined variable: url in PHP
 ? NoMethodError in OrderController#new