TypeScript-组合两个接口并使其中某些成员成为必需

时间:2019-12-02 08:18:08

标签: javascript reactjs typescript

我有以下两个不能修改的界面

interface User {
  username: string;
  email?: string;
  age?: number;
  country?: string;
}

interface Player {
  room: number;
  group?: string;
  device?: string;
}

我想将它们仅合并为一个接口:Member,同时将字段User['email']Player['group']强制(仅是这2个)。

我尝试了以下操作(仅作为起点(TBD)):

// please edit this code accordingly
interface Member extends User, Player  {}

然后,预期结果是出现以下错误:

const member: Member = {
  username: 'bill.gates',
  // email: 'bill.gates@microsoft.com',
  age: 50,
  room: 5,
  // group: 'A',
}

因为未指定emailgroup

这里有一个Playground

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以结合使用Utility Types中的PickRequiredOmit来实现。

type Member = Required<Pick<User & Player, 'email' | 'group'>> & Omit<User & Player, 'email' | 'group'>;


/*
Type '{ username: string; age: number; room: number; }' is not assignable to type 'Member'.
  Type '{ username: string; age: number; room: number; }' is missing the following properties from type 'Required<Pick<User & Player, "email" | "group">>': email, group(2322)
*/
const member: Member = {
  username: 'bill.gates',
  // email: 'bill.gates@microsoft.com',
  age: 50,
  room: 5,
  // group: 'A',
}

这里是working playground

答案 1 :(得分:1)

这样定义成员:

interface Member extends User, Player  {
    email: string;
    group: string;
}