如何在不初始化值的情况下使用类变量?

时间:2016-03-31 01:54:54

标签: typescript

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

}

如果我在构造函数方法中删除了初始化默认值代码,则设置行上将出现未定义错误

但初始化代码看起来很难看,我不认为这是正确的方法。

我该怎样做才能让它变得更好?

1 个答案:

答案 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