Skip to content

About

AlloyTeam TSLint 规则

Resources

Stars

200 stars

Watchers

13 watching

Forks

Repository files navigation

AlloyTeam TSLint 规则

一套完整的 TSLint 规则,以及对每条规则的释义。

使用方法

安装:

npm install --save-dev tslint typescript tslint-config-alloy

在你的项目根目录下创建 tslint.json,并将以下内容复制到文件中:

{
    "extends": ["tslint-config-alloy"],
    "linterOptions": {
        "exclude": ["**/node_modules/**"]
    },
    "rules": {
        // 这里填入你的项目需要的个性化配置,比如:
        //
        // // 一个缩进必须用两个空格替代
        // // @has-fixer 可自动修复
        // // @prettier 可交由 prettier 控制
        // "indent": [true, "spaces", 2]
    }
}

规则列表

TypeScript 相关

与 TypeScript 特性相关的规则。

开关 名称 描述
✅ adjacent-overload-signatures 重载的函数必须写在一起
❌ ban-types 禁用特定的类型
✅ member-access 必须设置类的成员的可访问性
✅ member-ordering 指定类成员的排序规则
❌ no-any 禁止使用 any
✅ no-empty-interface 禁止定义空的接口
✅ no-import-side-effect 禁止导入有副作用(立即执行)的模块,除了 css, less, sass, scss
✅ no-inferrable-types 禁止给一个初始化时直接赋值为 number, string 或 boolean 的变量显式的指定类型
✅ no-internal-module 禁止使用 module 来定义命名空间
✅ no-magic-numbers 禁止使用魔法数字,仅允许使用一部分白名单中的数字
✅ no-namespace 禁止使用 namespace 来定义命名空间
✅ no-non-null-assertion 禁止使用 non-null 断言(感叹号)
✅ no-parameter-reassignment 禁止对函数的参数重新赋值
✅ no-reference 禁止使用三斜线引入模块 /// <reference path="foo" />
❌ no-unnecessary-type-assertion 禁止无用的类型断言
✅ no-var-requires 禁止使用 require 来引入模块
✅ only-arrow-functions 必须使用箭头函数,除非是单独的函数声明或是命名函数
✅ prefer-for-of 使用 for 循环遍历数组时,如果 index 仅用于获取成员,则必须使用 for of 循环替代 for 循环
❌ promise-function-async async 函数的返回值必须是 Promise
❌ typedef 变量、函数返回值、函数参数等必须要有类型定义
✅ typedef-whitespace 类型定义的冒号前面必须没有空格,后面必须有一个空格
✅ unified-signatures 函数重载时,若能通过联合类型将两个函数的类型声明合为一个,则使用联合类型而不是两个函数声明

功能性检查

找出可能的错误,以及可能会产生 bug 的编码习惯。

