编辑 | blame | 历史 | 原始文档

---
paths:
- "**/*.ts"

- "**/*.vue"

TypeScript 前端开发规则

基于 ECC TypeScript 规则扩展,适配 Vue Vben Admin 项目。

类型定义

禁止 any

// ❌ 错误:使用 any
function handleData(data: any) {
  return data.value;
}

// ✅ 正确:使用具体类型
interface DataType {
  value: string;
}

function handleData(data: DataType) {
  return data.value;
}

// ✅ 正确:使用 unknown + 类型守卫
function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  return '未知错误';
}

import type

// ✅ 正确:类型导入使用 import type
import type { UserInfo } from '#/api/system/user';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

// ❌ 错误:普通导入类型
import { UserInfo } from '#/api/system/user';

接口定义

// ✅ 正确:实体接口
export namespace UserApi {
  export interface User {
    id?: number;
    username: string;
    nickname?: string;
    status: number;
  }
}

// ✅ 正确:Props 接口
interface Props {
  userId: number;
  userName?: string;
}

const props = withDefaults(defineProps<Props>(), {
  userName: '',
});

不可变性

// ❌ 错误:直接修改 props
props.userName = 'new name';

// ✅ 正确:使用 emit 更新
emit('update:userName', 'new name');

// ✅ 正确:使用展开运算符
const newUser = { ...user, name: 'new name' };

错误处理

// ✅ 正确:async/await + try-catch
async function loadUser(id: number) {
  try {
    const user = await getUser(id);
    return user;
  } catch (error: unknown) {
    if (error instanceof Error) {
      message.error(error.message);
    }
    throw error;
  }
}

路径别名

// ✅ 正确:使用 # 别名
import { getUser } from '#/api/system/user';
import DictTag from '#/components/dict-tag/dict-tag.vue';

// ❌ 错误:使用相对路径
import { getUser } from '../../../api/system/user';

组件命名

// ✅ 正确:组件文件名 PascalCase
UserList.vue
DictTag.vue
TableAction.vue

// ✅ 正确:定义组件名
defineOptions({ name: 'UserList' });

控制台输出

// ❌ 禁止:console.log 在生产代码中
console.log('debug info');

// ✅ 正确:使用日志库或移除
// 生产环境移除所有调试输出