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

如何在JS/VSCode/TS中声明setter类型?为何类型检查失败?

问题原因与解决方案

你遇到的问题是因为TypeScript(VSCode的类型检查引擎)不认可在setter上直接使用@type注解——@type在这里会被解析为setter函数的返回类型,但setter本身没有返回值,所以这个注解完全无效,类型检查自然不通过。

修正方案一:用@param标注setter参数类型

直接给setter的参数指定类型,这是最直接的方式:

class Person {
    _name = '';
    _age  = 0;
    get name() {
        return this._name;
    }
    /**
     * @param {string} name
     */
    set name(name) {
        this._name = name;
    }
    get age() {
        return this._age;
    }
    /**
     * @param {number | string} age
     */
    set age(age) {
        if (age === 'too old') {
            age = 100000;
        }
        this._age = age;
    }
}

修正方案二:在getter上标注属性完整类型

如果希望统一指定属性的读写类型,可以在对应的getter上用@type标注属性的完整类型,TypeScript会自动推断setter的参数类型与该类型一致:

class Person {
    _name = '';
    _age  = 0;
    /**
     * @type {string}
     */
    get name() {
        return this._name;
    }
    set name(name) {
        this._name = name;
    }
    /**
     * @type {number | string}
     */
    get age() {
        return this._age;
    }
    set age(age) {
        if (age === 'too old') {
            age = 100000;
        }
        this._age = age;
    }
}

两种方案都能让VSCode的类型检查正常工作,根据你的编码习惯选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:06:35