> 文章列表 > TS代码规范

TS代码规范

TS代码规范

TypeScript 是一种静态类型的编程语言,它支持 JavaScript 的所有语法,并且增加了许多额外的语法和特性。下面是一些常用的 TypeScript 代码规范,以及相应的示例代码:

  1. 缩进:使用 2 个空格缩进。
function foo(): void {if (condition) {// 两个空格缩进console.log('Hello, world!');}
}
  1. 命名:变量、函数、属性名使用小驼峰命名法;类名使用大驼峰命名法。
class Person {firstName: string;lastName: string;constructor(firstName: string, lastName: string) {this.firstName = firstName;this.lastName = lastName;}getFullName(): string {return `${this.firstName} ${this.lastName}`;}
}
  1. 类型注解:函数参数和返回值需要添加类型注解。
function add(a: number, b: number): number {return a + b;
}
  1. 接口:定义对象的接口时使用 PascalCase 命名法,并且在接口名前加上 I。
interface IPerson {firstName: string;lastName: string;age?: number;
}const person: IPerson = {firstName: 'John',lastName: 'Doe',
};
  1. 枚举:定义枚举类型时使用 PascalCase 命名法。
enum Color {Red,Green,Blue,
}const color: Color = Color.Green;
  1. 类型别名:定义类型别名时使用 PascalCase 命名法,与接口名一致。
type IPerson = {firstName: string;lastName: string;age?: number;
};const person: IPerson = {firstName: 'John',lastName: 'Doe',
};
  1. 空格:在关键字和圆括号之间加上空格。
function foo(): void {if (condition) { // 错误的写法console.log('Hello, world!');}if (condition) { // 正确的写法console.log('Hello, world!');}
}
  1. 引号:使用单引号而不是双引号。
const message = 'Hello, world!'; // 正确的写法
const message = "Hello, world!"; // 错误的写法
  1. 注释:使用 JSDoc 风格的注释来描述函数和方法。
/* Adds two numbers together. @param {number} a - The first number to add.* @param {number} b - The second number to add.* @returns {number} The sum of the two numbers.*/
function add(a: number, b: number): number {return a + b;
}
  1. 格式化:

//使用 prettier 或者其他代码格式化工具来格式化代码。
  1. 函数:函数名称应使用动词或动词短语,表示它们执行的操作。函数参数应该按以下顺序排列:必需参数首先,其次是可选参数和默认参数,最后是剩余参数。

function sendMessage(to: string, message: string, cc?: string[], bcc = [], ...attachments: string[]) {// ...
}
  1. 布尔类型:不要使用 Bool 类型,而是使用 boolean 类型。

let bool: boolean = true;
  1. 构造函数:定义构造函数时,将属性声明为参数,使用 public 访问修饰符自动创建类属性。

class Person {constructor(public firstName: string, public lastName: string) {}
}
  1. 箭头函数:当函数体只有一条语句时,可以省略花括号和 return 关键字。

const add = (a: number, b: number): number => a + b;
  1. null 和 undefined:尽可能地避免使用 null 和 undefined。当需要使用这两个值时,可以使用非空断言操作符(!)或可选链操作符(?)来处理。

let str: string | null = 'hello';
str = null; // 错误的写法let str: string | null = 'hello';
str!.toUpperCase(); // 正确的写法interface Person {name?: string;
}const person: Person = {};
const name = person?.name ?? 'Unknown'; // 使用可选链操作符和空值合并运算符
  1. 类型推断:尽可能地让 TypeScript 推断变量的类型。当需要明确指定变量类型时,可以使用类型注解。

const str = 'hello'; // 推断为 string 类型
const num: number = 123; // 明确指定为 number 类型
  1. 路径别名:使用路径别名来代替绝对路径或相对路径,提高代码可读性。

import { Foo } from '@components/Foo';
import { Bar } from '@services/Bar';

以上这些 TypeScript 代码规范可以帮助技术团队统一代码风格,提高代码质量和可读性,同时也能避免一些常见的编程错误。