Typescript
命名
文件
使用camelCase
为 ts 文件命名。
代码
- 使用
PascalCase
为类型命名。
::: codeStyle bad
ts
type todoItem = {
title: string
}
interface animal {
name: string
}
:::
::: codeStyle good
ts
type TodoItem = {
title:string
}
interface Animal = {
name:string
}
:::
- 类型多个属性结尾不加
,
使用换行。
::: codeStyle bad
ts
type TodoItem = {
title: string,
text: string,
}
ts
interface Animal {
title: string,
text: string,
}
:::
::: codeStyle good
ts
type TodoItem = {
title: string
text: string
}
ts
interface Animal {
title: string
text: string
}
:::
- 不要使用
I
做为接口名前缀。 - 使用
PascalCase
为枚举值命名。 - 使用
camelCase
为函数命名。 - 使用
camelCase
为属性或本地变量命名。 - 私有属性名添加
_
前缀。 - 尽可能使用完整的单词拼写命名。
类型
- 不要导出类型/函数,除非你要在不同的组件中共享它。
- 如无必要,不要在全局命名空间内定义类型/值。
- 在一个文件里,类型定义应该出现在顶部。
null 和 undefined
- 使用 undefined,不要使用
null
。
一般假设
- 假设像 Nodes,Symbols 等这样的对象在定义它的组件外部是不可改变的。不要去改变它们。
- 假设数组是不能改变的。
匿名函数表达式
使用 arrow 函数代替匿名函数表达式。
arrow 函数
只要需要的时候才把 arrow 函数的参数括起来。
::: codeStyle bad
ts
(x) => x + x
:::
::: codeStyle good
ts
// i.
x => x + x
// ii.
(x,y) => x + y
// iii.
<T>(x: T, y: T) => x === y
:::
循环体和条件语句
总是使用{}
把循环体和条件语句括起来。
::: codeStyle bad
ts
if(a > b) return 1
else return 0
:::
::: codeStyle good
ts
if (a > b) {
return 1
} else {
return 0
}
:::
开始的 " { "
开始的{总是在同一行。 ::: codeStyle bad
ts
if(a > b)
{
return 0
}
:::
::: codeStyle good
ts
if (a > b) {
return 0
}
:::
空格
小括号里开始不要有空格。
逗号,冒号,分号后要有一个空格。
::: codeStyle good
ts
// i.
for (var i = 0, n = str.length; i < 10; i++) {}
// ii.
if (x < 10) {
}
// iii.
function f(x: number, y: string): void {}
:::
变量声明
每个变量声明语句只声明一个变量。
::: codeStyle bad
ts
var x = 1, y = 2
:::
::: codeStyle good
ts
var x = 1
var y = 2
:::
Any
禁止使用 any 定义类型,最糟糕的情况使用 unknow 来定义
引号
允许的情况下都使用单引号
::: codeStyle good
ts
import { createApp } from 'vue'
const foo = {
name: 'zhangsan',
}
:::
结尾逗号
定义函数参数,对象,数组或者函数传参时
- 一行 不加 结尾逗号
- 多行 加 结尾逗号
::: codeStyle bad
ts
//单行
function foo(a: string, b: string,){}
foo(1, 2,)
const arr = [1, 2, 3,]
const obj = {name: 'zhangsan', age: 19,}
ts
//多行
function foo(
a: string,
b: string
){
}
foo(
1,
2
)
const arr = [
1,
2,
3
]
const obj = {
name: 'zhangsan',
age: 19
}
:::
::: codeStyle good
ts
//单行
function foo(a: string, b: string) {}
foo(1, 2)
const arr = [1, 2, 3]
const obj = { name: 'zhangsan', age: 19 }
ts
//多行
function foo(
a: string,
b: string,
){
}
foo(
1,
2,
)
const arr = [
1,
2,
3,
]
const obj = {
name: 'zhangsan',
age: 19,
}
:::