英文:
Define one prop as optional if another one is of specific enum type
问题
组件属性类型:
interface IRequireUserPermits {
minimalRequiredRole: UserRoles;
allowedPermissions?: UserPermissions[];
}
UserRoles
是一个枚举类型:
export enum UserRoles {
SUPERADMIN = "SUPERADMIN",
ADMIN = "ADMIN",
AGENT = "AGENT",
}
如何定义 allowedPermissions
属性仅在 minimalRequiredRole
属性为 UserRoles.AGENT
时为必需?或者反过来,如何使属性可选,仅当 minimalRequiredRole
属性为 UserRoles.SUPERADMIN
或 UserRoles.ADMIN
时?
谢谢。
英文:
Component prop type:
interface IRequireUserPermits {
minimalRequiredRole: UserRoles;
allowedPermissions: UserPermissions[];
}
UserRoles
is an enum:
export enum UserRoles {
SUPERADMIN = "SUPERADMIN",
ADMIN = "ADMIN",
AGENT = "AGENT",
}
How can I define allowedPermissions
prop required only if the minimalRequiredRole
prop is UserRoles.AGENT
? Or the other way around - how to make prop optional only if the minimalRequiredRole
prop is either UserRoles.SUPERADMIN
or UserRoles.ADMIN
?
Thanks
答案1
得分: 1
你正在寻找区分联合类型。我们可以使用type
而不是interface
来定义IRequireUserPermits
:
type IRequireUserPermits =
| {
minimalRequiredRole: UserRoles.AGENT;
allowedPermissions: UserPermissions[];
}
| {
minimalRequiredRole: UserRoles.SUPERADMIN | UserRoles.ADMIN;
};
测试代码如下:
const case1: IRequireUserPermits = {
minimalRequiredRole: UserRoles.AGENT,
allowedPermissions: [], // 没有错误
};
const case2: IRequireUserPermits = {
minimalRequiredRole: UserRoles.ADMIN,
allowedPermissions: [], // 报错
};
英文:
You are looking for discriminated unions. Instead of interface let's use type for IRequireUserPermits
:
type IRequireUserPermits =
| {
minimalRequiredRole: UserRoles.AGENT;
allowedPermissions: UserPermissions[];
}
| {
minimalRequiredRole: UserRoles.SUPERADMIN | UserRoles.ADMIN;
};
Testing:
const case1: IRequireUserPermits = {
minimalRequiredRole: UserRoles.AGENT,
allowedPermissions: [], // no error
};
const case2: IRequireUserPermits = {
minimalRequiredRole: UserRoles.ADMIN,
allowedPermissions: [], // error
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论