开关 名称 描述
❌ await-promise await 必须接受 Promise
❌ ban 禁用指定的函数或全局方法
✅ ban-comma-operator 禁止使用逗号操作符
✅ curly if 后面必须有 {,除非是单行 if
✅ forin for in 内部必须有 hasOwnProperty
❌ import-blacklist 禁用指定的模块
❌ label-position 只允许在 do, for, while 或 switch 中使用 label
✅ no-arg 禁止使用 arguments.callee
❌ no-bitwise 禁止使用位运算
✅ no-conditional-assignment 禁止在分支条件判断中有赋值操作
❌ no-console 禁止使用 console
✅ no-construct 禁止使用 new 来生成 String, Number 或 Boolean
❌ no-debugger 禁止使用 debugger
✅ no-duplicate-super 禁止 super 在一个构造函数中出现两次
✅ no-duplicate-switch-case 禁止在 switch 语句中出现重复测试表达式的 case
✅ no-duplicate-variable 禁止出现重复的变量定义或函数参数名
❌ no-dynamic-delete 禁止 delete 动态的值
✅ no-empty 禁止出现空代码块,允许 catch 是空代码块
✅ no-eval 禁止使用 eval
❌ no-floating-promises 函数返回值为 Promise 时,必须被处理
❌ no-for-in-array 禁止对 array 使用 for in 循环
✅ no-implicit-dependencies 禁止引入 package.json 中不存在的模块
❌ no-inferred-empty-object-type 禁止推论出的类型是空对象类型
✅ no-invalid-template-strings 禁止在非模版字符串中出现 ${}
✅ no-invalid-this 禁止在类外面使用 this
❌ no-misused-new 禁止在接口中定义 constructor,或在类中定义 new
❌ no-null-keyword 禁止使用 null
✅ no-object-literal-type-assertion 禁止对对象字面量进行类型断言(断言成 any 是允许的)
❌ no-return-await 禁止没必要的 return await
❌ no-shadowed-variable 禁止变量名与上层作用域内的定义过的变量重复
✅ no-sparse-arrays 禁止在数组中出现连续的逗号,如 let foo = [,,]
✅ no-string-literal 禁止出现 foo['bar'],必须写成 foo.bar
✅ no-string-throw 禁止 throw 字符串,必须 throw 一个 Error 对象
❌ no-submodule-imports 禁止 import 模块的子文件
✅ no-switch-case-fall-through switch 的 case 必须 return 或 break
✅ no-this-assignment 禁止将 this 赋值给其他变量,除非是解构赋值
❌ no-unbound-method 使用实例的方法时,必须 bind 到实例上
❌ no-unnecessary-class 禁止定义没必要的类,比如只有静态方法的类
❌ no-unsafe-any 禁止取用一个类型为 any 的对象的属性
✅ no-unsafe-finally 禁止 finally 内出现 return, continue, break, throw 等
✅ no-unused-expression 禁止无用的表达式
❌ no-use-before-declare 变量必须先定义后使用
✅ no-var-keyword 禁止使用 var
❌ no-void-expression 禁止返回值为 void 类型
❌ prefer-conditional-expression 可以用三元表达式时,就不用 if else
✅ prefer-object-spread 使用 { ...foo, bar: 1 } 代替 Object.assign({}, foo, { bar: 1 })
✅ radix parseInt 必须传入第二个参数
❌ restrict-plus-operands 使用加号时,两者必须同为数字或同为字符串
❌ strict-boolean-expressions 在分支条件判断中必须传入布尔类型的值
❌ strict-type-predicates 禁止出现永远为 true 或永远为 false 的条件判断(通过类型预测出一个表达式为 true 还是 false)
❌ switch-default switch 语句必须有 default
✅ triple-equals 必须使用 === 或 !==,禁止使用 == 或 !=
❌ typeof-compare typeof 表达式比较的对象必须是 'undefined', 'object', 'boolean', 'number', 'string', 'function' 或 'symbol'
❌ use-default-type-parameter 传入的类型与默认类型一致时,必须省略传入的类型
✅ use-isnan 必须使用 isNaN(foo) 而不是 foo === NaN

可维护性

增强代码可维护性的规则。

开关 名称 描述
✅ cyclomatic-complexity 禁止函数的循环复杂度超过 20,详见 https://en.wikipedia.org/wiki/Cyclomatic_complexity
❌ deprecation 禁止使用废弃(被标识了 @deprecated)的 API
✅ eofline 文件最后一行必须有一个空行
✅ indent 一个缩进必须用四个空格替代
✅ linebreak-style 限制换行符为 LF 或 CRLF
❌ max-classes-per-file 限制每个文件的类的数量
❌ max-file-line-count 限制每个文件的行数
❌ max-line-length 限制每行字符数
❌ no-default-export 禁止使用 default export
✅ no-duplicate-imports 禁止出现重复的 import
✅ no-mergeable-namespace 禁止一个文件中出现多个相同的 namespace
❌ no-require-imports 禁止使用 require
❌ object-literal-sort-keys 对象字面量必须按 key 排序
❌ prefer-const 申明后不再被修改的变量必须使用 const 来申明
❌ prefer-readonly 如果私有变量只在构造函数中被赋值,则必须使用 readonly 修饰符
✅ trailing-comma 限制对象、数组、解构赋值等的最后一项末尾是否需要逗号

代码风格

与代码风格相关的规则。

开关 名称 描述
❌ align 变量定义需要竖向对其
❌ array-type 限制必须使用 T[] 或 Array<T> 之中的一种来定义数组的类型
✅ arrow-parens 箭头函数的参数必须有小括号
✅ arrow-return-shorthand 箭头函数的函数体只有 return 语句的时候,必须简写
❌ binary-expression-operand-order 数字字面量必须在加号的右边,即禁止 1 + x
✅ callable-types 可以简写为函数类型的接口或字面类似,必须简写
✅ class-name 类名与接口名必须为驼峰式
✅ comment-format 限制单行注释的规则
❌ completed-docs 类、函数等必须写注释
✅ encoding 文件类型必须是 utf-8
❌ file-header 文件的开头必须有指定的字符串
❌ file-name-casing 约束文件命名规范
✅ import-spacing import 语句中,关键字之间的间距必须是一个空格
❌ interface-name 接口名称必须已 I 开头
✅ interface-over-type-literal 优先使用接口而不是字面类型
✅ jsdoc-format 注释必须符合 JSDoc 规范
❌ match-default-export-name import 的名称必须和 export default 的名称一致
✅ new-parens new 后面只必须有一个空格
❌ newline-before-return return 语句前必须有空行
❌ newline-per-chained-call 链式调用时,每次调用都必须占用一行
✅ no-angle-bracket-type-assertion 类型断言必须使用 as Type,禁止使用 <Type>
❌ no-boolean-literal-compare 禁止变量与 true 或 false 比较
✅ no-consecutive-blank-lines 禁止连续超过三行空行
✅ no-irregular-whitespace 禁止使用特殊空白符(比如全角空格)
✅ no-parameter-properties 禁止给类的构造函数的参数添加修饰符
✅ no-redundant-jsdoc 禁止 JSDoc 中的冗余类型声明,因为 TypeScirpt 已经包含了大部分功能
✅ no-reference-import 如果已经引入过库,则禁止使用三斜杠引入类型定义文件
✅ no-trailing-whitespace 禁止行尾有空格
❌ no-unnecessary-callback-wrapper 禁止没必要的函数调用,如 x => f(x) 应该简写为 f
✅ no-unnecessary-initializer 禁止变量定义时赋值为 undefined
❌ no-unnecessary-qualifier 在命名空间中,可以直接使用内部变量,不需要添加命名空间前缀
✅ number-literal-format 小数必须以 0. 开头,禁止以 . 开头,并且不能以 0 结尾
❌ object-literal-key-quotes 对象的 key 必须用引号包起来
✅ object-literal-shorthand 必须使用 a = {b} 而不是 a = {b: b}
✅ one-line if 后的 { 禁止换行
✅ one-variable-per-declaration 变量申明必须每行一个,for 循环的初始条件中除外
✅ ordered-imports import 必须排序
❌ prefer-function-over-method 类中没有使用 this 的方法应该提取成类外的函数
❌ prefer-method-signature 必须使用 foo(): void 而不是 foo: () => void
❌ prefer-switch 当 if 中只有 === 时,必须使用 switch 替换 if
❌ prefer-template 必须使用模版字符串而不是字符串连接
❌ prefer-while 当没有初始值的时候,必须使用 while 而不是 for
✅ quotemark 必须使用单引号,jsx 中必须使用双引号
❌ return-undefined 使用 return; 而不是 return undefined;
✅ semicolon 行尾必须有分号
✅ space-before-function-paren 函数名前必须有空格
✅ space-within-parens 括号内首尾禁止有空格
❌ switch-final-break switch 的最后一项禁止有 break
✅ type-literal-delimiter 字面类型的每个成员都必须有分号
❌ variable-name 限制变量命名规则
✅ whitespace 限制空格的位置

CLI 中运行

使用项目依赖中的 tslint 脚本,指定项目路径,检查所有 ts 后缀的文件:

./node_modules/.bin/tslint --project . ./**/*.ts

将 tslint 作为 npm scripts 运行:

  1. package.json 的 scripts 字段添加一条 "tslint": "tslint --project . ./**/*.ts"
  2. 运行 npm run tslint

与 VSCode 集成

  1. 在 VSCode 中安装 tslint 插件
  2. 按下 Cmd + , 或 Ctrl + ,,打开设置
  3. 将 tslint.autoFixOnSave,配置为 true

与 Prettier 集成

Prettier 是一个专注于对代码风格进行统一格式化的工具,由于与 TSLint 的部分配置冲突,故需要使用 tslint-config-prettier 禁用掉 TSLint 的部分规则。

首先安装 prettier 和 tslint-config-prettier:

npm install --save-dev prettier tslint-config-prettier

然后为 tslint.config 的 extends 添加 tslint-config-prettier 即可:

{
    "extends": ["tslint-config-alloy", "tslint-config-prettier"],
    "linterOptions": {
        "exclude": ["**/node_modules/**"]
    },
    "rules": {
        // 这里填入你的项目需要的个性化配置,比如:
        //
        // // 一个缩进必须用两个空格替代
        // // @has-fixer 可自动修复
        // // @prettier 可交由 prettier 控制
        // "indent": [true, "spaces", 2]
    }
}

如果需要在 VSCode 中实现保存时修复 Prettier 的问题,则可以按照以下步骤配置:

  1. VSCode 安装 Prettier - Code formatter 插件
  2. 按下 Cmd + , 或 Ctrl + ,,打开设置
  3. 将 tslint.formatOnSave,配置为 true

Prettier 的配置文件 prettier.config.js 可以参考这个:

// prettier.config.js or .prettierrc.js
module.exports = {
    // 一行最多 100 字符
    printWidth: 100,
    // 使用 4 个空格缩进
    tabWidth: 4,
    // 不使用缩进符,而使用空格
    useTabs: false,
    // 行尾需要有分号
    semi: true,
    // 使用单引号
    singleQuote: true,
    // jsx 不使用单引号,而使用双引号
    jsxSingleQuote: false,
    // 末尾不需要逗号
    trailingComma: 'none',
    // 大括号内的首尾需要空格
    bracketSpacing: true,
    // jsx 标签的反尖括号需要换行
    jsxBracketSameLine: false,
    // 箭头函数,只有一个参数的时候,也需要括号
    arrowParens: 'always',
    // 每个文件格式化的范围是文件的全部内容
    rangeStart: 0,
    rangeEnd: Infinity,
    // 不需要写文件开头的 @prettier
    requirePragma: false,
    // 不需要自动在文件开头插入 @prettier
    insertPragma: false,
    // 使用默认的折行标准
    proseWrap: 'preserve',
    // 根据显示样式决定 html 要不要折行
    htmlWhitespaceSensitivity: 'css',
    // 换行符使用 lf
    endOfLine: 'lf'
};

About

AlloyTeam TSLint 规则

Resources

Stars

200 stars

Watchers

13 watching

Forks

Releases

Packages

Used by

Contributors

Languages