Extract Builds Per-Channel Required Variants

Use Extract with a channel discriminant to derive per-variant required shapes, then switch exhaustively over the narrowed union.

TypescriptData Integrity

Code

typescriptsnippet
35 lines
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: 'ada@example.com',
  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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

Extract Builds Per-Channel Required Variants is built around the function send.

Using it

The main signature reads function send(message: DeliveryMessage)

The demo output is labeled (channels:), so every printed line can be matched to the operation behind it.

Key statements

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

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `send` at load time.