TypeScript编码规范
1 命名及约定
1.1 类
使用 PascalCase 进行命名。
Bad
Good
1.2 类成员(变量、方法)
使用 camelCase 进行命名。
Bad
Good
1.3 接口
使用 PascalCase 进行命名,不要在接口名前加“I”。
接口成员使用 camelCase 进行命名。
Bad
Good
1.4 命名空间
使用 PascalCase 进行命名。
Bad
Good
1.5 枚举
使用 PascalCase 进行命名。
Bad
Good
枚举成员使用 PascalCase 进行命名。
Bad
Good
1.6 文件名
- 使用破折号分隔描述性单词,比如:hero-list.ts。
- 使用点将描述性名称与类型分开,比如:user-info.page.ts。
- 尽量使用常规的几种类型名,包括.page,.service,.component,.pipe,.module,.directive,.controller 和.middleware。当然也可以自己创建其他类型,但不宜太多。
- 类名与文件名匹配,并遵循类命名规范。
类名 | 文件名 |
---|---|
export class AppComponent { } | app.component.ts |
export class HeroListComponent { } | hero-list.component.ts |
export class UserProfileService { } | user-profile.service.ts |
2 类型
需显式地为变量、数组和方法编写类型(类型推论能够推断出类型的不需要声明类型)。
Bad
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Bar {
bar(input) {
let isZero;
const foo: number = 5;
if (input === 5) {
isZero = false;
}
const resultObject = {
fo: foo,
isZeroRes: isZero,
};
return resultObject;
}
}Good
不要使用 Number、String、Boolean、Object 为变量、数组和方法设置类型。
Bad
Good
3 声明变量
如果变量在其生命周期可能发生改变,尽量使用 let。
如果一个值在程序生命周期内不会改变,尽量使用 const。
Bad
Good
4 对象
使用{}进行对象创建。
Bad
Good
在对象字面量里使用属性简写。
Bad
Good
仅使用引号用于属于无效标识符的属性。
Bad
Good
5 字符串
使用单引号声明字符串。
Bad
Good
6 解构
访问和使用对象的多个属性时,使用对象解构。
Bad
Good
访问数组中的多个数据时,使用解构。
Bad
Good
7 空格
- 在定义类型前面加上空格。
- 赋值等号两边加上空格。
- 方法、类大括号前空格。
- 对象冒号后空格。
Bad
1 | class Foo { |
Good
1 | class Foo { |
8 缩进
使用两个空格缩进。
9 分号
语句结尾添加分号。
Bad
Good
10 数组
使用[]定义数组。
Bad
Good
使用 push 添加数据
Bad
Good