如何在Typescript中创建包含Type1的所有属性或Type2的所有属性的类型?

如何在Typescript中创建包含Type1的所有属性或Type2的所有属性的类型?,typescript,Typescript,我有一些这样的代码: interface Notification { message: TemplatedEmail & Email, //current attempt which doesnt do what I want } interface Destination { ccAddresses?: string[], bccAddresses?: string[], toAddresses: string[] } interface TemplatedEma

我有一些这样的代码:

interface Notification {
  message: TemplatedEmail & Email, //current attempt which doesnt do what I want
}

interface Destination {
  ccAddresses?: string[],
  bccAddresses?: string[],
  toAddresses: string[]
}

interface TemplatedEmail {
  destination: Destination,
  source: string,
  template: string,
  templateData: any,
  replyToAddresses?: string[]
}

interface Email {
  destination: Destination,
  source: string,
  body: string,
  subject: string,
  replyToAddresses?: string[]
}
我希望
通知
消息
属性为
电子邮件
模板文件
类型,我的意思是
电子邮件
的所有属性(当然可以跳过可选属性)或
模板文件
的所有属性都应该在
消息
中可用。对于联合类型,我只能访问这两种类型的公共属性;对于交叉类型,我可以获得这两种类型的所有属性

在我当前的代码中,类似这样的东西不起作用:

const x: Notification = { 
    message: {
          destination: { toAddresses: [ "" ] },
          source: "",
          body: "",
          subject: ""
    }
};
它抱怨
x
中缺少属性
template
templateData
,一种方法是使用,但这会稍微改变消息的结构:

type XType = TemplateNotification | EmailNotification;

interface TemplateNotification {
  kind: 'template',
  message: TemplatedEmail
}

interface EmailNotification {
  kind: 'email',
  message: Email
}

const x: XType = { 
    kind: 'email',
    message: {
          destination: { toAddresses: [ "" ] },
          source: "",
          body: "",
          subject: ""
    }
};
操场示例

一种方法是使用,但这会稍微改变消息的结构:

type XType = TemplateNotification | EmailNotification;

interface TemplateNotification {
  kind: 'template',
  message: TemplatedEmail
}

interface EmailNotification {
  kind: 'email',
  message: Email
}

const x: XType = { 
    kind: 'email',
    message: {
          destination: { toAddresses: [ "" ] },
          source: "",
          body: "",
          subject: ""
    }
};

操场示例

您的代码不完整,请完成它,然后自己查看错误,链接太长,因此我无法将其放入注释中。@StupidMan我编辑了URL为什么将
通知
更改为
通知
?在您更新的代码中,heni do
console.log(x.message.body),我得到的
属性“body”在类型“TemplatedEmail | Email”上不存在。属性“body”在类型“TemplatedEmail”上不存在。
联合类型仅允许访问这两种类型中可用的属性。接口通知保留在TS游乐场中,来自lib.dom.d.TS,这就是我必须将其更改为INotification的原因。您的模块中不会出现此问题。我现在了解到您尝试使用union,所以我编辑了我的答案,以更好地满足您的要求。希望此帮助您的代码不完整,请完成它,然后亲自查看错误,链接太长,因此我无法将其放在注释中。@StupidMan我编辑了URL为什么将
通知更改为
通知
?在您更新的代码中,heni do
console.log(x.message.body),我得到的
属性“body”在类型“TemplatedEmail | Email”上不存在。属性“body”在类型“TemplatedEmail”上不存在。
联合类型仅允许访问这两种类型中可用的属性。接口通知保留在TS游乐场中,来自lib.dom.d.TS,这就是我必须将其更改为INotification的原因。您的模块中不会出现此问题。我现在了解到您尝试使用union,所以我编辑了我的答案,以更好地满足您的要求。希望这有帮助