问一个ts的问题,怎么通过两个枚举合并生成另外一个枚举?

权限码时有模块枚举和权限枚举共同组成的,比如:

enum PermModuleCodeEnum {
  EnterpriseTenant = 'enterpriseTenant',
  EnterpriseIncoming = 'enterpriseIncoming',
  EnterpriseIncoming1 = 'enterpriseIncoming1',
}

type PremCode = 'Add' | 'Disable' | 'Edit'

function createPerCodes<T extends string>(union: T[], module: PermModuleCodeEnum): { [K in T]: `${PermModuleCodeEnum}:${K}` } {
  return union.reduce((pre, cur) => ({ ...pre, [cur]: `${module}:${cur}` }), {} as { [K in T]: `${PermModuleCodeEnum}:${K}` });
}

const perCodes = createPerCodes<PremCode>(['Add', 'Disable', 'Edit'], PermModuleCodeEnum.EnterpriseTenant);

console.log('xxx-1', perCodes);


此时此时的 perCodes为 {
    Add: "enterpriseTenant:Add" | "enterpriseIncoming:Add" | "enterpriseIncoming1:Add";
    Disable: "enterpriseTenant:Disable" | "enterpriseIncoming:Disable" | "enterpriseIncoming1:Disable";
    Edit: "enterpriseTenant:Edit" | "enterpriseIncoming" | "enterpriseIncoming1:Edit";
}

而不是

{
    Add: "enterpriseTenant:Add";
    Disable: "enterpriseTenant:Disable";
    Edit: "enterpriseTenant:Edit";
}

怎样才能修复createPerCodes的类型定义呢

阅读 2.9k
2 个回答
enum PermModuleCodeEnum {
  EnterpriseTenant = 'enterpriseTenant',
  EnterpriseIncoming = 'enterpriseIncoming',
  EnterpriseIncoming1 = 'enterpriseIncoming1',
}

type PremCode = 'Add' | 'Disable' | 'Edit';

function createPerCodes<T extends string, M extends PermModuleCodeEnum>(union: T[], module: M): { [K in T]: `${M}:${K}` } {
  return union.reduce((pre, cur) => ({ ...pre, [cur]: `${module}:${cur}` }), {} as { [K in T]: `${M}:${K}` });
}

const perCodes = createPerCodes<PremCode, typeof PermModuleCodeEnum.EnterpriseTenant>(['Add', 'Disable', 'Edit'], PermModuleCodeEnum.EnterpriseTenant);

console.log('xxx-1', perCodes);
type PermModuleCodeEnum = 'enterpriseTenant' | 'enterpriseIncoming' | 'enterpriseIncoming1';

type PremCode = 'Add' | 'Disable' | 'Edit';

type PermissionCode<M extends string, P extends string> = `${M}:${P}`;

function createPerCodes<M extends string, P extends string>(
  permissions: P[],
  module: M
): { [K in P]: PermissionCode<M, K> } {
  return permissions.reduce((pre, cur) => ({ ...pre, [cur]: `${module}:${cur}` }), {} as { [K in P]: PermissionCode<M, K> });
}

const perCodes = createPerCodes(['Add', 'Disable', 'Edit'], 'enterpriseTenant');

GPT回答的。没验证过。你试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