name: strict-typescript-mode
description: 强制执行TypeScript最佳实践,在编写代码时。自动为TypeScript项目启用严格类型,防止any使用,并推荐泛型约束。在TS/TSX文件、新功能、代码审查上激活。
严格TypeScript模式
此技能基于2025年State-of-the-Art Guide强制执行TypeScript最佳实践。
何时激活
- 当处理
.ts或.tsx文件时 - 在新功能实现中
- 在代码审查期间
- 当将JavaScript重构为TypeScript时
严格规则
1. 切勿使用any而未文档化
// 禁止
function process(data: any) { ... }
// 允许(有正当理由)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// 理由:外部API返回未类型化的数据,在运行时验证
function processExternal(data: any) { ... }
// 更好:使用unknown和类型守卫
function process(data: unknown): ProcessedData {
if (!isValidData(data)) throw new Error('Invalid data');
return data as ProcessedData;
}
2. 公共API的显式类型
// 禁止:导出上的隐式返回类型
export const calculate = (x, y) => x + y;
// 要求:显式类型
export const calculate = (x: number, y: number): number => x + y;
// 对于React组件
interface ButtonProps {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary';
}
export const Button = ({ label, onClick, variant = 'primary' }: ButtonProps) => { ... };
3. 使用泛型约束
// 禁止:无约束泛型
function getValue<T>(obj: T, key: string) {
return obj[key]; // 错误
}
// 要求:约束泛型
function getValue<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
4. 利用工具类型
// 代替重复:
interface UserBase { name: string; email: string; }
interface UserCreate { name: string; email: string; }
interface UserUpdate { name?: string; email?: string; }
// 使用工具类型:
interface User { id: string; name: string; email: string; createdAt: Date; }
type UserCreate = Omit<User, 'id' | 'createdAt'>;
type UserUpdate = Partial<Pick<User, 'name' | 'email'>>;
5. 只读用于不可变性
interface Config {
readonly apiUrl: string;
readonly timeout: number;
}
// 对于数组
const items: readonly string[] = ['a', 'b'];
// 或
const items: ReadonlyArray<string> = ['a', 'b'];
6. 常量断言用于字面量
// 无常量断言
const STATUS = { ACTIVE: 'active', INACTIVE: 'inactive' };
// 类型:{ ACTIVE: string; INACTIVE: string }
// 有常量断言
const STATUS = { ACTIVE: 'active', INACTIVE: 'inactive' } as const;
// 类型:{ readonly ACTIVE: "active"; readonly INACTIVE: "inactive" }
7. 区分联合用于状态
// 代替可选属性:
interface Response {
data?: Data;
error?: Error;
loading?: boolean;
}
// 使用区分联合:
type Response =
| { status: 'loading' }
| { status: 'success'; data: Data }
| { status: 'error'; error: Error };
推荐的tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
}
}
编辑前检查清单
- [ ] 没有
any而未文档化理由 - [ ] 导出上的显式类型
- [ ] 适用时的泛型约束
- [ ] 使用工具类型代替重复
- [ ] 需要不可变性时的只读属性
- [ ] 用于状态的区分联合
违规时
- 发出警告并提供具体改进建议
- 显示正确方法的代码示例
- 链接到TypeScript手册以处理复杂情况
例外(需要文档)
- 遗留代码迁移(临时)
- 第三方库互操作
- 性能关键热点路径(有基准测试证据)