首页 > 解决方案 > 比在打字稿中使用 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 配置中禁用,任何人都可以提出更好的方法吗?

目的是设置员工信息,为此我创建了员工模型。

任何帮助将非常感激。

提前致谢

标签: javascriptnode.jstypescriptclassgetter-setter

解决方案


由于除了分配给它的属性之外,您没有对这一侧的数据做任何事情,听起来您应该创建一个普通对象。由于在您的原始代码中,所有设置属性的方法都是公共的,并且不做任何其他事情,它们不会完成任何有用的事情。如果外部源可以调用 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,一个类通常仅在您需要与实例关联的数据以某种方式检索和使用数据的方法时才有用。


推荐阅读