| name | hide-unsafe-assertions |
| description | Use when type assertions are necessary. Use when function implementations need any. Use when hiding unsafe code. |
Hide Unsafe Type Assertions in Well-Typed Functions
Overview
Keep type signatures clean; hide assertions in implementations.
If a function needs a type assertion or any internally, that's OK - as long as the public signature is correct. Users see a well-typed API; the unsafe code is contained.
When to Use This Skill
- Function implementations need type assertions
- TypeScript can't follow your logic
- Wrapping libraries with poor types
- Internal complexity, clean external API
The Iron Rule
Never compromise type signatures for implementation convenience.
Hide assertions inside well-typed functions.
Remember:
- Type signatures are your API contract
- Implementations are hidden details
- Users shouldn't see assertions
- Test assertion-heavy code thoroughly
Detection: Exposed Unsafety
async function fetchPeak(peakId: string): Promise<unknown> {
return checkedFetchJSON(`/api/peaks/${peakId}`);
}
const peak = await fetchPeak('denali') as MountainPeak;
Better: Hide the Assertion
async function fetchPeak(peakId: string): Promise<MountainPeak> {
return checkedFetchJSON(`/api/peaks/${peakId}`) as Promise<MountainPeak>;
}
const peak = await fetchPeak('denali');
The assertion is hidden inside; callers get a clean API.
Validate Inside Hidden Assertions
async function fetchPeak(peakId: string): Promise<MountainPeak> {
const maybePeak = await checkedFetchJSON(`/api/peaks/${peakId}`);
if (!maybePeak || typeof maybePeak !== 'object' || !('name' in maybePeak)) {
throw new Error(`Invalid peak data: ${JSON.stringify(maybePeak)}`);
}
return maybePeak as MountainPeak;
}
Now the assertion has runtime backup.
When TypeScript Can't Follow
function shallowEqual(a: object, b: object): boolean {
for (const [k, aVal] of Object.entries(a)) {
if (!(k in b) || aVal !== b[k]) {
return false;
}
}
return Object.keys(a).length === Object.keys(b).length;
}
We know k in b is true, but TypeScript doesn't connect this to b[k].
Wrong Fix: Weaken the Signature
function shallowEqual(a: object, b: any): boolean {
}
shallowEqual({x: 1}, null);
Right Fix: Hide the Assertion
function shallowEqual(a: object, b: object): boolean {
for (const [k, aVal] of Object.entries(a)) {
if (!(k in b) || aVal !== (b as any)[k]) {
return false;
}
}
return Object.keys(a).length === Object.keys(b).length;
}
shallowEqual({x: 1}, null);
Type signature stays clean; assertion is narrowly scoped.
Function Overloads as Hidden Assertions
async function fetchPeak(peakId: string): Promise<MountainPeak>;
async function fetchPeak(peakId: string): Promise<unknown> {
return checkedFetchJSON(`/api/peaks/${peakId}`);
}
const denali = fetchPeak('denali');
The implementation returns unknown, but callers see MountainPeak.
Narrow Scope of Assertions
const config: Config = {
a: 1,
b: 2,
c: { key: value }
} as any;
const config: Config = {
a: 1,
b: 2,
c: { key: value as any }
};
Document Why Assertions Are Valid
function shallowEqual(a: object, b: object): boolean {
for (const [k, aVal] of Object.entries(a)) {
if (!(k in b) || aVal !== (b as any)[k]) {
return false;
}
}
return Object.keys(a).length === Object.keys(b).length;
}
Comments help future maintainers understand the assertion.
Test Thoroughly
Functions with hidden assertions need extra testing:
describe('fetchPeak', () => {
it('handles valid peak data', async () => {
const peak = await fetchPeak('denali');
expect(peak.name).toBe('Denali');
expect(peak.elevationMeters).toBe(6190);
});
it('throws on invalid data', async () => {
mockFetch({ invalid: 'data' });
await expect(fetchPeak('unknown')).rejects.toThrow('Invalid peak');
});
it('handles missing fields', async () => {
mockFetch({ name: 'Partial' });
await expect(fetchPeak('partial')).rejects.toThrow();
});
});
Pressure Resistance Protocol
1. "Just Change the Return Type"
Pressure: "Make it return unknown to avoid the assertion"
Response: That pushes unsafety to every caller.
Action: Keep clean signature; hide assertion in implementation.
2. "Assertions Are Dangerous"
Pressure: "We should avoid assertions entirely"
Response: Sometimes they're necessary. Contained and tested is OK.
Action: Hide, validate, document, and test.
Red Flags - STOP and Reconsider
- Function signatures containing
any or unknown for convenience
- Assertions scattered across calling code
- Changing signatures to avoid implementation errors
- Untested assertion-heavy code
Common Rationalizations (All Invalid)
| Excuse | Reality |
|---|
| "It's more honest" | Pushing unsafety to callers is worse |
| "Assertions are bad" | Contained assertions are fine |
| "Users can narrow" | Users shouldn't have to |
Quick Reference
function fetch(): Promise<unknown> { ... }
const data = await fetch() as Data;
function fetch(): Promise<Data> {
return api.fetch() as Promise<Data>;
}
const obj = { a: value as any };
return data as Data;
The Bottom Line
Hide unsafe code; expose clean types.
Type assertions and any types are sometimes necessary. Keep them in function implementations, not signatures. Document why they're valid. Test thoroughly.
Reference
Based on "Effective TypeScript" by Dan Vanderkam, Item 45: Hide Unsafe Type Assertions in Well-Typed Functions.