code-style-typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Code Style Guide
TypeScript代码风格指南
When to Apply
适用场景
- When writing new TypeScript code
- During code review of files
.ts - When refactoring existing code
- When generating code snippets, examples, or documentation for TypeScript
- When working with TypeScript-related blocks in Markdown, Vue.js, etc.
- When formatting or cleaning up code
- 编写新的TypeScript代码时
- 评审.ts文件时
- 重构现有代码时
- 生成TypeScript代码片段、示例或文档时
- 处理Markdown、Vue.js等文件中与TypeScript相关的代码块时
- 格式化或清理代码时
Rules
规则
Rule: No semicolons at the end of statements
规则:语句末尾不加分号
No semicolons at the end of statements.
Exception: TypeScript interfaces, types, and similar type definitions MUST use semicolons as property separators.
语句末尾不加分号。
例外情况:TypeScript接口、类型及类似的类型定义必须使用分号作为属性分隔符。
Examples
示例
✅ Correct:
typescript
// Statements - no semicolons
const result = calculateValue()
function greet(name: string) {
return `Hello, ${name}`
}
// Interfaces - semicolons required
interface User {
id: number;
}
type Config = {
timeout: number;
}
// Classes - no semicolons
class UserService {
private users: User[]
constructor() {
this.users = []
}
addUser(user: User) {
this.users.push(user)
}
}❌ Wrong:
typescript
// Don't add semicolons to statements
const foo = 'bar';
function greet(name: string) {
return `Hello, ${name}`;
}
// Don't omit semicolons in interfaces
interface User {
id: number
}
type Config = {
apiKey: string
}✅ 正确写法:
typescript
// Statements - no semicolons
const result = calculateValue()
function greet(name: string) {
return `Hello, ${name}`
}
// Interfaces - semicolons required
interface User {
id: number;
}
type Config = {
timeout: number;
}
// Classes - no semicolons
class UserService {
private users: User[]
constructor() {
this.users = []
}
addUser(user: User) {
this.users.push(user)
}
}❌ 错误写法:
typescript
// Don't add semicolons to statements
const foo = 'bar';
function greet(name: string) {
return `Hello, ${name}`;
}
// Don't omit semicolons in interfaces
interface User {
id: number
}
type Config = {
apiKey: string
}Rule: No method calls in conditional statements
规则:条件语句中不直接调用方法
Extract method calls to separate variables before using them in conditional statements (, , , etc.).
ifwhilefor提取方法调用结果到单独变量中,再在条件语句(、、等)中使用。
ifwhileforExamples
示例
✅ Correct:
typescript
const isAdmin = user.isAdmin()
if (isAdmin) {
console.log('Admin access granted')
}
const hasPermission = checkPermissions(user, 'write')
while (hasPermission) {
// Do something
}❌ Wrong:
typescript
// Don't call methods directly in conditions
if (user.isAdmin()) {
console.log('Admin access granted')
}
while (checkPermissions(user, 'write')) {
// Do something
}✅ 正确写法:
typescript
const isAdmin = user.isAdmin()
if (isAdmin) {
console.log('Admin access granted')
}
const hasPermission = checkPermissions(user, 'write')
while (hasPermission) {
// Do something
}❌ 错误写法:
typescript
// Don't call methods directly in conditions
if (user.isAdmin()) {
console.log('Admin access granted')
}
while (checkPermissions(user, 'write')) {
// Do something
}Rule: No function calls as arguments
规则:函数参数中不直接调用函数
Extract function calls to separate variables before using them as arguments to other functions.
Exception: See "Nested function calls as arguments on separate lines" rule for rare cases.
提取函数调用结果到单独变量中,再作为其他函数的参数使用。
例外情况:在罕见场景下,可遵循“嵌套函数调用作为参数时分行书写”规则。
Examples
示例
✅ Correct:
typescript
const userData = fetchUser()
const result = processData(userData)
const filtered = filterItems(items)
const mapped = mapValues(filtered)
const validation = validateInput(data)
saveToDatabase(validation)❌ Wrong:
typescript
// Don't call functions directly in arguments
const result = processData(fetchUser())
const mapped = mapValues(filterItems(items))
saveToDatabase(validateInput(data))✅ 正确写法:
typescript
const userData = fetchUser()
const result = processData(userData)
const filtered = filterItems(items)
const mapped = mapValues(filtered)
const validation = validateInput(data)
saveToDatabase(validation)❌ 错误写法:
typescript
// Don't call functions directly in arguments
const result = processData(fetchUser())
const mapped = mapValues(filterItems(items))
saveToDatabase(validateInput(data))Rule: Group one-line declarations together, separate multiline declarations
规则:单行声明分组,多行声明分隔
One-line declarations should stay together without blank lines. Multiline declarations should be separated by blank lines.
单行声明应连续书写,不添加空行。多行声明之间需用空行分隔。
Examples
示例
✅ Correct:
typescript
const age = 30
const city = 'New York'
const name = 'John'
const complexObject = {
id: 1,
metadata: {
created: new Date(),
updated: new Date()
},
name: 'Product'
}
const anotherSimple = 'value'
const moreSimple = 42❌ Wrong:
typescript
// Don't separate one-line declarations
const name = 'John'
const age = 30
const city = 'New York'
// Don't keep multiline declarations together
const complexObject = {
id: 1,
name: 'Product'
}
const anotherObject = {
bar: 'baz',
foo: 'bar'
}✅ 正确写法:
typescript
const age = 30
const city = 'New York'
const name = 'John'
const complexObject = {
id: 1,
metadata: {
created: new Date(),
updated: new Date()
},
name: 'Product'
}
const anotherSimple = 'value'
const moreSimple = 42❌ 错误写法:
typescript
// Don't separate one-line declarations
const name = 'John'
const age = 30
const city = 'New York'
// Don't keep multiline declarations together
const complexObject = {
id: 1,
name: 'Product'
}
const anotherObject = {
bar: 'baz',
foo: 'bar'
}Rule: Inline JSDoc comments on one line
规则:单行JSDoc注释
One-line JSDoc comments should be on the same line with and .
/***/单行JSDoc注释应与和写在同一行。
/***/Examples
示例
✅ Correct:
typescript
/** User ID */
const userId = 123
/** Calculates the total price */
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0)
}
/**
* Complex function with detailed documentation
* @param name - User name
* @returns Greeting message
*/
function greet(name: string): string {
return `Hello, ${name}`
}❌ Wrong:
typescript
/**
* User ID
*/
const userId = 123
/**
* Calculates the total price
*/
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0)
}✅ 正确写法:
typescript
/** User ID */
const userId = 123
/** Calculates the total price */
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0)
}
/**
* Complex function with detailed documentation
* @param name - User name
* @returns Greeting message
*/
function greet(name: string): string {
return `Hello, ${name}`
}❌ 错误写法:
typescript
/**
* User ID
*/
const userId = 123
/**
* Calculates the total price
*/
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0)
}Rule: Object key ordering - shorthand properties first
规则:对象键排序 - 简写属性优先
Shorthand properties in objects should be ordered before regular properties.
对象中的简写属性应排在常规属性之前。
Examples
示例
✅ Correct:
typescript
const user = {
age,
name,
city: 'New York',
country: 'USA'
}
const config = {
isActive,
timeout,
apiKey: 'secret-key',
baseUrl: 'https://api.example.com'
}❌ Wrong:
typescript
// Don't mix shorthand and regular properties
const user = {
city: 'New York',
age,
name,
country: 'USA'
}
const config = {
apiKey: 'secret-key',
isActive,
baseUrl: 'https://api.example.com',
timeout
}✅ 正确写法:
typescript
const user = {
age,
name,
city: 'New York',
country: 'USA'
}
const config = {
isActive,
timeout,
apiKey: 'secret-key',
baseUrl: 'https://api.example.com'
}❌ 错误写法:
typescript
// Don't mix shorthand and regular properties
const user = {
city: 'New York',
age,
name,
country: 'USA'
}
const config = {
apiKey: 'secret-key',
isActive,
baseUrl: 'https://api.example.com',
timeout
}Rule: Object keys alphabetically ordered
规则:对象键按字母顺序排序
Object keys should be ordered alphabetically, with shorthand properties grouped first (also alphabetically).
对象键应按字母顺序排序,其中简写属性需优先分组(同样按字母顺序排列)。
Examples
示例
✅ Correct:
typescript
const user = {
age,
name,
city: 'New York',
country: 'USA'
}
const config = {
isActive,
timeout,
apiKey: 'secret-key',
baseUrl: 'https://api.example.com'
}❌ Wrong:
typescript
// Keys not in alphabetical order
const user = {
name,
age,
country: 'USA',
city: 'New York'
}✅ 正确写法:
typescript
const user = {
age,
name,
city: 'New York',
country: 'USA'
}
const config = {
isActive,
timeout,
apiKey: 'secret-key',
baseUrl: 'https://api.example.com'
}❌ 错误写法:
typescript
// Keys not in alphabetical order
const user = {
name,
age,
country: 'USA',
city: 'New York'
}Rule: Multiple object keys on separate lines
规则:多个对象键分行书写
Objects with more than one key must have each key on a separate line.
包含多个键的对象必须将每个键单独写在一行。
Examples
示例
✅ Correct:
typescript
// Single key - can stay on one line
const point = { x: 10 }
// Multiple keys - separate lines
const user = {
age: 30,
name: 'John'
}
const config = {
apiKey: 'secret',
timeout: 5000
}❌ Wrong:
typescript
// Don't put multiple keys on one line
const user = { name: 'John', age: 30 }
const config = { apiKey: 'secret', timeout: 5000 }✅ 正确写法:
typescript
// Single key - can stay on one line
const point = { x: 10 }
// Multiple keys - separate lines
const user = {
age: 30,
name: 'John'
}
const config = {
apiKey: 'secret',
timeout: 5000
}❌ 错误写法:
typescript
// Don't put multiple keys on one line
const user = { name: 'John', age: 30 }
const config = { apiKey: 'secret', timeout: 5000 }Rule: Separate multiline object values with blank lines
规则:多行对象值用空行分隔
Multiline values in objects should be separated by blank lines.
对象中的多行值之间需用空行分隔。
Examples
示例
✅ Correct:
typescript
const config = {
another: 42,
lastSimple: 'end',
simple: 'value',
array: [
'item1',
'item2'
],
complex: {
deep: 'value',
nested: true
}
}❌ Wrong:
typescript
// Don't keep multiline values together
const config = {
another: 42,
lastSimple: 'end',
simple: 'value',
array: [
'item1',
'item2'
],
complex: {
deep: 'value',
nested: true
}
}✅ 正确写法:
typescript
const config = {
another: 42,
lastSimple: 'end',
simple: 'value',
array: [
'item1',
'item2'
],
complex: {
deep: 'value',
nested: true
}
}❌ 错误写法:
typescript
// Don't keep multiline values together
const config = {
another: 42,
lastSimple: 'end',
simple: 'value',
array: [
'item1',
'item2'
],
complex: {
deep: 'value',
nested: true
}
}Rule: No trailing commas
规则:不使用尾随逗号
Never use trailing commas in arrays, objects, or other structures.
绝对不要在数组、对象或其他结构中使用尾随逗号。
Examples
示例
✅ Correct:
typescript
const items = [
'first',
'second',
'third'
]
const user = {
age: 30,
city: 'New York',
name: 'John'
}❌ Wrong:
typescript
// Don't use trailing commas
const items = [
'first',
'second',
'third',
]
const user = {
age: 30,
city: 'New York',
name: 'John'
}✅ 正确写法:
typescript
const items = [
'first',
'second',
'third'
]
const user = {
age: 30,
city: 'New York',
name: 'John'
}❌ 错误写法:
typescript
// Don't use trailing commas
const items = [
'first',
'second',
'third',
]
const user = {
age: 30,
city: 'New York',
name: 'John'
}Rule: Separate multiline blocks with blank lines
规则:多行代码块用空行分隔
Multiline blocks (if/else, loops, try/catch, functions, etc.) should be separated from other code with blank lines, unless they are at the start or end of a parent block.
多行代码块(if/else、循环、try/catch、函数等)应与其他代码用空行分隔,除非它们位于父代码块的开头或结尾。
Examples
示例
✅ Correct:
typescript
function processUser(user: User) {
const isValid = validateUser(user)
if (isValid) {
console.log('Valid user')
saveToDatabase(user)
}
return isValid
}
const result = calculate()
for (const item of items) {
processItem(item)
updateCounter(item)
}
const total = getTotal()❌ Wrong:
typescript
// Don't keep multiline blocks together with other code
function processUser(user: User) {
const isValid = validateUser(user)
if (isValid) {
console.log('Valid user')
saveToDatabase(user)
}
return isValid
}
const result = calculate()
for (const item of items) {
processItem(item)
updateCounter(item)
}
const total = getTotal()Note: Blank lines at the start or end of parent blocks are not needed:
typescript
// ✅ No blank line needed after opening brace
function example() {
const value = 10
if (value > 5) {
doSomething()
}
// ✅ No blank line needed before closing brace
}✅ 正确写法:
typescript
function processUser(user: User) {
const isValid = validateUser(user)
if (isValid) {
console.log('Valid user')
saveToDatabase(user)
}
return isValid
}
const result = calculate()
for (const item of items) {
processItem(item)
updateCounter(item)
}
const total = getTotal()❌ 错误写法:
typescript
// Don't keep multiline blocks together with other code
function processUser(user: User) {
const isValid = validateUser(user)
if (isValid) {
console.log('Valid user')
saveToDatabase(user)
}
return isValid
}
const result = calculate()
for (const item of items) {
processItem(item)
updateCounter(item)
}
const total = getTotal()注意: 父代码块开头或结尾的空行并非必需:
typescript
// ✅ 左大括号后无需空行
function example() {
const value = 10
if (value > 5) {
doSomething()
}
// ✅ 右大括号前无需空行
}Rule: Nested function calls as arguments on separate lines
规则:嵌套函数调用作为参数时分行书写
Exception to the "No function calls as arguments" rule: In rare cases (e.g., validator schemas, DSL configurations) when using a function call as an argument is necessary for readability, parameters should be on separate lines.
“函数参数中不直接调用函数”规则的例外情况:在极少数场景(如验证器 schema、DSL 配置)中,若为了可读性必须将函数调用作为参数使用,则参数需单独写在一行。
Examples
示例
✅ Correct:
typescript
// Validator schemas - rare exception
const schema = v.string(
v.array()
)
const userSchema = v.object(
v.optional(
v.string()
)
)
const pipeline = pipe(
transform(config)
)❌ Wrong:
typescript
// Don't keep nested function calls on the same line
const schema = v.string(v.array())
const userSchema = v.object(v.optional(v.string()))
const pipeline = pipe(transform(config))Note: Prefer extracting to variables in most cases. Use this exception sparingly.
✅ 正确写法:
typescript
// Validator schemas - rare exception
const schema = v.string(
v.array()
)
const userSchema = v.object(
v.optional(
v.string()
)
)
const pipeline = pipe(
transform(config)
)❌ 错误写法:
typescript
// Don't keep nested function calls on the same line
const schema = v.string(v.array())
const userSchema = v.object(v.optional(v.string()))
const pipeline = pipe(transform(config))注意: 大多数情况下优先提取到变量中。请谨慎使用此例外情况。