2017-11-07 10 views
1

クラスのインスタンスを作成するときに、コンストラクタパラメータを検証しようとしています。コンストラクタパラメータとlintエラーの検証

パラメータは、正確にのクラスに定義されているすべてのプロパティ(適切なタイプのもの)を含むオブジェクトである必要があります。

これが当てはまらない場合は、TypeScriptで不一致が発生する可能性があります。

class User { 
    username: string; 
    // more properties 

    constructor(data:object) { 
     // Check if data Obejct exactly all the class properties and they are of the right type; 
     // Set instance properties 
    } 
}; 

// Desired Output 
new User(); // "data parameter missing"; 
new User(45); // "data parameter is not of type object"; 
new User(); // "username Poperty missing!"; 
new User({username:"Michael"}); // Valid; 
new User({username:43}); // "username is not of type string"; 
new User({username:"Michael", favoriteFood: "Pizza"}); // "favoriteFood is not a valid property"; 

{ 
    "compilerOptions": { 
    "target": "es2016", 
    "module": "es2015", 
    "lib": [ 
     "es2016.array.include" 
    ], 
    "downlevelIteration": true, 
    "strict": true 
    } 
} 

答えて

2

tsconfig.jsonソリューションは、インターフェイス宣言されています

interface UserProps { 
    username: string; 
} 

class User implements UserProps { 
    username: string; 
    // more properties 

    constructor (data: UserProps) { 
    // Check if data Obejct exactly all the class properties and they are of the right type; 
    // Set instance properties 
    } 
} 
+0

をそうでしたが、私のIDE(のIntelliJ IDEAは)まだ不一致をlintのはありません。 インターフェイスを使用することは意味があります(特にコンストラクタでの宣言)が、インターフェイスとクラスのプロパティを定義する必要がありますが、これを達成するためのクリーナーはありませんか? –

+0

あなたのプロジェクトにtypescript構文チェッカーが設定されていると思いますか? –

+0

私は 'tsconfiig、json'ファイルを質問に追加しました –