Double Assertions Route Through Unknown

Direct casts between shapes with no overlap fail with TS2352; routing through unknown works, but a real guard beats a double assertion.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
type LegacyRow = { id: string; packed: { value: number } };

// JSON.parse returns any, so the first cast is a plain narrowing claim
const raw = JSON.parse('{"id":"r-1","packed":{"value":42}}') as LegacyRow;
console.log('packed value:', raw.packed.value);

// Casts between shapes with no overlap are rejected outright:
// const flat = raw as { id: string; value: number }; // TS2352
// The escape hatch routes through unknown, which overlaps with both sides —
// but the compiler cannot check it, so wrong shapes silently read undefined
const flat = raw as unknown as { id: string; value: number };
console.log('flat:', flat.id, flat.value);

// Prefer a guard: verify the shape at runtime instead of asserting it
function hasValue(value: unknown): value is { id: string; value: number } {
  return typeof value === 'object' && value !== null && 'value' in value;
}

const candidate: unknown = { id: 'r-2', value: 7 };
if (hasValue(candidate)) {
  console.log('guarded value:', candidate.value);
}

console.log('guard rejects unchecked shapes:', hasValue(raw) === false);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

packed value: 42
flat: r-1 undefined
guarded value: 7
guard rejects unchecked shapes: true

Line-by-line reading

Structurally, expect the function hasValue and nothing else.

Points of care

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

The surface you program against: function hasValue(value: unknown)

Output arrives labeled — packed value:, flat:, guarded value: — when the file runs.

Key statements

return typeof value === 'object' && value !== null && 'value' in value;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `hasValue` at load time.