#Type value of enum

22 messages · Page 1 of 1 (latest)

dense eagle
#

I have the following enum and I want to create a type that represents only the values of the enum. Is that possible?

enum ModerateErrors {
    OWNER = 1,
    BOT_PERMISSION = 2,
    BOT_ROLE = 3,
    EXECUTOR_ROLE = 4,
    MODERATE_BOT = 5,
    MODERATE_SELF = 6
}
dapper creek
#

yes

#

the enum is both ther type and the values

#
const myRole: ModerateErrors = ModerateErrors.OWNER;
dense eagle
#

Yes, I know that but the type that I need is like only can be valid a value of the enum, I will explain better:
I have a function that returns n number and is typed like this

export async function canModerateMember(): Promise<ModerateErrors> {
    // code
}

but when this function returns a value that is not a value of ModerateErrors doesn't happens anything

dapper creek
#

right

dense eagle
#

In the enum only are numbers from 1 to 6 and allow returning 10 for example

dapper creek
#

because by default, enums are just names for numbers

#

and returning an "enum" is the same as returning a number

#

just don't use numbers with enum

#

use strings

dense eagle
#

ok i will do that

#

thx

#

!resolved

jaunty breachBOT
#
Ascor8522#7606

Preview:```ts
enum ModerateErrors {
OWNER = "OWNER",
BOT_PERMISSION = "BOT_PERMISSION",
BOT_ROLE = "BOT_ROLE",
EXECUTOR_ROLE = "EXECUTOR_ROLE",
MODERATE_BOT = "MODERATE_BOT",
MODERATE_SELF = "MODERATE_SELF",
}

export async function canModerateMember(): Promise<ModerateErrors>
...```

dapper creek
#

!ts

jaunty breachBOT
#
enum ModerateErrors {
  OWNER = "OWNER",
  BOT_PERMISSION = "BOT_PERMISSION",
  BOT_ROLE = "BOT_ROLE",
  EXECUTOR_ROLE = "EXECUTOR_ROLE",
  MODERATE_BOT = "MODERATE_BOT",
  MODERATE_SELF = "MODERATE_SELF",
}

export async function canModerateMember(): Promise<ModerateErrors> {
  return Promise.resolve("foo");
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Type '"foo"' is not assignable to type 'ModerateErrors'.
}

export async function canModerateMember2(): Promise<ModerateErrors> {
  return Promise.resolve(ModerateErrors.MODERATE_BOT);
}
dapper creek
#

@dense eagle that's on of the reasons why some ppl don't recommend using enums
but imo, when used right (with strings and not numbers, they are completely fine)

dense eagle
#

Ok thx for all rodrii2LovesU

dapper creek
#

!resolved

jaunty breachBOT
#

@dense eagle
Because your issue seemed to be resolved, this post was marked as resolved by @dapper creek.
If your issue is not resolved, you can reopen this post by running !reopen.
If you have a different question, make a new post in #1057653400046674112.

sharp cipher
#

@dense eagle FWIW, while I don't love enums, either, this specific issue with numeric enums will go away in TS 5.0