in Operator Narrows Union Shapes
Union members without a shared discriminant are narrowed with the in operator: checking key presence gives each branch its exact shape and fields.
Code
type Incoming =
| { text: string; author: string }
| { blob: Uint8Array; checksum: string };
// 两个形状没有公共判别字段:用 in 检查键的存在来收窄
function label(data: Incoming): string {
if ('text' in data) {
return `text from ${data.author} (${data.text.length} chars)`;
}
return `blob ${data.checksum} (${data.blob.byteLength} bytes)`;
}
const messages: Incoming[] = [
{ text: 'deploy finished', author: 'ci' },
{ blob: new Uint8Array([1, 2, 3, 4]), checksum: 'a1b2c3' },
];
for (const message of messages) {
console.log(label(message));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
text from ci (15 chars)
blob a1b2c3 (4 bytes)How it works
Count the function label as the entire surface area of in Operator Narrows Union Shapes.
Repetition is confined to for (const message of messages) — the rest of the file is straight-line.
What to watch for
- The guard
'text' in datashort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
Signature: function label(data: Incoming)
Core lines
return `blob ${data.checksum} (${data.blob.byteLength} bytes)`;
return `text from ${data.author} (${data.text.length} chars)`;
Interactive Tools for This Topic
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `label` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.