Symbol.hasInstance Extends instanceof

Give structural shapes a static Symbol.hasInstance type predicate so instanceof narrows parsed JSON to LineItem without any shared class prototype.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
// Symbol.hasInstance lets instanceof narrow shapes that share no prototype.
interface LineItem {
  readonly kind: 'line-item';
  readonly cents: number;
}

class CartEntry {
  static [Symbol.hasInstance](value: unknown): value is LineItem {
    return (
      typeof value === 'object' &&
      value !== null &&
      'kind' in value &&
      'cents' in value &&
      value.kind === 'line-item'
    );
  }
}

const parsed: unknown = JSON.parse('{"kind":"line-item","cents":1250}');

if (parsed instanceof CartEntry) {
  // Narrowed to LineItem without any shared prototype or class instance
  console.log('narrowed:', parsed.kind, parsed.cents);
} else {
  console.log('not a line item');
}

console.log('plain object:', { kind: 'line-item', cents: 5 } instanceof CartEntry);
console.log('wrong kind:', { kind: 'tax', cents: 5 } instanceof CartEntry);

// Primitives need an unknown detour to reach the custom check
const text: unknown = '1250';
console.log('string:', text instanceof CartEntry);

Output

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

narrowed: line-item 1250
plain object: true
wrong kind: false
string: false

How it works

Structurally, expect the class CartEntry and nothing else.

Caveats

  • All behavior comes from the standard library; nothing is external.

Using it

Output lines are prefixed (narrowed:, not a line item, plain object:), so every step’s effect is easy to pick out.

The key statements that remain

const parsed: unknown = JSON.parse('{"kind":"line-item","cents":1250}');
const text: unknown = '1250';
readonly kind: 'line-item';

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced.