All files readonlyKeywordRule.ts

100% Statements 13/13
100% Branches 11/11
100% Functions 3/3
100% Lines 13/13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 621x 1x 1x 1x                                 1x                 1046x             1046x         189x     69x         120x 20x   100x             926x    
import * as ts from "typescript";
import * as Lint from "tslint";
import * as Ignore from "./shared/ignore";
import {
  InvalidNode,
  createInvalidNode,
  CheckNodeResult,
  createCheckNodeRule
} from "./shared/check-node";
 
type Options = Ignore.IgnoreLocalOption &
  Ignore.IgnorePrefixOption &
  Ignore.IgnoreClassOption &
  Ignore.IgnoreInterfaceOption;
 
/**
 * This rule checks that the readonly keyword is used in all PropertySignature and
 * IndexerSignature nodes (which are the only places that the readonly keyword can exist).
 */
// tslint:disable-next-line:variable-name
export const Rule = createCheckNodeRule(
  Ignore.checkNodeWithIgnore(checkNode),
  "A readonly modifier is required."
);
 
function checkNode(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): CheckNodeResult {
  return { invalidNodes: checkPropertySignatureAndIndexSignature(node, ctx) };
}
 
function checkPropertySignatureAndIndexSignature(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): ReadonlyArray<InvalidNode> {
  if (
    node.kind === ts.SyntaxKind.PropertySignature ||
    node.kind === ts.SyntaxKind.IndexSignature ||
    node.kind === ts.SyntaxKind.PropertyDeclaration
  ) {
    if (
      !(
        node.modifiers &&
        node.modifiers.filter(m => m.kind === ts.SyntaxKind.ReadonlyKeyword)
          .length > 0
      )
    ) {
      // Check if ignore-prefix applies
      if (Ignore.shouldIgnorePrefix(node, ctx.options, ctx.sourceFile)) {
        return [];
      }
      return [
        createInvalidNode(node, [
          new Lint.Replacement(node.getStart(ctx.sourceFile), 0, "readonly ")
        ])
      ];
    }
  }
  return [];
}