简体   繁体   中英

Strings concatenation in enum value

I'm trying to refactor my redux action types to be enum type, but the problem is I would like to generate values through string concatenation.

Currently, my action looks like this (it is not symmetrical, so static generators won't work):

export const TYPE = '@@FOLDER';
export const FolderActionTypes = {
    REQUEST: `${TYPE}/REQUEST`,
    SUCCESS: `${TYPE}/SUCCESS`,
    ERROR: `${TYPE}/ERROR`,
    CHECK: `${TYPE}/CHECK`,
    UNCHECK: `${TYPE}/UNCHECK`,
    CLOSE: `${TYPE}/CLOSE`,
    OPEN: `${TYPE}/OPEN`
};

How I would like to make it looks like:

export const TYPE = '@@FOLDER';
export enum FolderActionTypes = {
    REQUEST = `${TYPE}/REQUEST`;
    SUCCESS = `${TYPE}/SUCCESS`;
    ERROR = `${TYPE}/ERROR`;
    CHECK = `${TYPE}/CHECK`;
    UNCHECK = `${TYPE}/UNCHECK`;
    CLOSE = `${TYPE}/CLOSE`;
    OPEN = `${TYPE}/OPEN`;
};

Is there any simple way to make it works?

You can create a helper method that accepts a string prefix and list of the actions that should be created & prefixed.

Given a prefix and array method should create an object having action types as keys and prefixed types as a values.

So given PREFIX/ and ['a', 'b'] the output should be { a: 'PREFIX/a', b: 'PREFIX/b' }

This might be simply done with the reduce array method.

The magic comes when you use use TS types - it can infer the output object keys from the function argument. So, as result IDE will autocomplete the action types for you:)

type ActionTypeMap<T extends string> = { [key in T ]: string };

const createActionTypesMap = <T extends string>(prefix: string, types: T[]): ActionTypeMap<T> =>
  types.reduce(
    (obj, key) => ({ 
      ...obj,
      [key]: `${prefix}${key}`
    }),
    {} as ActionTypeMap<T>
  );

const folderActionTypes = createActionTypesMap(
  '@FOLDER/',
  [
    'REQUEST',
    'SUCCESS',
    'ERROR',
    'CHECK',
    'UNCHECK',
    'CLOSE',
    'OPEN'
  ]
);

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM