【问题标题】:How to reliably detect TypeScript SyntaxKind in TSLint?如何可靠地检测 TSLint 中的 TypeScript SyntaxKind?
【发布时间】:2019-11-19 14:12:52
【问题描述】:

我正在编写一些自定义 TSLint 规则,发现我不能在 TypeScript 版本之间依赖 (ASTObject).kind

例如,在 TypeScript 中 3.4.5enum ts.SyntaxKind ImportDeclaration = 249ImportClause = 250

但是在 TypeScript 中 3.5.3enum ts.SyntaxKind ImportDeclaration = 250ImportClause = 251

这违反了我的 lint 规则。有没有更好的方法来检测这一点,或者没有使用目标项目中的枚举和/或导致它们未对齐的配置问题?

我找不到相关的文档或其他讨论,所以我不确定它是否被忽视(不太可能)或者我没有正确使用它。

export class Rule extends Rules.AbstractRule {
  public apply(sourceFile: ts.SourceFile): RuleFailure[] {

    for (const statement of sourceFile.statements) {

      // statement.kind / ts.SyntaxKind.ImportDeclaration
      // is 249 in TypeScript 3.4.5, 250 in TypeScript 3.5.3,
      // object property changes for target code, enum stays the same as lint source
      if (statement && statement.kind === ts.SyntaxKind.ImportDeclaration) {
        const importDeclaration: ts.ImportDeclaration = statement as ts.ImportDeclaration;

        // importDeclaration.moduleSpecifier.kind / ts.SyntaxKind.StringLiteral
        // 10 in TypeScript 3.4.5, 10 in TypeScript 3.5.3
        if (importDeclaration.moduleSpecifier && importDeclaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) {
          const moduleSpecifierStringLiteral: ts.StringLiteral = importDeclaration.moduleSpecifier as ts.StringLiteral;
        ...
        }

        // importDeclaration.importClause.kind / ts.SyntaxKind.ImportClause
        // is 250 in TypeScript 3.4.5, 251 in TypeScript 3.5.3
        // object property changes for target code, enum stays the same as lint source
        if (importDeclaration.importClause) {
          if (importDeclaration.importClause.namedBindings) {
            const namedBindings: ts.NamespaceImport | ts.NamedImports = importDeclaration.importClause.namedBindings;
            // namedBindings.kind / ts.SyntaxKind.NamedImports
            // is 252 in TypeScript 3.4.5, 253 in TypeScript 3.5.3
            // object property changes for target code, enum stays the same as lint source
            if (namedBindings && namedBindings.kind === ts.SyntaxKind.NamedImports) {
              const namedImports: ts.NamedImports = namedBindings as ts.NamedImports;
              for (const element of namedImports.elements) {
                const importName: string = element.name.text;
              ...
              }
            }
          }
        }
      ...
      }
    }
  }
}

【问题讨论】:

    标签: typescript enums tslint


    【解决方案1】:

    我想说一个很好的尝试是切换到 typescript 的“is-methods”,例如:

    if (!ts.isImportDeclaration(statement)) {
        return;
    }
    

    希望有所帮助;)

    【讨论】:

    • 我从直接比较 .kind 到使用这些方法,但似乎它们在版本之间也失败了。这似乎是他们会考虑的一个超级奇怪的问题,而我只是还没有找到正确的方法。我可能会求助于爬取对象并在每次出现的基础上处理繁荣。
    猜你喜欢
    • 2015-01-15
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2021-10-09
    • 2015-01-17
    相关资源
    最近更新 更多