简体   繁体   中英

Why does my getter,setter not working in Typescript?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM