TypeScript 是一种静态类型的编程语言,它支持 JavaScript 的所有语法,并且增加了许多额外的语法和特性。下面是一些常用的 TypeScript 代码规范,以及相应的示例代码:
缩进:使用 2 个空格缩进。
function foo ( ) : void {
if ( condition) {
console . log ( 'Hello, world!' ) ;
}
}
命名:变量、函数、属性名使用小驼峰命名法;类名使用大驼峰命名法。
class Person {
firstName: string ;
lastName: string ;
constructor ( firstName: string , lastName: string ) {
this . firstName = firstName;
this . lastName = lastName;
}
getFullName ( ) : string {
return ` ${ this . firstName} ${ this . lastName} ` ;
}
}
类型注解:函数参数和返回值需要添加类型注解。
function add ( a: number , b: number ) : number {
return a + b;
}
接口:定义对象的接口时使用 PascalCase 命名法,并且在接口名前加上 I。
interface IPerson {
firstName: string ;
lastName: string ;
age? : number ;
}
const person: IPerson = {
firstName: 'John' ,
lastName: 'Doe' ,
} ;
枚举:定义枚举类型时使用 PascalCase 命名法。
enum Color {
Red,
Green,
Blue,
}
const color: Color = Color. Green;
类型别名:定义类型别名时使用 PascalCase 命名法,与接口名一致。
type IPerson = {
firstName: string ;
lastName: string ;
age? : number ;
} ;
const person: IPerson = {
firstName: 'John' ,
lastName: 'Doe' ,
} ;
空格:在关键字和圆括号之间加上空格。
function foo ( ) : void {
if ( condition) {
console . log ( 'Hello, world!' ) ;
}
if ( condition) {
console . log ( 'Hello, world!' ) ;
}
}
引号:使用单引号而不是双引号。
const message = 'Hello, world!' ;
const message = "Hello, world!" ;
注释:使用 JSDoc 风格的注释来描述函数和方法。
function add ( a: number , b: number ) : number {
return a + b;
}
格式化:
函数:函数名称应使用动词或动词短语,表示它们执行的操作。函数参数应该按以下顺序排列:必需参数首先,其次是可选参数和默认参数,最后是剩余参数。
function sendMessage ( to: string , message: string , cc? : string [ ] , bcc = [ ] , ... attachments: string [ ] ) {
}
布尔类型:不要使用 Bool 类型,而是使用 boolean 类型。
let bool: boolean = true ;
构造函数:定义构造函数时,将属性声明为参数,使用 public 访问修饰符自动创建类属性。
class Person {
constructor ( public firstName: string , public lastName: string ) { }
}
箭头函数:当函数体只有一条语句时,可以省略花括号和 return 关键字。
const add = ( a: number , b: number ) : number => a + b;
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' ;
类型推断:尽可能地让 TypeScript 推断变量的类型。当需要明确指定变量类型时,可以使用类型注解。
const str = 'hello' ;
const num: number = 123 ;
路径别名:使用路径别名来代替绝对路径或相对路径,提高代码可读性。
import { Foo } from '@components/Foo' ;
import { Bar } from '@services/Bar' ;
以上这些 TypeScript 代码规范可以帮助技术团队统一代码风格,提高代码质量和可读性,同时也能避免一些常见的编程错误。