TypeScript - 对象初始值设定项中的Get属性问题

时间:2016-08-20 14:41:54

标签: angular typescript

我正在使用带有Angular2的TypeScript,以下是我的类声明 -

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

    constructor() {
    }

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

当我尝试使用以下代码初始化上述类时 -

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

我收到以下错误 -

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

请问我在这里做错了什么,或者TypeScript不支持它?

1 个答案:

答案 0 :(得分:2)

要从Student类构造一个对象,您需要使用类'constructor。

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

console.log(stud1.FullName);

或者甚至更好,让构造函数初始化对象的字段:

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