协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
typescript-refactoring-patterns【开发与工程】Expert TypeScript refactoring patterns for cleaner, type-safe code
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
as castsas const for immutable literal typesextends constraints over anyWhen you see multiple boolean flags, refactor to discriminated union:
// Before
interface User {
isAdmin: boolean;
isGuest: boolean;
permissions?: string[];
}
// After
type User =
| { role: 'admin'; permissions: string[] }
| { role: 'guest' }
| { role: 'member'; permissions: string[] };
When you see switch statements on type, use the strategy pattern:
// Before
function process(item: Item) {
switch (item.type) {
case 'a': return processA(item);
case 'b': return processB(item);
}
}
// After
const processors: Record<ItemType, (item: Item) => Result> = {
a: processA,
b: processB,
};
const process = (item: Item) => processors[item.type](item);
When narrowing types, create reusable type guards:
function isNonNullable<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
// Usage
const items = array.filter(isNonNullable);
Prevent primitive obsession with branded types:
type UserId = string & { readonly brand: unique symbol };
type Email = string & { readonly brand: unique symbol };
function createUserId(id: string): UserId {
if (!isValidUuid(id)) throw new Error('Invalid user ID');
return id as UserId;
}
Watch for these patterns and refactor:
any types (replace with unknown + type guards)! (add proper checks)as (use type guards)?.?.?. (restructure data)strict: true in tsconfigsatisfies for type checking without wideningreadonly arrays and objectsunknown for external data, validate at boundaries