typescript 使用setter作为属性时获得警告

tsm1rwdh  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(107)

我正在做一个有Angular 的项目,我们经常使用这种“模式”

public _value;
@Input() public set value(value) {
    this._value = value;
}

它在项目中很普遍,而且有它的用途,所以我们想保留它。问题是,经常发生的是,使用的值没有下划线,这样它就指向setter(返回undefined而不给出任何错误或警告),导致意外的结果和令人沮丧的调试。就像这样

if(this.value) {
    //Never enters here because this.value returns undefined
}

是否有eslint规则或tsconfig设置在“阅读”setter时显示警告?
为什么访问Typescript中缺少的getter会返回'undefined'而不是导致编译错误?所以我想还没有通过 typescript 支持这个,我试着用谷歌搜索一些eslint设置,但我发现没有什么有用的。

zf9nrax1

zf9nrax11#

没有eslint规则为我的情况,所以我决定使我自己的。它与“accessor-pair”远不相似,它们涉及两个不相关的问题,所以我从头开始写我的(也许我唯一可以复制的是如何找到getter和setter并在objectliterals上使用它)。在某些情况下可能会中断(我认为文件有两个类),但在今天之前,我甚至不知道如何编写ESlint规则,我会随着时间的推移改进它,但欢迎提出建议。
我分享的代码“是”,没有测试,到目前为止,它似乎工作(它发现2 setter用作属性,我错过了)

let setters = [];
// @ts-check
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
    meta: {
        type: 'problem',
        hasSuggestions: true,
        fixable: false,
    },
    create: (context) => {
        return {
            ClassBody(node) {
                if(setters) {
                    setters = [];
                }

                const getters = node.body.filter((n) => n.type === 'MethodDefinition' && n.kind === 'get').map((n) => n["key"].name);
                setters.push(...node.body.filter((n) => n.type === 'MethodDefinition' && n.kind === 'set' && !getters.includes(n["key"].name)).map((n) => n["key"].name));
                
                return null;
            },
            MemberExpression(node) {
                if (node.parent.type !== 'AssignmentExpression') {
                    if (setters.includes(node.property["name"])) {
                        context.report({
                            node,
                            message: 'Found setter used as property',
                        });
                    }
                }

                return null;
            },
        };
    },
};

相关问题