[英]TypeScript - Issue with Get property in object initializer
我在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不支持它?
要从Student类构造一个对象,您需要使用该类的构造函数。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.