1

I'm trying to see if a user has a role with discordjs v13. I'm using typescript as well.

On multiple posts, I've seen people use this code:

function handleCommand(interaction: CommandInteraction) {
...
  let isAdmin = interaction.member.roles.cache.some(role => role.name === 'Admin')
...

This is an example

However, I get an error:

  Property 'cache' does not exist on type 'string[]'.

22   console.log(interaction.member.roles.cache.some((r) => r.name == "Admin"));
                                          ~~~~~

What is the correct way to do this?

oriont
  • 684
  • 2
  • 10
  • 25

2 Answers2

1

As Elitezen kindly pointed out, interaction.member.roles is a string[] instead of a GuildMemberRoleManager. I manually casted it to the correct type and it worked!

  let roles = (interaction.member.roles as GuildMemberRoleManager).cache;
  let isAdmin = roles.some(
    (role) => role.name === "admin")
  );
oriont
  • 684
  • 2
  • 10
  • 25
0

Rather than type casting I think it is better to check that the interaction is actually happening in a cached guild (because then .member will be typed as GuildMember and hence .member.roles is typed as GuildMemberRoleManager).

if (!interaction.inCachedGuild()) throw new Error('Not a cached guild')
const roles = interaction.member.roles.cache;
const isAdmin = roles.some(
  (role) => role.name === "admin")
);