typescript-rules
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "typescript-rules":https://skillpi.com/zh/skills/deepskill-bf83466c6fc4317c855a7c0292da238c75b4b55d2562e3010fbdfb8b0a96571c。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
TypeScript/JavaScript 编码规范工具,涵盖风格、设计模式、安全性与测试。触发条件包括 .ts/.tsx/.js/.jsx、package.json、tsconfig.json、以及 React、Next.js、Vue、Vite、Vitest、Jest 和 ESLint 相关情境。
介绍来源: third_party · softspark · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 输入和输出
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: typescript-rules
description: "TypeScript/JavaScript coding rules: style, patterns, security, testing. Triggers: .ts, .tsx, .js, .jsx, package.json, tsconfig.json, React, Next.js, Vue, Vite, Vitest, Jest, ESLint."
effort: medium
user-invocable: false
allowed-tools: ReadTypeScript/JavaScript Rules
These rules come from app/rules/typescript/ in ai-toolkit. They cover
the project's standards for coding style, frameworks, patterns,
security, and testing in TypeScript/JavaScript. Apply them when writing or
reviewing TypeScript/JavaScript code.
TypeScript Coding Style
Strict Mode
- Always use
strict: truein tsconfig.json. - Never use
any-- useunknown+ type guards instead. - Prefer
interfaceovertypefor object shapes (extendable). - Use
as constfor literal types and readonly tuples.
Naming
- PascalCase: types, interfaces, enums, classes, components.
- camelCase: variables, functions, methods, properties.
- UPPER_SNAKE: constants, env vars.
- Prefix interfaces with
Ionly if project convention requires it.
Functions
- Prefer arrow functions for callbacks and inline.
- Use
functiondeclarations for hoisted, named functions. - Max 3 parameters -- use options object beyond that.
- Always type return values for public/exported functions.
Imports
- Group: node builtins, external, internal, relative.
- Use
typeimports:import type { Foo } from './foo'. - No barrel exports unless at package boundary.
- Prefer named exports over default exports.
Types
- Use discriminated unions over class hierarchies for state.
- Use
readonlyfor arrays and objects that should not be mutated. - Use
satisfiesoperator to validate types without widening. - Prefer
unknownoveranyat API boundaries. - Use template literal types for string patterns.
Avoid
enum-- useas constobjects or union types.namespace-- use ES modules.privatekeyword -- use#private fields.- Non-null assertion
!-- use proper type narrowing. astype casting -- use type guards and narrowing.
Configuration
- Enable
noUncheckedIndexedAccessfor safer array/object access. - Enable
exactOptionalPropertyTypesto distinguishundefinedfrom missing. - Use
moduleResolution: "bundler"for modern projects. - Set
isolatedModules: truefor bundler compatibility.
TypeScript Frameworks
React
- Use function components exclusively. No class components.
- Colocate state with the component that owns it. Lift only when needed.
- Use
useCallbackanduseMemoonly when profiling shows a need. - Use
React.lazy()+ Suspense for code-splitting routes. - Avoid prop drilling past 2 levels -- use Context or state management.
Next.js (App Router)
- Default to Server Components. Add
"use client"only when needed. - Use Server Actions for mutations. Never expose internal APIs to client.
- Use
loading.tsxanderror.tsxfor streaming and error boundaries. - Fetch data in Server Components, not in useEffect on client.
- Use
revalidatePath/revalidateTagfor cache invalidation.
Express / Fastify / Hono
- Use layered architecture: route -> controller -> service -> repository.
- Validate request body/params/query with Zod middleware.
- Centralize error handling in a single error middleware.
- Use async route handlers with proper error forwarding.
- Return consistent response shapes:
{ data }or{ error }.
State Management
- Use Zustand or Jotai for client state. Redux only for complex existing apps.
- Use TanStack Query (React Query) for server state.
- Separate server state (fetched data) from client state (UI state).
- Never duplicate server data in client state stores.
ORM / Database
- Use Drizzle for new projects (SQL-like, type-safe, lightweight).
- Use Prisma for rapid prototyping (schema-first, great DX).
- Always use migrations. Never modify schema manually in production.
- Use transactions for multi-table operations.
Node.js Runtime
- Use
node:prefix for built-in modules:import { readFile } from 'node:fs/promises'. - Prefer
fetch(built-in since Node 18) over axios/node-fetch. - Use
structuredClone()for deep cloning. - Set
"type": "module"in package.json for ESM.
Monorepo
- Use Turborepo or Nx for monorepo orchestration.
- Share types via internal packages, not copy-paste.
- Use workspace protocols:
"@org/shared": "workspace:*".
TypeScript Patterns
Error Handling
- Use Result type pattern:
{ success: true; data: T } | { success: false; error: E }. - Use Zod
.safeParse()for validation -- returns typed result, never throws. - Create domain-specific error classes extending
Errorwith error codes. - Centralize error handling in middleware, not in each handler.
- Never catch errors silently. Log or rethrow with context.
Discriminated Unions
- Use discriminated unions for state machines and polymorphic data.
- Always include a
typeorkindliteral field as discriminant. - Use
switchwith exhaustive checking (neverin default) on unions. - Prefer unions over optional fields for mutually exclusive states.
Async Patterns
- Use
async/awaiteverywhere. Never use raw.then()chains. - Use
Promise.all()for independent concurrent operations. - Use
Promise.allSettled()when some failures are acceptable. - Implement cancellation with
AbortControllerfor long operations. - Wrap callbacks in Promises at the boundary, then use async/await.
Validation
- Validate at API boundaries with Zod, Valibot, or ArkType.
- Derive TypeScript types from schemas:
z.infer<typeof Schema>. - Never trust runtime data to match TypeScript types without validation.
- Use branded types for domain primitives:
UserId,Email,Slug.
Dependency Injection
- Use constructor injection for services and repositories.
- Accept interfaces, not concrete classes, in constructors.
- Use factory functions for creating configured instances.
- Avoid service locator pattern and global singletons.
Immutability
- Use
readonlyon interface properties by default. - Use
Readonly<T>,ReadonlyArray<T>for function parameters. - Use
Object.freeze()only for runtime safety in config objects. - Prefer spread/map/filter over mutating methods (push, splice).
Type Guards
- Use
isreturn type for custom type guards:(x: unknown): x is User. - Use
inoperator for discriminating object shapes. - Prefer
satisfiesoverasfor type validation without casting. - Use assertion functions (
asserts x is T) for preconditions.
TypeScript Security
Input Validation
- Validate ALL request data with Zod/Valibot at API boundary.
- Use
.strip()/.strict()to reject unexpected fields. - Validate URL params and query strings, not just request bodies.
- Never pass raw user input to
eval(),Function(), or template literals in SQL.
XSS Prevention
- Use framework auto-escaping (React JSX, Angular templates).
- Never use
dangerouslySetInnerHTMLwithout DOMPurify sanitization. - Sanitize user content before storing, not just before rendering.
- Set CSP headers:
default-src 'self'; script-src 'self'.
Authentication
- Use
httpOnly,secure,sameSite: 'strict'for auth cookies. - Implement CSRF protection for cookie-based auth (double-submit or token).
- Use short-lived JWTs (15min) with refresh token rotation.
- Validate JWT signature, expiration, issuer, and audience on every request.
SQL / NoSQL Injection
- Use parameterized queries with Drizzle/Prisma/TypeORM. Never concatenate.
- For raw queries, use tagged template literals:
sql\SELECT * FROM users WHERE id = ${id}``. - Validate and cast IDs to expected types (UUID, integer) before queries.
- Use ORM query builders for dynamic filters.
Dependency Security
- Run
npm auditin CI. Fail on high/critical vulnerabilities. - Use
npm audit signaturesto verify package provenance. - Pin exact versions with lockfile. Review lockfile changes in PRs.
- Avoid packages with postinstall scripts unless trusted.
Secrets
- Use
process.envwith Zod validation for env vars. - Never import
.envfiles in production -- use platform env injection. - Never log
req.headers.authorizationor session tokens. - Use
crypto.timingSafeEqual()for comparing secrets.
Server Hardening
- Set security headers: HSTS, X-Content-Type-Options, X-Frame-Options.
- Use
helmetmiddleware in Express, built-in security in Fastify. - Implement rate limiting on all endpoints (
express-rate-limit,@fastify/rate-limit). - Disable
X-Powered-Byheader. Do not expose server technology.
File Uploads
- Validate file type by magic bytes, not just extension or MIME type.
- Set maximum file size limits on the server.
- Store uploads outside the web root. Serve through a proxy with CDN.
- Generate random filenames. Never use user-provided filenames for storage.
TypeScript Testing
Framework
- Use Vitest for new projects (faster, native ESM, TypeScript-first).
- Use Jest only for existing projects already using it.
- Use Playwright for E2E browser testing.
- Use Supertest or built-in fetch for API integration tests.
File Naming
- Test files:
*.test.tsor*.spec.tscolocated with source. - Test utilities:
tests/helpers/ortests/utils/. - Fixtures:
tests/fixtures/with typed factory functions.
Structure
- Use
describefor grouping by function/class/feature. - Use
itwith behavior descriptions:it('returns 404 when user not found'). - Avoid deeply nested
describeblocks (max 2 levels). - Use
beforeEachfor setup, avoidbeforeAllfor mutable state.
Type-Safe Mocking
- Use
vi.fn()with type parameters:vi.fn<[string], Promise<User>>(). - Use
vi.mock()for module-level mocking. - Prefer dependency injection over module mocking for testability.
- Use
vi.spyOn()for partial mocks on existing objects.
React/Component Testing
- Use React Testing Library. Query by role, label, text -- not test IDs.
- Use
userEventoverfireEventfor realistic user interactions. - Test behavior and rendered output, not component internals.
- Use
renderHookfor testing custom hooks in isolation.
Assertions
- Use
expect().toBe()for primitives,expect().toEqual()for objects. - Use
expect().toMatchInlineSnapshot()for complex output verification. - Avoid
toBeTruthy/toBeFalsy-- use specific matchers. - Use
expect().rejects.toThrow()for async error testing.
Async Testing
- Always
awaitasync operations. Never usedonecallback. - Use
vi.useFakeTimers()for timer-dependent code. - Use
waitForfrom Testing Library for async DOM updates.
Performance
- Run tests in parallel (Vitest default). Isolate state to enable this.
- Use
vi.mock()for heavy dependencies (DB, network) in unit tests. - Keep unit test suite under 30 seconds.
版本历史
-
v6.2.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
原版更新说明
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
原版更新说明
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
原版更新说明
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供全面且深入的TypeScript/JavaScript编码规范,覆盖风格、框架、模式、安全性和测试五大核心领域
- 内容基于现代最佳实践,适用于React、Next.js、Express、Zod、Vitest等主流技术栈,实用价值极高
亮点
- 触发词精准完整,明确列出.ts、.tsx、.js、.jsx、package.json、tsconfig.json等文件类型
- 覆盖React、Next.js、Vue、Vite、Vitest、Jest、ESLint等主流框架和工具,边界清晰无歧义
待提升项
-
缺少When to Use/示例章节 原报告严重程度:轻微
文档结构清晰但缺少When to Use说明和端到端使用示例
改进建议:建议补充When to Use章节说明适用场景,并添加1-2个端到端示例展示如何在实际项目中应用这些规范
亮点
- 文档结构清晰,分为TypeScript Coding Style、Frameworks、Patterns、Security、Testing五大逻辑模块
- 每个模块内部条目分明,使用二级标题和项目符号组织,易于阅读和理解
亮点
- 所有建议均基于业界公认的最佳实践,工具来源明确(Zod、Vitest、Drizzle等)
- 参数建议具体且合理(如strict: true、moduleResolution: 'bundler'等),覆盖主要异常处理场景
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。