All files noMixedInterfaceRule.ts

100% Statements 28/28
100% Branches 6/6
100% Functions 6/6
100% Lines 22/22
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  1x   1x 1x   1x 1x 1x   1x   1x 1x   7x     4x 4x 1x     4x   1x             4x 4x 7x 7x 6x 6x   3x    
import * as ts from "typescript";
import * as Lint from "tslint";
 
export class Rule extends Lint.Rules.AbstractRule {
  public static FAILURE_STRING = "Only the same kind of members allowed in interfaces.";
 
  public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    const walker = new PropertyInterfaceWalker(sourceFile, this.getOptions());
    return this.applyWithWalker(walker);
  }
}
 
class PropertyInterfaceWalker extends Lint.RuleWalker {
  public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void {
    // Extract 'kind' from all members to a list of numbers.
    const memberKinds: number[] = node.members.map((m) => m.kind);
 
    // Check so all members of a node have the same kind,
    const unUniqueMember: number = uniqIndex(memberKinds);
    if (unUniqueMember !== -1) {
      this.addFailure(this.createFailure(node.members[unUniqueMember].getStart(), node.members[unUniqueMember].getWidth(), Rule.FAILURE_STRING));
    }
 
    super.visitInterfaceDeclaration(node);
  }
}
 
/**
 * Return the index of the first non unique item.
 *
 */
function uniqIndex(list: number[]): number {
  let i = 0;
  let lastItem: number | undefined = undefined;
  for (let item of list) {
    if (lastItem !== undefined && lastItem !== item) { return i; }
    i++;
    lastItem = item;
  }
  return -1;
}