Raj
Raj

Reputation: 125

TypeScript - Issue with Get property in object initializer

I am using TypeScript with Angular2, following is my class declaration -

export /**
 * Stress
 */
class Student {
    FirstName: string;
    LastName: string;

    constructor() {
    }

    get FullName() : string {
        return this.FirstName + this.LastName;
    }
}

When I try to initialize the above class using following code -

var stud1: Student = { FirstName:"John", LastName:"Troy" }

I am getting the following error -

Type '{ FirstName: string; LastName: string; }' is not assignable to type 'Student'.
Property 'FullName' is missing in type '{ FirstName: string; LastName: string; }'.

Any help please what I am doing wrong here, or it is not supported yet by TypeScript?

Upvotes: 2

Views: 1013

Answers (1)

Granga
Granga

Reputation: 1662

To construct an object from your Student class you need to use the class' constructor.

var stud1 = new Student();
stud1.FirstName = "John";
stud1.LastName = "Troy";

console.log(stud1.FullName);

Or even better, let the constructor initialize object's fields:

class Student {
    FirstName: string; //this is public, unless you specify private
    LastName: string;

    constructor(firstName: string, lastName: string){
        this.FirstName = firstName;
        this.LastName = lastName;
    }

    //your FullName getter comes here
}

var stud1 = new Student("John", "Troy");
console.log(stud1.FullName);

Upvotes: 2

Related Questions