You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中Getter/Setter不生效?密码长度校验逻辑失效原因排查

问题:给password赋值前的长度检查不生效,原因是什么?

我希望在给password赋值前检查其长度,若值的长度小于3则抛出错误,但实例化时传入长度为2的22却没有任何反应,这是为什么?我定义了Department基类和ITDepartment子类,代码如下:

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赋值,跳过了自己定义的pass setter方法,所以长度检查的逻辑根本没被执行。

解决方法

把构造函数里的this.password = password改成this.pass = password,这样赋值时会触发setter的检查逻辑,当密码长度小于3时就会抛出错误:

修改后的构造函数代码:

constructor(empNum:number,employees:string[],orginizingDate :number,password:number){
    super("IT",empNum,employees)
    this.orginizingDate = orginizingDate
    this.pass = password // 改用setter赋值触发检查
}

这样实例化ITDepartment传入22时,就会触发错误:Error: The password is not safe。

另外,为了避免后续不小心直接给this.password赋值绕过检查,要确保所有对密码的修改都通过pass setter来进行,不要直接操作私有属性。

内容的提问来源于stack exchange,提问作者Sarkhan Hadjibayov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:05:30