验证构造函数参数和lint错误

时间:2017-11-07 13:53:39

标签: oop typescript tslint

我正在尝试在创建类的实例时验证构造函数参数。

参数应该是一个对象,其中包含完全类中定义的所有属性(足够类型)。

如果不是这种情况,我希望TypeScript能够解决不匹配问题。

array(70) {
  [0]=>
  string(12) "0.3x1245--27"
  [1]=>
  string(13) "0.35x1245--27"
  [2]=>
  string(12) "0.4x1100--27"
  [3]=>
  string(13) "0.45x1245--27"
  [4]=>
  string(12) "0.5x1245--27"

tsconfig.json

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

1 个答案:

答案 0 :(得分:2)

解决方案是声明一个界面:

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