0

I have a UserRoles type in typscript

type = 'student' | 'editor' | 'moderator' | 'admin'
or
type UserRoles = 'student' | 'editor' | 'moderator' | 'admin'

how can I create an array based on these types? something like

const roles = Array.from(UserRoles)

Thanks in advance :)

1
  • var userRoles:UserRoles[] = []; // would create an empty array of UserRoles Commented Jun 28, 2020 at 17:21

2 Answers 2

3

UserRoles only refers to a type, you can not use it as a value. But you can explictly create a readonly array for the roles and extract the type from it. For example,

const roles = ['student', 'editor', 'moderator', 'admin'] as const;

// type will be  'student' | 'editor' | 'moderator' | 'admin'
type UserRoles = typeof roles[number]

let uRole: UserRoles;
// valid
uRole = 'student';

// compile-time error
uRole = 'hello'

typescript playground

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

3 Comments

after setting user Roles to type enum, I can't use it as I used before .. https://image.prntscr.com/image/dS2lBofuSWG0PfW9w4YS6A.png
enums and union types are two different things. If you want to modify your code base you can fix the error by assigning the role value like this role: Roles.student. If you don't want to modify your code base use the solution that i have provided, it will not break any existing code.
Here is another example ts playground
0

One good practice in your case is using Enums. Besides numbers, you can also have string enums (which is what you need).

enum UserRoles {
    Student = 'student',
    Editor = 'editor',
    Moderator = 'moderator',
    Admin = 'admin'
}

If you do it this way, you can consider the Enum an object and get an array of its values with

const values = Object.values(UserRoles);

2 Comments

after setting user Roles to type enum, I can't use it as I used before .. https://image.prntscr.com/image/dS2lBofuSWG0PfW9w4YS6A.png
@YungSilva This is something requested, but I doubt it has been implemented (github.com/microsoft/TypeScript/issues/17690). The common usage of enums is assigning Type.Value to the variable instead of a string literal. In your case, given the screenshots, you could do { ... ; role: Roles.student; ... }. Notice that you need to export the enum if you want to use it in a different file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.