← 中文资源

简体中文版本

用 this is 返回值收窄方法接收者类型

在类方法上声明 this is 子类型谓词,调用方在条件分支内可直接把接收者实例收窄到已连接状态并访问非空属性,省去外部守卫。

阅读英文原文

运行结果

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

idle channel: waiting for handshake
active: STREAM.INTERNAL/EVENTS sess-901

实现说明

用 this is 返回值收窄方法接收者类型的核心是类 ServiceChannel。 for (const ch of channels) 反复执行,循环体之外没有别的重复。 顶层就这几处状态:channels。

使用要点

  • 这里没有依赖树——平台本身就是全部依赖。
  • 演示输出是带标签的(active:、idle channel: waiting for handshake),每个操作都会留下自己的一行标注。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:channels。

核心语句

sessionId: string | undefined;
readonly status: 'connected';
status: 'idle' | 'connected';

代码示例

interface ConnectedState {
  readonly status: 'connected';
  readonly endpoint: string;
  readonly sessionId: string;
}

class ServiceChannel {
  status: 'idle' | 'connected';
  endpoint: string | undefined;
  sessionId: string | undefined;

  constructor(endpoint?: string, sessionId?: string) {
    if (endpoint && sessionId) {
      this.status = 'connected';
      this.endpoint = endpoint;
      this.sessionId = sessionId;
    } else {
      this.status = 'idle';
    }
  }

  // A `this is ...` predicate narrows the receiver instance at call sites
  isConnected(): this is this & ConnectedState {
    return (
      this.status === 'connected' &&
      this.endpoint !== undefined &&
      this.sessionId !== undefined
    );
  }
}

const channels = [
  new ServiceChannel(),
  new ServiceChannel('stream.internal/events', 'sess-901'),
];

for (const ch of channels) {
  if (ch.isConnected()) {
    // Both `endpoint` and `sessionId` narrow from `string | undefined` to `string`
    console.log('active:', ch.endpoint.toUpperCase(), ch.sessionId);
  } else {
    console.log('idle channel: waiting for handshake');
  }
}