[关闭]
@Secretmm 2021-01-20T07:35:20.000000Z 字数 877 阅读 586

ts代码风格规范

梳理


一、类型定义空格

定义变量类型的冒号前没有空格,冒号后有空格;表示可选属性/参数的问号前后没有空格

  1. let foo: string;
  2. let person: {
  3. name: string;
  4. age?: number;
  5. };

二、 interface和对象中属性类型定义后用分号

interface和对象中属性类型定义后用分号, 而不是逗号;拖尾分号规则与拖尾逗号一致

  1. interface Peaple {
  2. name: string;
  3. age: number;
  4. }
  5. type Foo = {
  6. id: string;
  7. state: number;
  8. }
  9. let bar: { status: string } = { status: 'error' };

三、 interface和自定义类型命名使用大驼峰

  1. interface ActiveItem {
  2. id: string;
  3. remark: string;
  4. }
  5. type DisabledItem = {
  6. id: string;
  7. remark: string;
  8. }

四、 枚举enum及枚举值的命名使用大驼峰

  1. enum RequestStaus {
  2. Ready,
  3. LoadSuccess,
  4. LoadFail
  5. }

五、 函数返回类型

有返回值的函数在定义时要声明返回值类型;没有返回值的函数也建议在定义时声明void类型

  1. function add(a: number, b: number): number {
  2. return a + b;
  3. }

六、 减少any类型

如无必要,不使用any类型;尽量将类型定义清晰

七、Class公共成员加public

Class中,可被外部访问的成员变量和方法(不包括constructorgetset)在声明时显式的加public关键字

  1. class Client {
  2. public id: number;
  3. constructor() {}
  4. public connect(url: string) {
  5. // TODO
  6. }
  7. }

八、 类型断言/强制转换使用as

在类型断言或者类型强制转换时,使用as关键字,而不是<>

  1. interface Foo {
  2. bar: number;
  3. bas: string;
  4. }
  5. // 推荐
  6. const foo = {} as Foo;
  7. // 不推荐
  8. const foo = <Foo>{};
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注