Как надежно определить TypeScript SyntaxKind в TSLint? - PullRequest
0 голосов
/ 01 ноября 2019

Я пишу некоторые пользовательские правила TSLint и обнаружил, что не могу положиться на (ASTObject).kind между версиями TypeScript.

Например, в TypeScript 3.4.5, enum ts.SyntaxKind ImportDeclaration = 249 и ImportClause = 250.

Однако в TypeScript 3.5.3, enum ts.SyntaxKind ImportDeclaration = 250 и ImportClause = 251.

Это нарушило мои правила ворса. Есть ли лучший способ обнаружить это или проблему конфигурации, которая не использует перечисление из целевого проекта и / или приводит к смещению их?

Я не смог найти документацию или другие обсуждения по этому поводу, поэтому яЯ не уверен, что он остался незамеченным (маловероятным) или я не правильно его использую.

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;
              ...
              }
            }
          }
        }
      ...
      }
    }
  }
}
...