← 中文资源

简体中文版本

Extract 按 channel 派生必填变体

用 Extract 配合 channel 判别字段派生每个变体,并以穷尽 switch 处理收窄后的联合。

阅读英文原文

运行结果

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

email:Release:Ship it
sms:+10000000000:Ship it
channels: email,sms

实现说明

Extract 按 channel 派生必填变体的核心是函数 send。

使用要点

  • 直接运行文件,输出会带上标签,比如 channels:——输出的每一行都能指回产生它的那次调用。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 send。

主要签名是 function send(message: DeliveryMessage)

核心语句

return 'email:' + message.subject + ':' + message.body;
return 'push:' + message.deviceId + ':' + message.body;
return 'sms:' + message.to + ':' + message.body;

代码示例

type DeliveryMessage =
  | { channel: 'email'; to: string; subject: string; body: string }
  | { channel: 'sms'; to: string; body: string }
  | { channel: 'push'; deviceId: string; body: string };

// Extract 按 channel 判别字段取出对应变体,缺失字段会编译失败
type RequiredFor<T extends { channel: string }, K extends T['channel']> = Extract<T, { channel: K }>;

function send(message: DeliveryMessage): string {
  switch (message.channel) {
    case 'email':
      return 'email:' + message.subject + ':' + message.body;
    case 'sms':
      return 'sms:' + message.to + ':' + message.body;
    case 'push':
      return 'push:' + message.deviceId + ':' + message.body;
  }
}

const email: RequiredFor<DeliveryMessage, 'email'> = {
  channel: 'email',
  to: '[email protected]',
  subject: 'Release',
  body: 'Ship it',
};

const sms: RequiredFor<DeliveryMessage, 'sms'> = {
  channel: 'sms',
  to: '+10000000000',
  body: 'Ship it',
};

console.log(send(email));
console.log(send(sms));
console.log('channels:', email.channel + ',' + sms.channel);