Home > OS >  Why does my getter,setter not working in Typescript?
Why does my getter,setter not working in Typescript?

Time:11-15

I want to check my password`s length before assigning value to the password. If value's length is less than 3 it has to throw an error. But it is not returning anything. Why?

I have a Department class and ITDepartment subclass.

class Department {
    static currentYear = 2022
    departmentName:string
    empNum:number
    employees :string[] = []
    constructor(public name:string,nums:number, 
        employees:string[]){
        this.departmentName =name
        this.empNum = nums
        this.employees = employees
    }


}

class ITDepartment extends Department {
orginizingDate : number
 private password :number

 public get pass (){
    return this.password
 }


 public set pass (value:number){
    if(value.toString().length < 3){
        throw new Error ('The password is not safe ')
    }
     this.password = value
 }

constructor(empNum:number,employees:string[],orginizingDate :number,password:number){
    super("IT",empNum,employees)
    this.orginizingDate = orginizingDate
    this.password = password
}
printInfo(){
    console.log("The Department "   this.departmentName   " has "   this.empNum  " employers and orginized in "  this.orginizingDate)
}

addEmployee(employee: string): void {
    if(employee === "Adam"){
        return
    }
    this.employees.push(employee)
}
}   

let it = new ITDepartment(52,[],2000,22)

CodePudding user response:

this.password = password won't go through the setter named pass. Furthermore, you aren't actually comparing the length, but the value itself.

  • Related