typescript について
typescript は、厳格な型付け、プロジェクト構成、ツール、テスト、CI 品質チェックの規約と例を提供するスキルです。一貫した TypeScript 開発手法の導入や維持に役立ちます。
主な機能
- 01厳格な TypeScript 設定
- 02プロジェクト構成の提案
- 03ESLint と Prettier の設定
- 04Jest テストの例
- 05型安全なパターンと検証
- 06コミット前および CI のチェック
活用シーン
- 01TypeScript プロジェクトの品質チェック設定
- 02アプリケーションサービスのテスト作成
- 03結果型や ID 型の安全なパターン選択
- 04ステージ済み変更のチェック
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ alinaqi/ maggy --skill typescriptインストール後、Claude Code で/typescriptを入力して読み込まれたか確認します。
詳細
TypeScript スキル
Strict モード(必須)
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
プロジェクト構成
project/
├── src/
│ ├── core/ # Pure business logic
│ │ ├── types.ts # Domain types/interfaces
│ │ ├── services/ # Pure functions
│ │ └── index.ts # Public API
│ ├── infra/ # Side effects
│ │ ├── api/ # HTTP handlers
│ │ ├── db/ # Database operations
│ │ └── external/ # Third-party integrations
│ └── utils/ # Shared utilities
├── tests/
│ ├── unit/
│ └── integration/
├── package.json
├── tsconfig.json
└── CLAUDE.md
ツール(必須)
// package.json scripts
{
"scripts": {
"lint": "eslint src/ --ext .ts,.tsx",
"typecheck": "tsc --noEmit",
"test": "jest",
"test:coverage": "jest --coverage",
"format": "prettier --write 'src/**/*.ts'"
}
}
// eslint.config.js
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{
rules: {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-function-return-type': 'error',
'max-lines-per-function': ['error', 20],
'max-depth': ['error', 2],
'max-params': ['error', 3],
}
}
);
Jest によるテスト
// tests/unit/services/user.test.ts
import { calculateTotal } from '../../../src/core/services/pricing';
describe('calculateTotal', () => {
it('returns sum of item prices', () => {
// Arrange
const items = [{ price: 10 }, { price: 20 }];
// Act
const result = calculateTotal(items);
// Assert
expect(result).toBe(30);
});
it('returns zero for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
it('throws on invalid item', () => {
expect(() => calculateTotal([{ invalid: 'item' }])).toThrow();
});
});
GitHub Actions
name: TypeScript Quality Gate
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Type Check
run: npm run typecheck
- name: Test with Coverage
run: npm run test:coverage
- name: Coverage Threshold (80%)
run: npm run test:coverage -- --coverageThreshold='{"global":{"branches":80,"functions":80,"lines":80,"statements":80}}'
コミット前フック
Husky + lint-staged を使用します:
npm install -D husky lint-staged
npx husky init
// package.json
{
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
}
# .husky/pre-commit
npx lint-staged
npx tsc --noEmit
npm run test -- --onlyChanged --passWithNoTests
コミットのたびに次を実行します:
- ステージングされたファイルに対する ESLint + Prettier
- プロジェクト全体の型チェック
- 変更されたファイルのみを対象とするテスト
型のパターン
結果には判別可能なユニオンを使用
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function parseUser(data: unknown): Result<User> {
// Type-safe error handling without exceptions
}
ID にはブランド型を使用
type UserId = string & { readonly brand: unique symbol };
type OrderId = string & { readonly brand: unique symbol };
// Can't accidentally pass UserId where OrderId expected
function getOrder(orderId: OrderId): Order { ... }
リテラルには const アサーションを使用
const STATUSES = ['pending', 'active', 'closed'] as const;
type Status = typeof STATUSES[number]; // 'pending' | 'active' | 'closed'
実行時の検証には Zod を使用
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
});
type User = z.infer<typeof UserSchema>;
TypeScript のアンチパターン
- ❌
any型:unknownを使用して絞り込む - ❌ 型アサーション(
as):型ガードを使用する - ❌ 非 null アサーション(
!):null を明示的に処理する - ❌ 説明のない
@ts-ignore - ❌ Enum:const オブジェクトまたはユニオン型を使用する
- ❌ データにクラスを使用する:インターフェース/型を使用する
- ❌ デフォルトエクスポート:名前付きエクスポートを使用する
コメント
Markdown 対応