我有以下两个不能修改的界面 :
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',
}
因为未指定email
和group
。
这里有一个Playground。
谢谢!
答案 0 :(得分:4)
您可以结合使用Utility Types中的Pick
,Required
和Omit
来实现。
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',
}
答案 1 :(得分:1)
这样定义成员:
interface Member extends User, Player {
email: string;
group: string;
}