实现说明
逻辑集中在函数 label里。
这个文件只在 for (const message of messages) 里循环。
使用要点
- 守卫
'text' in data满足时靠提前的return短路流程。
常见问题
有语言之外需要解析的导入吗?
没有。每个导入都解析到语言自带的模块。 文件在加载时定义 label。
入口签名:function label(data: Incoming)
核心语句
return `blob ${data.checksum} (${data.blob.byteLength} bytes)`;
return `text from ${data.author} (${data.text.length} chars)`;
代码示例
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));
}