[英]Checking the AST for @Injectable decorator for TSLint custom rule
I am trying to design a custom TSLint
rule that will allow for me to check and make sure that the @Injectable
decorator is not included within classes that do not inject any other services into themselves via the constructor. 我正在尝试设计一个自定义
TSLint
规则,该规则将允许我检查并确保@Injectable
装饰器未包含在不会通过构造函数向自身注入任何其他服务的类中。
I have been reading this documentation and have been able to write a rule previously to disallow export
modifiers in test files by doing: 我一直在阅读此文档,并且以前能够通过以下操作编写规则以禁止在测试文件中
export
修饰符:
const hasExport = node.modifiers && node.modifiers.some(
(modifier) => modifier.kind === SyntaxKind.ExportKeyword
);
This AST explorer website has been helpful throughout this process but I am having trouble deciding the best way to figure out if the @Injectable
decorator is being added to my node. 这个AST资源管理器网站在此过程中一直很有帮助,但是我无法确定确定
@Injectable
装饰器是否已添加到我的节点的最佳方法。
So far I have: 到目前为止,我有:
const hasInjectableDecorator = node.decorators && node.decorators.some(
(decorator) => decorator.kind === SyntaxKind.Decorator
);
But this will only check to see if it is of any decorator (@Injectable, @Component, @NgModule, etc.) and I was wondering how I could then check the text, using the available properties/methods on decorator
to make sure it is indeed an @Injectable
. 但这只会检查它是否是任何装饰器(@ Injectable,@ Component,@ NgModule等),我想知道如何使用
decorator
上的可用属性/方法来检查文本,以确保它是确实是@Injectable
。 I would like to start with this first and then dive into ensuring no other services are being injected. 我首先要开始,然后再深入研究以确保没有其他服务被注入。
Thanks 谢谢
+1 for astexplorer.net! 为astexplorer.net +1! Great website.
很棒的网站。
import * as ts from "typescript"; 从“打字稿”中将*作为ts导入;
const hasInjectableDecorator = (node: ts.ClassDeclaration) => node.decorators
&& node.decorators.some(isInjectableDecorator);
const isInjectableDecorator = (decorator: ts.Decorator) => ts.isIdentifier(decorator.expression)
&& decorator.expression.text === "Injectable"
Explanation: you want to check whether the decorator's expression
has a text value of "Injectable"
, right? 说明:您想检查装饰器的
expression
是否具有文本值"Injectable"
,对吗? This method will check if the decorator is an Identifier (it refers to a variable), and if so, checks what text name it uses. 此方法将检查装饰器是否为标识符(它引用变量),如果是,则检查其使用的文本名称。
Fun fact: instead of checking node.kind === ts.SyntaxKind.Decorator
, you should use the built-in ts.isDecorator
method (and its equivalents for other node syntax kinds) . 有趣的事实:您应该使用内置的
ts.isDecorator
方法(以及其他节点语法类型的等效方法),而不是检查node.kind === ts.SyntaxKind.Decorator
。 They directly check .kind
the same way and also return node is ts.Decorator
, so you'll get type inference without having to manually cast node as ts.Decorator
later on. 他们以相同的方式直接检查
.kind
,并且返回的node is ts.Decorator
,因此您将获得类型推断,而无需稍后手动将node as ts.Decorator
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.