2

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?

1
  • When I try to initialize the above class I guess you mean "instantiate". Commented Aug 20, 2016 at 15:38

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Thanks Granga, that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.