TSLint is a static code analysis tool used in software development for checking Typescript code quality , if TypeScript source code complies with coding rules. TSLint checks your TypeScript code for readability, maintainability, and functionality errors.

Installation :

You can install TSLint by using "npm". you just run the following commands in the command prompt.

"npm install typescript -g"


Switch to the root of your TypeScript project and generate tslint.jsonconfig file by just running the below command. "tslint --init".


tslint will have to use the same version of tsc used to actually compile your sources files. tslint will have to use the same version of tsc used to actually compile your sources files. Usage : Please ensure that the TypeScript source files compile correctly before running the linter. Usage: tslint [options] [file ...]

-c, --config          configuration file
--force               return status code 0 even if there are lint errors
-h, --help            display detailed help
-i, --init            generate a tslint.json config file in  the current working directory
-o, --out             output file
-r, --rules-dir       rules directory
-s, --formatters-dir  formatters directory
-e, --exclude         exclude globs from path expansion
-t, --format          output format (prose, json, verbose, pmd, msbuild, checkstyle)    [default: "prose"]
--test                test that tslint produces the correct output for the specified directory
-v, --version         current version

you can use tslint through gulp. first run the below command in the command prompt.

"npm install gulp-tslint -g"

see the below example how to use tslint in gulp.

gulp.task("tslint", function(){
  return   gulp.src("./src/lib/searching-functions.ts")

now run 'gulp tslint ' command in the prompt .By default, TSLint looks for a configuration file named tslint.json in the directory of the file being linted and, if not found, searches ancestor directories. A sample config filewith all possible rules is available.

Rules :

TypeScript Specific : These rules find errors related to TypeScript features: member-access : Requires explicit visibility declarations for class members. Explicit visibility declarations can make code more readable and accessible for those new to TS. Two arguments may be optionally provided: "check-accessor" enforces explicit visibility on get/set accessors (can only be public) "check-constructor" enforces explicit visibility on constructors (can only be public). Examples "member-access": true "member-access": [true, "check-accessor"] member-ordering : Enforces member ordering.A consistent ordering for class members can make classes easier to read, navigate, and edit. One argument, which is an object, must be provided. It should contain an orderproperty. The order property should have a value of one of the following strings: fields-first statics-first instance-sandwich Alternatively, the value for order maybe be an array consisting of the following strings: public-static-field protected-static-field private-static-field public-instance-field protected-instance-field private-instance-field constructor public-static-method protected-static-method private-static-method public-instance-method protected-instance-method private-instance-method Examples

"member-ordering": [true, { "order": "fields-first" }]

no-any: Don't use any data type. Using any as a type declaration nullifies the compile-time benefits of the type system. Examples

"no-any": true

no-inferrable-types: Always give data types for variables. Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean. Examples

"no-inferrable-types": true
"no-inferrable-types": [true, "ignore-params"]

no-internal-module: Disallows internal module.Using module leads to a confusion of concepts with external modules. Use the newernamespace keyword instead. Examples

"no-internal-module": true

no-namespace: Disallows use of internal modules and namespaces.This rule still allows the use of declare module ... {}. ES6-style external modules are the standard way to modularize code. Using module {}and namespace {} are outdated ways to organize TypeScript code. Examples "no-namespace": true "no-namespace": [true, "allow-declarations"] no-reference: Disallows /// imports (use ES6-style imports instead). Using /// comments to load other files is outdated. Use ES6-style imports to reference other files. Examples "no-reference": true no-var-requires: Disallows the use of require statements except in import statements.In other words, the use of forms such as var module = require("module") are banned. Instead use ES6 style imports or import foo = require('foo') imports. Examples "no-var-requires": true typedef: Requires type definitions to exist. Six arguments may be optionally provided: "call-signature" checks return type of functions. "parameter" checks type specifier of function parameters for non-arrow functions. "arrow-parameter" checks type specifier of function parameters for arrow functions. "property-declaration" checks return types of interface properties. "variable-declaration" checks variable declarations. "member-variable-declaration" checks member variable declarations. Examples

"typedef": [true, "call-signature", "parameter", "member-variable-declaration"]

typedef-whitespace: Requires or disallows whitespace for type definitions.Determines if a space is required or not before the colon in a type specifier. Possible keys are: "call-signature" checks return type of functions. "index-signature" checks index type specifier of indexers. "parameter" checks function parameters. "property-declaration" checks object property declarations. "variable-declaration" checks variable declaration. Examples

    "call-signature": "nospace",
    "index-signature": "nospace",
    "parameter": "nospace",
    "property-declaration": "nospace",
    "variable-declaration": "nospace"
    "call-signature": "onespace",
    "index-signature": "onespace",
    "parameter": "onespace",
    "property-declaration": "onespace",
    "variable-declaration": "onespace"

Functionality: These rules catch common errors in JS programming or otherwise confusing constructs that are prone to producing bugs. ban : Bans the use of specific functions.At this time, there is no way to disable global methods with this rule. Examples "ban": [true, ["console", "log"], ["someObject", "someFunction"]] curly: Enforces braces for if/for/do/while statements. Ex:

if (foo === bar)

In the code above, the author almost certainly meant for both foo++ and bar++ to be executed only if foo === bar. However, he forgot braces and bar++ will be executed no matter what. This rule could prevent such a mistake. Examples "curly": true forin: Requires a for ... in statement to be filtered with an if statement. Ex:

for (let key in someObject) {
    if (someObject.hasOwnProperty(key)) {
        // code here

Prevents accidental interation over properties inherited from an object’s prototype. SeeMDN’s for...in documentation for more information about for...in loops. Examples

"forin": true

Only allows labels in sensible locations. This rule only allows labels to be on do/for/while/switch statements. Labels in JavaScript only can be used in conjunction with break or continue, constructs meant to be used for loop flow control. While you can theoretically use labels on any block statement in JS, it is considered poor code structure to do so. Examples

"label-position": true

no-bitwise: Disallows bitwise operators.Specifically, the following bitwise operators are banned: &, &=, |, |=, ^, ^=, <<, <<=,>>, >>=, >>>, >>>=, and ~. This rule does not ban the use of & and | for intersection and union types. Bitwise operators are often typos - for example bool1 & bool2 instead of bool1 && bool2. They also can be an indicator of overly clever code which decreases maintainability. Examples "no-bitwise": true no-conditional-assignment: Disallows any type of assignment in conditionals.This applies to do-while, for, if, and while statements. Assignments in conditionals are often typos: for example if (var1 = var2) instead ofif (var1 == var2). They also can be an indicator of overly clever code which decreases maintainability. Examples "no-conditional-assignment": true no-console: Bans the use of specified console methods.In general, console methods aren’t appropriate for production code. Examples "no-console": [true, ["log", "error"]] no-construct Disallows access to the constructors of String, Number, and Boolean. Disallows constructor use such as new Number(foo) but does not disallow Number(foo). There is little reason to use String, Number, or Boolean as constructors. In almost all cases, the regular function-call version is more appropriate. More details are available on StackOverflow. Examples

"no-construct": true

no-debugger Disallows debugger statements.In general, debugger statements aren’t appropriate for production code. Examples

"no-debugger": true

no-duplicate-key Disallows duplicate keys in object literals. There is no good reason to define an object literal with the same key twice. This rule is now implemented in the TypeScript compiler and does not need to be used. Examples

"no-duplicate-key": true

no-duplicate-variable Disallows duplicate variable declarations in the same block scope. This rule is only useful when using the var keyword - the compiler will detect redeclarations of let and const variables. A variable can be reassigned if necessary - there’s no good reason to have a duplicate variable declaration. Examples "no-duplicate-variable": true no-empty Disallows empty blocks.Blocks with a comment inside are not considered empty. Empty blocks are often indicators of missing code. Examples "no-empty": true no-eval: Disallows eval function invocations. eval() is dangerous as it allows arbitrary code execution with full privileges. There arealternatives for most of the use cases for eval(). Examples

"no-eval": true

no-invalid-this: Disallows using the this keyword outside of classes. check-function-in-method disallows using the this keyword in functions within class methods. Examples

"no-invalid-this": true
"no-invalid-this": [true, "check-function-in-method"]

no-null-keyword: Disallows use of the null keyword literal. Instead of having the dual concepts of null and undefined in a codebase, this rule ensures that only undefined is used. Examples "no-null-keyword": true no-shadowed-variable Disallows shadowing variable declarations.Shadowing a variable masks access to it and obscures to what value an identifier actually refers. In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. This outer variable is said to be shadowed by the inner variable, while the inner identifier is said to mask the outer identifier. Examples

"no-shadowed-variable": true

no-switch-case-fall-through Disallows falling through case statements.For example, the following is not allowed:

switch(foo) {
    case 1:
    case 2:

However, fall through is allowed when case statements are consecutive or a magic /* falls through */ comment is present. The following is valid:

switch(foo) {
    case 1:
        /* falls through */
    case 2:
    case 3:

Fall though in switch statements is often unintentional and a bug. Examples

"no-switch-case-fall-through": true

no-unreachable: Disallows unreachable code after break, catch, throw, and return statements. Examples

"no-unreachable": true

no-unused-expression Disallows unused expression statements. Unused expressions are expression statements which are not assignments or function calls (and thus usually no-ops). Detects potential errors where an assignment or function call was intended. Also detects constructs such as new SomeClass(), where a constructor is used solely for its side effects, which is considered poor style. Examples

"no-unused-expression": true

no-unused-variable Disallows unused imports, variables, functions and private class members. Examples

"no-unused-variable": [true, "react"]
"no-unused-variable": [true, {"ignore-pattern": "^_"}]

no-use-before-declare Disallows usage of variables before their declaration. This rule is primarily useful when using the var keyword - the compiler will detect if alet and const variable is used before it is declared. Examples

"no-use-before-declare": true

no-var-keyword Disallows usage of the var keyword. Use let or const instead. Examples

"no-var-keyword": true

radix Requires the radix parameter to be specified when calling parseInt. From MDN: > Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. > Different implementations produce different results when a radix is not specified, usually defaulting the value to 10. Examples "radix": true switch-default Require a default case in all switch statements. Examples "switch-default": true triple-equals Requires === and !== in place of == and !=. Two arguments may be optionally provided: "allow-null-check" allows == and != when comparing to null. "allow-undefined-check" allows == and != when comparing to undefined. Examples

"triple-equals": true
"triple-equals": [true, "allow-null-check"]
"triple-equals": [true, "allow-undefined-check"]

use-isnan Enforces use of the isNaN() function to check for NaN references instead of a comparison to the NaN constant.Since NaN !== NaN, comparisons with regular operators will produce unexpected results. So, instead of if (myVar === NaN), do if (isNaN(myVar)). Examples "use-isnan": true use-strict Requires using ECMAScript 5’s strict mode.Two arguments may be optionally provided: check-module checks that all top-level modules are using strict mode. check-function checks that all top-level functions are using strict mode. Examples "use-strict": [true, "check-module"] Maintainability: These rules make code maintenance easier: indent enforces indentation with tabs or spaces.Using only one of tabs or spaces for indentation leads to more consistent editor behavior, cleaner diffs in version control, and easier programatic manipulation. One of the following arguments must be provided: "spaces" enforces consistent spaces. "tabs" enforces consistent tabs. Examples

"indent": [true, "spaces"]

max-line-length Requires lines to be under a certain max length. Limiting the length of a line of code improves code readability. It also makes comparing code side-by-side easier and improves compatibility with various editors, IDEs, and diff viewers.An integer indicating the max length of lines. Examples

"max-line-length": [true, 120]

no-default-export Disallows default exports in ES6-style modules. Use named exports instead. Named imports/exports promote clarity. In addition, current tooling differs on the correct way to handle default imports/exports. Avoiding them all together can help avoid tooling bugs and conflicts. Examples

"no-default-export": true

no-require-imports Disallows invocation of require(). Prefer the newer ES6-style imports over require(). Examples

"no-require-imports": true

no-trailing-whitespace Disallows trailing whitespace at the end of a line. Keeps version control diffs clean as it prevents accidental whitespace from being committed. Examples "no-trailing-whitespace": true object-literal-sort-keys Requires keys in object literals to be sorted alphabetically Useful in preventing merge conflicts Examples "object-literal-sort-keys": true Style These rules enforce consistent style across your codebase: align Enforces vertical alignment.Helps maintain a readable, consistent style in your codebase. Three arguments may be optionally provided: "parameters" checks alignment of function parameters. "arguments" checks alignment of function call arguments. "statements" checks alignment of statements. Examples "align": [true, "parameters", "statements"]


class-name: Enforces PascalCased class and interface names.Makes it easy to differentitate classes from regular variables at a glance. Examples "class-name": true comment-format Enforces formatting rules for single-line comments. Helps maintain a consistent, readable style in your codebase. Three arguments may be optionally provided: "check-space" requires that all single-line comments must begin with a space, as in// comment note that comments starting with /// are also allowed, for things such as/// "check-lowercase" requires that the first non-whitespace character of a comment must be lowercase, if applicable. "check-uppercase" requires that the first non-whitespace character of a comment must be uppercase, if applicable. Examples

"comment-format": [true, "check-space", "check-lowercase"]

interface-name Requires interface names to begin with a capital ‘I’ Makes it easy to differentitate interfaces from regular classes at a glance. One of the following two options must be provided: "always-prefix" requires interface names to start with an “I? "never-prefix" requires interface names to not have an “I? prefix Examples "interface-name": [true, "always-prefix"] "interface-name": [true, "never-prefix"] jsdoc-format Enforces basic format rules for JSDoc comments. The following rules are enforced for JSDoc comments (comments starting with /**): each line contains an asterisk and asterisks must be aligned each asterisk must be followed by either a space or a newline (except for the first and the last) the only characters before the asterisk on each line must be whitespace characters one line comments must start with /** and end with */ Helps maintain a consistent, readable style for JSDoc comments. Examples "jsdoc-format": true new-parens Requires parentheses when invoking a constructor via the new keyword. Maintains stylistic consistency with other function calls. Examples

"new-parens": true

no-angle-bracket-type-assertion Requires the use of as Type for type assertions instead of . Both formats of type assertions have the same effect, but only as type assertions work in .tsx files. This rule ensures that you have a consistent type assertion style across your codebase. Examples

"no-angle-bracket-type-assertion": true

no-consecutive-blank-lines Disallows more than one blank line in a row.Helps maintain a readable style in your codebase. Examples "no-consecutive-blank-lines": true no-constructor-vars Disallows parameter properties.Parameter properties can be confusing to those new to TS as they are less explicit than other ways of declaring and initializing class members. Examples

"no-constructor-vars": true

one-line Requires the specified tokens to be on the same line as the expression preceding them. Five arguments may be optionally provided: "check-catch" checks that catch is on the same line as the closing brace for try. "check-finally" checks that finally is on the same line as the closing brace forcatch. "check-else" checks that else is on the same line as the closing brace for if. "check-open-brace" checks that an open brace falls on the same line as its preceding expression. "check-whitespace" checks preceding whitespace for the specified tokens. Examples

"one-line": [true, "check-catch", "check-finally", "check-else"]

one-variable-per-declaration Disallows multiple variable definitions in the same declaration statement. One argument may be optionally provided: ignore-for-loop allows multiple variable definitions in a for loop declaration. Examples

"one-variable-per-declaration": true
"one-variable-per-declaration": [true, "ignore-for-loop"]

quotemark Requires single or double quotes for string literals. Five arguments may be optionally provided: "single" enforces single quotes. "double" enforces double quotes. "jsx-single" enforces single quotes for JSX attributes. "jsx-double" enforces double quotes for JSX attributes. "avoid-escape" allows you to use the “other? quotemark in cases where escaping would normally be required. For example, [true, "double", "avoid-escape"] would not report a failure on the string literal 'Hello "World"'. Examples

"quotemark": [true, "single", "avoid-escape"]
"quotemark": [true, "single", "jsx-double"]

semicolon Enforces consistent semicolon usage at the end of every statement. One of the following arguments must be provided: "always" enforces semicolons at the end of every statement. "never" disallows semicolons at the end of every statement except for when they are necessary. Examples

"semicolon": [true, "always"]
"semicolon": [true, "never"]

variable-name Checks variable names for various errors. Five arguments may be optionally provided: "check-format": allows only camelCased or UPPER_CASED variable names "allow-leading-underscore" allows underscores at the beginning (only has an effect if “check-format? specified) "allow-trailing-underscore" allows underscores at the end. (only has an effect if “check-format? specified) "allow-pascal-case allows PascalCase in addtion to camelCase. "ban-keywords": disallows the use of certain TypeScript keywords (any, Number,number, String, string, Boolean, boolean, undefined) as variable or parameter names. Examples

"variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"]

whitespace Enforces whitespace style conventions. Helps maintain a readable, consistent style in your codebase. Seven arguments may be optionally provided: "check-branch" checks branching statements (if/else/for/while) are followed by whitespace. "check-decl"checks that variable declarations have whitespace around the equals token. "check-operator" checks for whitespace around operator tokens. "check-module" checks for whitespace in import & export statements. "check-separator" checks for whitespace after separator tokens (,/;). "check-type" checks for whitespace before a variable type specification. "check-typecast" checks for whitespace between a typecast and its target. Examples

"whitespace": [true, "check-branch", "check-operator", "check-typecast"]

How to Save TSlint errors in a separate file :

I hope you know how to use TSlint.If you don't know click the link to learn about TSLint. Download "map-stream " . command to download map-stream "npm install map-stream" Now load map-stream in your gulpfile.js file. Look at the below example to understand clearly. Ex:

var gulp = require("gulp"),
concat = require("gulp-concat"),
map = require("map-stream"),
tslint = require("gulp-tslint") ;
 gulp.task("tslint", function(){
  return   gulp.src("./src/lib/searching-functions.ts")
         .pipe(map(function(file, done) {
           // Add the tslint errors in prose format
           if (file.tslint.output) {
               file.contents = new Buffer(
           } else {
               file.contents = new Buffer("");
           done(null, file);
       // Concat and save the errors

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions