TypeScript 常用语法与编码规范文档

0 阅读2分钟

TypeScript 常用语法与编码规范文档

1. 基础语法规范

1.1 类型注解

明确类型定义:避免隐式类型推断歧义

  // 推荐
  const count: number = 0;
  let name: string = 'Alice';
  // 禁止
  const age = 18; // 未显式声明类型(除非类型推断足够明确)

1.2 接口与类型别名

  • 接口 定义对象结构
 // 推荐
interface User {
  name: string;
  age: number;
}
// 禁止
type User = { name: string; age: number; }; // 对象类型建议用interface

1.3 泛型

  • 通用函数/类定义
 // 推荐
function identity<T>(arg: T): T {
  return arg;
}
// 禁止
function identity(arg: any): any { ... } // 避免any类型

1.4 可选链与空值合并

  • 安全访问属性
 // 推荐
const value = obj?.prop ?? 'default';
// 禁止
const value = obj && obj.prop || 'default'; // 可读性差

1.5 枚举

  • 常量枚举定义
 // 推荐
enum Status {
  Active = 1,
  Inactive = 2
}
// 禁止
const Status = { Active: 1, Inactive: 2 }; // 非TS最佳实践

1.6 类型断言

  • 明确类型转换
 // 推荐
const div = document.getElementById('app') as HTMLDivElement;
// 禁止
const div = <HTMLDivElement>document.getElementById('app'); // 避免使用angle-bracket语法

1.7 Union & Intersection 类型

  • 类型合并与交集
 // 推荐
type Shape = Circle | Square;
type ResizableShape = Shape & { resize(): void };
// 禁止
type Shape = any; // 避免过度使用any

1.8 只读与可选属性

  • 对象类型约束
 // 推荐
interface User {
  readonly id: number;
  name?: string; // 可选属性
}
// 禁止
interface User {
  id: number; // 缺少readonly导致意外修改
}

1.9 响应式类型定义(Vue3)

  • 结合组合式 API 的类型
 // 推荐
import { ref } from 'vue';
const count = ref<number>(0);
// 禁止
const count = ref(0); // 未明确基础类型
  1. 进阶语法规范

2.1 never 类型

  • 表示永不返回的函数
 // 推荐
function error(message: string): never {
  throw new Error(message);
}

2.2 类型守卫

  • 类型窄化安全判断
function isString(value: any): value is string {
  return typeof value === 'string';
}

2.3 映射类型

  • 批量修改属性类型
type ReadOnly<T> = {
  readonly [P in keyof T]: T[P];
};

2.4 类装饰器

  • 类扩展规范
function Serializable(target: Function) {
  // 装饰器逻辑
}
@Serializable
class User {}
  1. 禁止事项

3.1 避免 any 类型

  • 严格类型检查
  • typescript
  • // 禁止`` let obj: any = {}; // 除非绝对必要

3.2 禁用 Object.assign

  • 使用解构或 接口 替代
 // 推荐
const merged = { ...obj1, ...obj2 };
// 禁止
const merged = Object.assign({}, obj1, obj2); // 可读性差

3.3 禁止类型擦除

  • 避免函数参数类型丢失
 // 推荐
function log<T>(arg: T): T {
  console.log(arg);
  return arg;
}
// 禁止
function log(arg: any): any { ... } // 类型信息丢失

3.4 禁用隐式any

  • 启用严格模式
 // tsconfig.json配置
{
  "compilerOptions": {
    "noImplicitAny": true
  }
}
  1. Vue3 + TS 规范

4.1 组件 Props 定义

  • 使用 defineProps 接口
 // <script setup>
interface Props {
  title: string;
  count?: number;
}
const props = defineProps<Props>();

4.2 Emits 类型定义

  • 明确事件类型
const emits = defineEmits<{
  (e: 'update', value: string): void;
}>();

4.3 响应式数据类型

  • ref/reactive 显式类型
const user = ref<User>({
  id: 1,
  name: 'Alice'
});
  1. 工具链配置

推荐配置以下 ESLint 规则:

  • @typescript-eslint/no-explicit-any 禁止any类型
  • @typescript-eslint/explicit-module-boundary-types 函数参数返回类型必须显式声明
  • @typescript-eslint/ban-types 禁用对象类型作为函数参数
  • @typescript-eslint/no-non-null-assertion 禁止!类型断言(除非绝对必要)
  • @typescript-eslint/no-unsafe-assignment 禁止不安全赋值

``注意:TS项目需在 tsconfig.json 中启用以下基础配置:

 {
   "compilerOptions": {
     "strict": true,
     "noImplicitAny": true,
     "module": "ESNext",
     "target": "ES2017"
   }
 }