Skill站外收录 @skilllib/skill-2014279409652412417
typescript-conventions
规范前端 TypeScript代码的编写实践,涵盖文件命名、模块导入、类型安全、异步处理与错误捕获等核心环节,强调使用接口和类型守卫替代 any,强制 await 和 try catch,统一采用 kebab-case 文件名及带花括号的控制语句,提升代码可维护性与协作一致性。
测试与安全 AI 技能
Skills.MD
# TypeScript Conventions
## Style & Formatting
- Follow `.editorconfig` and ESLint + Prettier config strictly
- Run `npm run format` before committing
- **Minimize diffs**: Change only what's necessary, preserve existing formatting and structure
- Match surrounding code style exactly
## File Naming
- Use **kebab-case** for files and directories
- Component files: `user-profile.svelte`
- TypeScript files: `api-client.ts`, `user-service.ts`
- Test files: `user-service.test.ts` or `user-service.spec.ts`
## Imports
### Prefer Named Imports
```typescript
// ✅ Good: Named imports
import { UserService, type User } from '$lib/services/user-service';
import { formatDate, formatNumber } from '$lib/utils/formatters';
// ❌ Avoid: Namespace imports (except allowed exceptions)
import * as utils from '$lib/utils';
```
### Allowed Namespace Imports
```typescript
// ✅ Allowed: shadcn-svelte components
import * as Dialog from '$comp/ui/dialog';
import * as DropdownMenu from '$comp/ui/dropdown-menu';
// ✅ Allowed: Barrel exports
import * as Field from '$comp/ui/field';
```
## Type Safety
### Avoid `any`
```typescript
// ❌ Bad
function processData(data: any) { ... }
// ✅ Good: Use interfaces/types
interface UserData {
id: string;
name: string;
email: string;
}
function processData(data: UserData) { ... }
// ✅ Good: Use unknown for truly unknown data
function parseResponse(data: unknown): UserData {
if (isUserData(data)) {
return data;
}
throw new Error('Invalid data format');
}
```
### Type Guards
```typescript
function isUserData(data: unknown): data is UserData {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'name' in data &&
'email' in data
);
}
// Discriminated unions
type ApiResponse =
| { status: 'success'; data: UserData }
| { status: 'error'; error: string };
function handleResponse(response: ApiResponse) {
if (response.status === 'success') {
// TypeScript knows response.data exists
return response.data;
}
// TypeScript knows response.error exists
throw new Error(response.error);
}
```
## Promise Handling
### Always Await
```typescript
// ✅ Good: Always await
const user = await fetchUser(id);
const [users, projects] = await Promise.all([fetchUsers(), fetchProjects()]);
// ❌ Bad: Fire and forget without handling
fetchUser(id); // Exception is lost!
```
### Error Handling
```typescript
// ✅ Good: try/catch with proper typing
async function loadUser(id: string): Promise<User | null> {
try {
const response = await api.get<User>(`/users/${id}`);
return response.data;
} catch (error) {
if (error instanceof ApiError) {
console.error('API Error:', error.message);
}
return null;
}
}
```
## Control Statements
All single-line control statements need braces:
```typescript
// ✅ Good: Always use braces
if (condition) {
doSomething();
}
for (const item of items) {
process(item);
}
// ❌ Bad: No braces
if (condition) doSomething();
```
## Interface Naming
Follow HTTP verb prefixes for API-related types:
```typescript
// Request/Response interfaces
interface PostOrganizationRequest {
name: string;
billing_email: string;
}
interface GetOrganizationParams {
id: string;
}
interface PatchUserRequest {
name?: string;
email?: string;
}
```
## Export Patterns
```typescript
// Named exports preferred
export function createUser(data: CreateUserRequest): Promise<User> { ... }
export type { User, CreateUserRequest };
// Re-export from barrel files
// src/lib/features/users/index.ts
export { createUser, updateUser, deleteUser } from './api.svelte';
export type { User, CreateUserRequest } from './models';
```
## Modern ES6+ Features
```typescript
// Template literals
const message = `Hello, ${user.name}!`;
// Destructuring
const { id, name, email } = user;
const [first, ...rest] = items;
// Nullish coalescing
const displayName = user.nickname ?? user.name ?? 'Anonymous';
// Optional chaining
const city = user?.address?.city;
// Object shorthand
const data = { id, name, createdAt: new Date() };
```
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「typescript-conventions」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次