比在打字稿中使用setter更好的方法:声明了私有变量,但值未读问题

问题描述 投票:0回答:1

我有这样的情况:

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方法似乎毫无用处。由于我是TypeScript的新手,因此无需将这些变量设置为public或在tslint配置中禁用,是否有人可以建议采用更好的方法呢?

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

任何帮助将不胜感激。

提前感谢

javascript node.js typescript class getter-setter
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.