All files readonlyArrayRule.ts

97.06% Statements 33/34
97.87% Branches 46/47
100% Functions 5/5
97.06% Lines 33/34
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 1701x 1x 1x 1x                         1x                 1795x                           1795x 35x             35x           1x     34x 9x     25x                     1760x               1795x       118x       15x     103x 9x     94x           1677x             1795x           164x     164x 8x   156x 58x       21x 21x 21x                         21x                       1766x       33x                            
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.IgnoreRestParametersOption &
  Ignore.IgnoreReturnType;
 
// tslint:disable-next-line:variable-name
export const Rule = createCheckNodeRule(
  Ignore.checkNodeWithIgnore(checkNode),
  "Only ReadonlyArray allowed."
);
 
function checkNode(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): CheckNodeResult {
  return {
    invalidNodes: [
      ...checkArrayType(node, ctx),
      ...checkTypeReference(node, ctx),
      ...checkVariableOrParameterImplicitType(node, ctx)
    ]
  };
}
 
function checkArrayType(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): ReadonlyArray<InvalidNode> {
  // We need to check both shorthand syntax "number[]"...
  if (node.kind === ts.SyntaxKind.ArrayType) {
    Iif (
      node.parent &&
      Ignore.shouldIgnorePrefix(node.parent, ctx.options, ctx.sourceFile)
    ) {
      return [];
    }
 
    if (
      ctx.options.ignoreRestParameters &&
      node.parent &&
      node.parent.kind === ts.SyntaxKind.Parameter &&
      (node.parent as ts.ParameterDeclaration).dotDotDotToken
    ) {
      return [];
    }
 
    if (ctx.options.ignoreReturnType && checkIsReturnType(node)) {
      return [];
    }
 
    return [
      createInvalidNode(node, [
        new Lint.Replacement(
          node.getStart(ctx.sourceFile),
          0,
          "ReadonlyArray<"
        ),
        new Lint.Replacement(node.end - 2, 2, ">")
      ])
    ];
  }
  return [];
}
 
function checkTypeReference(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): ReadonlyArray<InvalidNode> {
  // ...and type reference "Array<number>"
  if (
    node.kind === ts.SyntaxKind.TypeReference &&
    (node as ts.TypeReferenceNode).typeName.getText(ctx.sourceFile) === "Array"
  ) {
    if (
      node.parent &&
      Ignore.shouldIgnorePrefix(node.parent, ctx.options, ctx.sourceFile)
    ) {
      return [];
    }
 
    if (ctx.options.ignoreReturnType && checkIsReturnType(node)) {
      return [];
    }
 
    return [
      createInvalidNode(node, [
        new Lint.Replacement(node.getStart(ctx.sourceFile), 0, "Readonly")
      ])
    ];
  }
  return [];
}
 
function checkVariableOrParameterImplicitType(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>
): ReadonlyArray<InvalidNode> {
  if (
    node.kind === ts.SyntaxKind.VariableDeclaration ||
    node.kind === ts.SyntaxKind.Parameter ||
    node.kind === ts.SyntaxKind.PropertyDeclaration
  ) {
    // The initializer is used to set and implicit type
    const varOrParamNode = node as
      | ts.VariableDeclaration
      | ts.ParameterDeclaration;
    if (Ignore.shouldIgnorePrefix(node, ctx.options, ctx.sourceFile)) {
      return [];
    }
    if (!varOrParamNode.type) {
      if (
        varOrParamNode.initializer &&
        varOrParamNode.initializer.kind === ts.SyntaxKind.ArrayLiteralExpression
      ) {
        const length = varOrParamNode.name.getWidth(ctx.sourceFile);
        const nameText = varOrParamNode.name.getText(ctx.sourceFile);
        let typeArgument = "any";
        // Not sure it is a good idea to guess what the element types are...
        // const arrayLiteralNode = varOrParamNode.initializer as ts.ArrayLiteralExpression;
        // if (arrayLiteralNode.elements.length > 0) {
        //   const element = arrayLiteralNode.elements[0];
        //   if (element.kind === ts.SyntaxKind.NumericLiteral) {
        //     typeArgument = "number";
        //   } else if (element.kind === ts.SyntaxKind.StringLiteral) {
        //     typeArgument = "string";
        //   } else if (element.kind === ts.SyntaxKind.TrueKeyword || element.kind === ts.SyntaxKind.FalseKeyword) {
        //     typeArgument = "boolean";
        //   }
        // }
        return [
          createInvalidNode(varOrParamNode.name, [
            new Lint.Replacement(
              varOrParamNode.name.end - length,
              length,
              `${nameText}: ReadonlyArray<${typeArgument}>`
            )
          ])
        ];
      }
    }
  }
  return [];
}
 
function checkIsReturnType(node: ts.Node): boolean {
  return Boolean(
    node.parent !== undefined &&
      (node.parent.kind === ts.SyntaxKind.FunctionDeclaration ||
        node.parent.kind === ts.SyntaxKind.FunctionExpression ||
        node.parent.kind === ts.SyntaxKind.ArrowFunction ||
        node.parent.kind === ts.SyntaxKind.MethodDeclaration) &&
      node ===
        (node.parent as
          | ts.FunctionDeclaration
          | ts.FunctionExpression
          | ts.ArrowFunction
          | ts.MethodDeclaration).type
  );
}