如果另一个属性是特定枚举类型的话,将一个属性定义为可选的。

huangapple go评论73阅读模式
英文:

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.SUPERADMINUserRoles.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: [], // 报错
};

playground

英文:

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
};

playground

huangapple
  • 本文由 发表于 2023年7月27日 17:40:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定