mirror-types
Mirror Types to Sever Dependencies
Overview
When you depend on types from external packages, changes to those types can break your code. Mirroring types - creating your own local copies of external types - severs this dependency. This is useful when you only need a subset of external types or when you want to insulate yourself from external changes.
When to Use This Skill
- Depending on external types
- Avoiding tight coupling to external packages
- External types might change frequently
- Building adapters or wrappers
- Types are only used internally
The Iron Rule
Mirror external types when you want to sever dependencies. Define only the subset you need, insulated from external changes.
Example
// BAD: Direct dependency on external type
import { ExternalUser } from 'external-library';
interface MyService {
processUser(user: ExternalUser): void;
}
// If ExternalUser changes, your code breaks
// GOOD: Mirror the type
interface User {
id: string;
name: string;
email: string;
}
interface MyService {
processUser(user: User): void;
}
// Adapter converts external to internal type
function adaptExternalUser(external: ExternalUser): User {
return {
id: external.id,
name: external.name,
email: external.email,
};
}
Reference
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 70: Mirror Types to Sever Dependencies
More from marius-townhouse/effective-typescript-skills
precise-any-variants
Use when forced to use any. Use when any is too broad. Use when function types need any.
86narrow-any-scope
Use when any is unavoidable. Use when working with untyped libraries. Use when silencing specific type errors.
35tsdoc-comments
Use when documenting public APIs. Use when writing library code. Use when using JSDoc-style comments. Use when generating documentation. Use when explaining complex types.
33exhaustiveness-checking
Use when handling tagged unions. Use when adding new cases to discriminated unions. Use when switch statements must cover all cases.
13code-gen-independent
Use when confused about types at runtime. Use when trying to use instanceof with interfaces. Use when type errors don't prevent JavaScript output.
12tsconfig-options
Use when setting up a TypeScript project. Use when confused by type checking behavior. Use when strict mode causes unexpected errors.
11