← 中文资源

简体中文版本

Symbol.hasInstance 扩展 instanceof

给类挂静态 Symbol.hasInstance 类型谓词,instanceof 就能收窄没有共同原型的结构化对象:解析出的 JSON 也能走 instanceof 分支。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

底层就是类 CartEntry。

使用要点

  • 跑完文件,输出里会留下标记——narrowed:、plain object:、wrong kind:。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。

核心语句

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

代码示例

// 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);