Narrow Method Receivers With this is Guards
Return a this is NarrowedState predicate from class methods so conditional checks narrow the receiver instance itself without external guard helpers.
Code
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');
}
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
idle channel: waiting for handshake
active: STREAM.INTERNAL/EVENTS sess-901Inside the routine — Narrow Method Receivers With this is Guards
The moving parts are the class ServiceChannel.
Repetition is confined to for (const ch of channels) — the rest of the file is straight-line.
The file’s state is a handful of top-level bindings: channels.
What to watch for
- Copy, run: the standard library answers every call in the file.
Putting it to use
The run emits 2 labeled sections — active:, idle channel: waiting for handshake — one per step.
Core lines
sessionId: string | undefined;
readonly status: 'connected';
status: 'idle' | 'connected';
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `channels`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.