javascript - 比在打字稿中使用 setter 更好的方法:声明了私有变量但未读取值问题
问题描述
我有这样的场景:
class Employee {
private fullName: string;
private firstName: string;
private lastName: string;
private age: number;
private isValid: boolean;
constructor() {
this.fullName = null;
this.firstName = null;
this.lastName = null;
this.age = null;
this.isValid = false;
}
setfullName(fullName: string) {
this.fullName = fullName;
}
setfirstName(firstName: string) {
this.firstName = firstName;
}
setlastName(lastName: string) {
this.lastName = lastName;
}
setAge(age: number) {
this.age = age;
}
setValid(isValid: boolean) {
this.isValid = isValid;
}
}
// test.ts file
let employee = new Employee();
// set in different positions in test.ts file based on getting the input paramters
employee.setfullName("james cooper");
employee.setfirstName("mary");
employee.setlastName("fransis"); // getting lastName from another api call
employee.setAge(50); // getting 50 from another api call
employee.setValid(true);
在这里,我在 vscode 中收到警告,例如“已声明私有变量但未读取其值”。为了防止这个警告,我必须使用 getter 方法,但这里的目的是保存对象属性而不是读取。所以getter方法似乎没用。由于我是打字稿的新手,没有将这些变量设置为公共或在 tslint 配置中禁用,任何人都可以提出更好的方法吗?
目的是设置员工信息,为此我创建了员工模型。
任何帮助将非常感激。
提前致谢
解决方案
由于除了分配给它的属性之外,您没有对这一侧的数据做任何事情,听起来您应该创建一个普通对象。由于在您的原始代码中,所有设置属性的方法都是公共的,并且不做任何其他事情,它们不会完成任何有用的事情。如果外部源可以调用 setter 方法,它也可以直接分配一个属性。这class
增加了不必要和令人困惑的开销,部分原因是 Typescript 抱怨的原因。相反,请执行以下操作:
type Employee = Partial<{
fullName: string;
firstName: string;
lastName: string;
age: number;
isValid: boolean;
}>;
const employee: Employee = {};
employee.age = 15;
employee.isValid = false;
// send employee to front-end
IMO,一个类通常仅在您需要与实例关联的数据和以某种方式检索和使用数据的方法时才有用。
推荐阅读
- javascript - Cypress cy.tick() 第二次调用时不转发时间
- kivy - cv2.Videocapture 几秒钟后关闭
- chainlink - 无法启动节点
- c - 得到前 50 个奇数的总和不是 5 的倍数?
- python - Python跳过多行字符串的第一行
- go - Golang 工作池 - 从作业中排队新作业
- flutter - 脚本 'C:\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' 行:1035
- grpc - '--grpc_out' 不是内部或外部命令、可运行程序或批处理文件
- flutter - (TiledWorldMap)错误:需要一个“双精度”类型的值,但得到一个“字符串”类型的值
- vue.js - 如何获取调用函数的组件?