class testClass
{
student: {
name: string,
age: number
}
constructor(options?: any) {
// initialize default values
this.student = {
name='',
age=0
};
}
setStudent(name:string, age:number) {
this.student.name = name; //
this.studetn.age = age;
}
}
如果我在构造函数方法中删除了初始化默认值代码,则设置行上将出现未定义错误。
但初始化代码看起来很难看,我不认为这是正确的方法。
我该怎样做才能让它变得更好?
答案 0 :(得分:1)
您可以在declaration
:
class TestClass {
student: {
name: string,
age: number
} = {
name: '',
age: 0
}
constructor(options?: any) {
}
setStudent(name: string, age: number) {
this.student.name = name;
this.student.age = age;
}
}
事实上,您甚至不需要提供类型注释,因为它可以推断出来:
class TestClass {
student = {
name: '',
age: 0
}
constructor(options?: any) {
}
setStudent(name: string, age: number) {
this.student.name = name;
this.student.age = age;
}
}
此处介绍:https://basarat.gitbooks.io/typescript/content/docs/classes.html