-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Enum literal cannot contain concatenated string #20784
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Out of curiosity, how are you currently planning on using the multiline enums? Something long enough that you hope nobody accidentally types it? Or is this just an unfortunate case of deep indentation? |
We have code that uses enums for collections of long string constants. Not sure if it's the right use of enums though. E.g. something like:
Note that it's not exactly multiline (we want the resulting string to have no embedded newlines) so we can't use backticks for a multiline string. We just have multiple lines with a + in the middle for code style reasons (column limit). |
Enums are probably not the best suited for this. Here is what I would do. export type ERROR_ONE = 'ERROR_ONE';
export const ERROR_ONE: ERROR_ONE = 'ERROR_ONE';
export type ERROR_TWO = 'ERROR_TWO';
export const ERROR_TWO: ERROR_TWO = 'ERROR_TWO';
export type ERROR_IDs = (
| ERROR_ONE
| ERROR_TWO
);
export const ERROR_MESSAGES: { [E in ERROR_IDs]: string; } = {
[ERROR_ONE]: 'long ERROR_ONE message',
[ERROR_TWO]: 'long ERROR_TWO message'
};
function getMessage(errorID: ERROR_IDs): string {
return ERROR_MESSAGES[errorID];
}
console.log(getMessage (ERROR_ONE)); // $> long ERROR_ONE message Neat things: You will get completions getMessage( ** here ** ) Plus, if you define add a new This is basically how I type my redux actions. It's definitely verbose, but it gets the completions/type checking so I don't mind a little copy pasta. |
There's lots of alternatives here but our users typically reach for enum as
the intuitive one. It's hard to convince people that repeating each
variable name seven times (like you do in your example) is worth it.
|
I agree. But enums in TypeScript are kinda meh. There have been like 100+ issues opened about enums, Best suggestion I can give is to write a script (or snippet for your prefered IDE) to generate that boilerplate for you. @chriseppstein just made an interesting suggestion here: #20898 (comment) which could also be compatible with string literals and would bring that 7 down to a 3. Not ideal, but eh |
Accepting PRs for this one. Should be reasonably straightforward as similar mechanics are already in place for numeric enum computations. |
thanks @Kingwl! |
TypeScript Version: 2.7.0-dev.20171216 and older
Code
Expected behavior:
Accepted.
Actual behavior:
error TS2352: Type 'string' cannot be converted to type 'Test'.
Adding some 'as Test' annotation didn't seem to work.
Workarounds:
The text was updated successfully, but these errors were encountered: