2016-03-31 12 views
0
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

あなたは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

関連する問題