2

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?

2
  • Why would you need to do that ? Commented Nov 13, 2019 at 15:45
  • Enum seems to be more natural here, but i don't want to type @@FOLDER multiple times, but it's important to me to keep action domain context. Commented Nov 13, 2019 at 16:02

1 Answer 1

2

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'
  ]
);

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.