typescript 教程
本文于 1594 天之前发表,文中内容可能已经过时。
TSLint 规则
一套完整的 TSLint 规则,以及对每条规则的释义。
使用方法
以tslint-config-alloy
为例:
安装:
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]
}
}
CLI 中运行
使用项目依赖中的 tslint
脚本,指定项目路径,检查所有 ts 后缀的文件:
./node_modules/.bin/tslint --project . ./**/*.ts
将 tslint
作为 npm scripts 运行:
package.json
的scripts
字段添加一条"tslint": "tslint --project . ./**/*.ts"
- 运行
npm run tslint
与 VSCode 集成
- 在 VSCode 中安装 tslint 插件
- 按下
Cmd
+,
或Ctrl
+,
,打开设置 - 将
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 的问题,则可以按照以下步骤配置:
- VSCode 安装 Prettier - Code formatter 插件
- 按下
Cmd
+,
或Ctrl
+,
,打开设置 - 将
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'
};
规则列表
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-require-imports | 禁止使用require |
object-literal-sort-keys | 对象字面量必须按key 排序 |
prefer-const | 申明后不再被修改的变量必须使用const 来申明 |
prefer-readonly | 如果私有变量只在构造函数中被赋值,则必须使用readonly 修饰符 |
trailing-comma | 限制对象、数组、解构赋值等的最后一项末尾是否需要逗号 |
代码风格
与代码风格相关的规则。
评论系统未开启,无法评论!