【问题标题】:TypeScript - Issue with Get property in object initializerTypeScript - 对象初始值设定项中的 Get 属性问题
【发布时间】:2016-12-27 13:50:47
【问题描述】:

我正在使用带有 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 还不支持它?

【问题讨论】:

  • 当我尝试初始化上面的类时我猜你的意思是“实例化”。

标签: angular typescript


【解决方案1】:

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

【讨论】:

  • 我可以这样做只是因为我发现对象初始化器更方便。更何况当我不想将每个“set”属性都放在构造函数中时,在这种情况下我必须这样做。感谢您的回复。
  • 要使用对象初始化器,Student 需要是接口,但是Student 将不能包含包括getter 在内的方法。他们讨论了一些选项here
  • 谢谢格兰加,这有帮助。
猜你喜欢
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2020-09-21
  • 2011-04-08
  • 2021-08-31
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
相关资源
最近更新 更多