Typescript编写一个检查方法名称和对象类型的规则

时间:2018-10-22 12:00:58

标签: angular typescript tslint

我正在努力编写一个自定义规则,该规则将检查方法名称和对象类型。我需要检查方法名称是否为“ includes”,对象是否为Array类型。我怎样才能做到这一点?我确实找到了一些提示here,但不知道如何获取对象类型。
这就是我想出的全部内容,但是我只能从中获得方法名称。

import * as ts from 'typescript';
import * as Lint from 'tslint';

/**
 * Rule for checking if project uses non IE supportive functions and errors them
 * To build run command 'tsc src\rules\noIeFunctionsRule.ts --lib 'es6,dom''
 */

export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
    ruleName: 'no-ie-functions',
    description: 'Disallow use of Internet Explorer uncompactible functions',
    optionsDescription: 'Not configurable.',
    options: null,
    optionExamples: [true],
    rationale: Lint.Utils.dedent`
        When function or constructor may be called with a type parameter but one isn't supplied or inferrable,
        TypeScript defaults to \`{}\`.
        This is often undesirable as the call is meant to be of a more specific type.
    `,
    type: 'functionality',
    typescriptOnly: true,
    requiresTypeInfo: true,
};
public static METHOD_INCLUDES = 'Internet Explorer does not support this method, use "indexOf(value) > 0" instead';

public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
    return this.applyWithWalker(new IeWalker(sourceFile, this.ruleName, program.getTypeChecker()));
}
}

class IeWalker extends Lint.AbstractWalker<void> {

constructor(sourceFile: ts.SourceFile, ruleName: string, private readonly checker: ts.TypeChecker) {
    super(sourceFile, ruleName, undefined);
}

public walk(sourceFile: ts.SourceFile): void {
    const cb = (node: ts.Node): void => {
        if (node.kind === ts.SyntaxKind.CallExpression) {
            this.checkCallExpression(node as ts.CallExpression);
        }
        return ts.forEachChild(node, cb);
    };
    return ts.forEachChild(sourceFile, cb);
}

private checkCallExpression(node: ts.CallExpression) {
    if (node.expression.getText().includes('includes')) {
            this.addFailureAtNode(node, Rule.METHOD_INCLUDES);
    }
}

}

0 个答案:

没有答案