Closed mohsen1 closed 8 years ago
I was actually thinking about that a while ago and the reason I didn't use them is the dev tools. It's not clear what action type is used due of the enum numbering and really makes it difficult to debug because of that. What do you think?
This is how the dev tools currently look like:
This is when using enums:
Well, it would be almost impossible for dev tool to know what the original name of those enums are...
So I guess it's a tradeoff.
See interesting discussion about string type enums here: https://github.com/Microsoft/TypeScript/issues/3192
Using the example there the Action code would look like this:
type ActionTypesEnum = "ADD_TO_CART" | "REMOVE_FROM_CART";
export const ActionTypes = {
ADD_TO_CART: "ADD_TO_CART" as ActionTypesEnum,
REMOVE_FROM_CART: "REMOVE_FROM_CART" as ActionTypesEnum
};
This gives an enum-like usage in the reducer, but has the above boilerplate in the action creator. Would definitely be nicer with a clean string enum syntax...
I see! But that's not landed in the language yet, right?
Unfortunately no. You can only use the above example code to mimic the same behaviour. I'm still contemplating if this is better than plain old strings...
I've updated the code to use this enum-like style. Although it's not as neat (and clean) as enums I agree that it's much easier and safer to consume in reducers. Even though it doesn't benefit minification I like the result and think it's better than the previous unsafe string constants. Thanks for the feedback! Here's the commit: https://github.com/InfomediaLtd/angular2-redux-example/commit/d7300db8ef2e101381eb7a9fe035872f94a47218 (Sorry I forgot to link to this issue during commit)
Cool! 👍🍺
Hello, could you please explain what do you mean by "much easier and safer to consume"? I've checked the commit with typings but reducers still take action as "any" so no help from TS editor here. And switch works well with both typed or simple strings. The only difference is you can do a typo while doing "boilerplate" when defining those string literals. At least in this case - maybe using strongly typed actions but it would add even more code which so the question is if it's worth it. Thank you.
Maybe we can use string enum:
enum CartActionTypes {
ADD_TO_CART= 'ADD_TO_CART',
REMOVE_FROM_CART = 'REMOVE_FROM_CART'
}
@xcatliu I agree. Much better! Would you like to create a PR?
It's better for minification since enums become numbers in transpiled code. It's also more TypeScript-y