Reputation: 724
I have a scenario like this:
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);
Here i am getting a warning in vscode like "private variables are declared but its value is not read". Inorder to prevent this warning, i have to use getter method, but here purpose is to save the object properties and not reading. So getter method seems to be useless. Since i am new to typescript, without setting these variables to public or disabling in tslint configuration, can anybody suggest a better approach for the same?
The purpose is to set the employee info, for that I created Employee model.
Any help would be really appreciated.
Thanks in advance
Upvotes: 1
Views: 297
Reputation: 370589
Since you're not doing anything with the data on this side other than assigning to properties of it, it sounds like you should be creating a plain object instead. Since in your original code, all the methods which set properties are public, and don't do anything else, they don't accomplish anything useful. If an external source can call a setter method, it may as well just assign a property directly. The class
adds unnecessary and confusing overhead, and part of that is why Typescript is complaining. Instead, do something like:
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, a class is generally useful only when you need to have data associated with an instance and methods which retrieve and use the data in some way.
Upvotes: 1