Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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?

share|improve this question
    
When I try to initialize the above class I guess you mean "instantiate". – torazaburo Aug 20 at 15:38
up vote 2 down vote accepted

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);
share|improve this answer
    
I could have done that just that I find object initializers more handy. More so when I don't want to put every "set" property in constructor, which in this case I have to. Thanks for the response. – Raj Aug 20 at 15:14
    
To work with object initializer, Student will need to be Interface, but then Student will not be able to contain methods including getters. They've discussed some options here. – Granga Aug 20 at 16:09
    
Thanks Granga, that helps. – Raj Aug 21 at 14:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.