验证构造函数参数和 lint 错误
Validating constructor parameter and lint error
我试图在创建 class 的实例时验证构造函数参数。
该参数应该是一个包含完全 class.
中定义的所有属性(适当类型)的对象
如果不是这种情况,我希望 TypeScript 对不匹配进行 lint。
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";
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "es2015",
"lib": [
"es2016.array.include"
],
"downlevelIteration": true,
"strict": true
}
}
解决方案是声明一个接口:
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
}
}
我试图在创建 class 的实例时验证构造函数参数。
该参数应该是一个包含完全 class.
中定义的所有属性(适当类型)的对象如果不是这种情况,我希望 TypeScript 对不匹配进行 lint。
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";
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "es2015",
"lib": [
"es2016.array.include"
],
"downlevelIteration": true,
"strict": true
}
}
解决方案是声明一个接口:
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
}
}