refactoring-typescript
Skill9 starsChanged 8 months agoMITView on GitHub
TypeScript refactoring: SOLID principles, DRY, type safety improvements, and eliminating code smells
In this repository31 other files it gives its agents.
- git-workflow-releaseSkill
- skill-authoring-generalSkill
- git-workflow-releaseSkill
- skill-authoring-generalSkill
- accessibility-generalSkill
- accessibility-react-nativeSkill
- architecture-generalSkill
- architecture-pythonSkill
- assistant-rocky-lti-assistSkill
- assistant-ucd-mobileSkill
- ci-cd-github-actionsSkill
- code-review-generalSkill
- code-review-pythonSkill
- code-review-typescriptSkill
- data-science-pythonSkill
- design-frontendSkill
- documentation-projectSkill
- documentation-readmeSkill
- git-workflow-generalSkill
- git-workflow-monorepoSkill
- git-workflow-pr-generatorSkill
- git-workflow-releaseSkill
- infrastructure-terraformSkill
- package-management-pythonSkill
- project-management-jiraSkill
- security-generalSkill
- skill-authoring-generalSkill
- testing-generalSkill
- testing-javaSkill
- testing-pythonSkill
- testing-typescriptSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
13 rules. About 0 are common, 6 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 9
Ensure existing tests are green.
- Very specific: line 11
Run tsc --noEmit and eslint after each change.
- Distinctive: line 12
Never change behavior while refactoring — if you are, that's a feature.
- Very specific: line 17
Use interface for object shapes.
- Very specific: line 18
Prefer readonly arrays and properties when data should not be mutated.
- Very specific: line 41
Avoid abbreviations except universally understood ones (url, id, ctx).
- Distinctive: line 52
Single Responsibility: if the function name needs "and", split it.
- Very specific: line 53
Open/Closed: use strategy pattern over if/else chains that grow over time.
- Very specific: line 166
Delete unused exports, parameters, branches, and commented-out code — don't leave // removed comments.
- Very specific: line 167
Use tsc --noEmit and your linter's no-unused-vars / @typescript-eslint/no-unused-vars to surface dead code automatically.
- Distinctive: line 170
Don't refactor code you don't understand yet — read it first.
- Distinctive: line 171
Don't refactor when no tests exist and writing them isn't feasible right now.
- Distinctive: line 172
Don't refactor stable, rarely-touched code just for style — the risk/reward is poor.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Refactoring — TypeScript
Before You Start
- Ensure existing tests are green. If there are no tests, write them first.
- Refactor in small, committed steps — one change at a time.
- Run
tsc --noEmitandeslintafter each change. - Never change behavior while refactoring — if you are, that's a feature.
Type Safety
- Replace
anywith proper types orunknown+ type guard. - Enable
strict: trueintsconfig.jsonif not set. - Use
interfacefor object shapes;typefor unions and intersections. - Prefer
readonlyarrays and properties when data should not be mutated.
// Before
function process(data: any) { ... }
// After
function process(data: unknown) {
if (!isOrderData(data)) throw new TypeError('Invalid order data');
...
}// Prefer discriminated unions over boolean flags
type Result =
| { status: 'ok'; value: string }
| { status: 'error'; message: string };Naming
- Names should say what, not how. Rename when you have to read the body to understand the call site.
- Boolean variables and functions: prefix with
is,has,can,should. - Avoid abbreviations except universally understood ones (
url,id,ctx).
// Before
const d = users.filter(u => u.a);
// After
const activeUsers = users.filter(user => user.isActive);SOLID Principles
- Single Responsibility: if the function name needs "and", split it.
- Open/Closed: use strategy pattern over
if/elsechains that grow over time. - Liskov Substitution: subtypes must be substitutable without breaking callers.
- Interface Segregation: split large interfaces; callers should not depend on methods they don't use.
- Dependency Inversion: accept interfaces, not concrete classes.
Common Smells → Fixes
| Smell | Fix |
| Long parameter list (4+) | Extract to typed options object |
| Deep nesting | Early returns / guard clauses |
| Magic numbers/strings | Named constants or enums |
| Copy-pasted logic | Extract to named function or generic utility |
| Large file (300+ lines) | Split into focused modules |
| Boolean parameter | Two functions, or discriminated union |
| Comments explaining what | Rename so it's self-evident |
| Mutable shared state | Encapsulate behind a function; return new values |
| Callback pyramid | Async/await with named steps |
Example: Guard Clauses
// Before — deep nesting
function processOrder(order: Order) {
if (order) {
if (order.items.length > 0) {
if (order.status === 'pending') {
// actual logic...
}
}
}
}
// After — guard clauses
function processOrder(order: Order) {
if (!order) return;
if (order.items.length === 0) return;
if (order.status !== 'pending') return;
// actual logic...
}Example: Extract Function
// Before — inline logic that hides intent
const total = items.reduce((sum, item) => {
const discounted = item.price * (1 - item.discountRate);
return sum + discounted * item.quantity;
}, 0);
// After — named helpers reveal intent
const lineTotal = (item: Item) => item.price * (1 - item.discountRate) * item.quantity;
const total = items.reduce((sum, item) => sum + lineTotal(item), 0);Example: Options Object
// Before
function createUser(name: string, age: number, role: string, active: boolean) { ... }
// After
interface CreateUserOptions {
name: string;
age: number;
role: string;
active: boolean;
}
function createUser(options: CreateUserOptions) { ... }Example: Async Flattening
// Before — callback pyramid / chained .then
fetchUser(id)
.then(user => fetchOrders(user.id)
.then(orders => fetchInvoices(orders[0].id)
.then(invoices => process(user, orders, invoices))));
// After — sequential async/await
async function loadUserData(id: string) {
const user = await fetchUser(id);
const orders = await fetchOrders(user.id);
const invoices = await fetchInvoices(orders[0].id);
return process(user, orders, invoices);
}Example: Strategy Pattern
// Before — growing switch that requires editing this function for each new type
function calculateShipping(method: string, weight: number): number {
if (method === 'standard') return weight * 0.5;
if (method === 'express') return weight * 1.2;
if (method === 'overnight') return weight * 2.5;
throw new Error('Unknown method');
}
// After — register new strategies without touching existing code
type ShippingStrategy = (weight: number) => number;
const shippingStrategies: Record<string, ShippingStrategy> = {
standard: w => w * 0.5,
express: w => w * 1.2,
overnight: w => w * 2.5,
};
function calculateShipping(method: string, weight: number): number {
const strategy = shippingStrategies[method];
if (!strategy) throw new Error(`Unknown shipping method: ${method}`);
return strategy(weight);
}Dead Code
- Delete unused exports, parameters, branches, and commented-out code — don't leave
// removedcomments. - Use
tsc --noEmitand your linter'sno-unused-vars/@typescript-eslint/no-unused-varsto surface dead code automatically.
When Not to Refactor
- Don't refactor code you don't understand yet — read it first.
- Don't refactor when no tests exist and writing them isn't feasible right now.
- Don't refactor stable, rarely-touched code just for style — the risk/reward is poor.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

