Transform a APIInteractionDataResolvedGuildMember into a GuildMember

Hello there, I am beginning with discord.js and typescript. To ensure type safety, i want to make sure that the object returned by a interaction.options.getMember() is a GuildMember and not a APIInteractionDataResolvedGuildMember in order to later perform various operations. So i've began to write a function to fetch the GuildMember if needed but APIInteractionDataResolvedGuildMember does not have a user property so i can't have the id for fetching... How should i deal with it ? Or can i safely assume that in the context of slash commands in guild i will always have a GuildMember object ? Here the function that i wrote :
export async function getMemberSafely(member : GuildMember | APIInteractionDataResolvedGuildMember| null , guild : Guild) : Promise<GuildMember | null> {
if (!member) return null;
if (member instanceof GuildMember) return member;

try {
const fetchedMember : GuildMember = await guild.members.fetch((member as APIInteractionDataResolvedGuildMember)?.user?.id); // Here is the problem
return fetchedMember;
} catch (error) {
console.error("Erreur lors de la récupération d'un membre : ",error);
return null;

}
}
export async function getMemberSafely(member : GuildMember | APIInteractionDataResolvedGuildMember| null , guild : Guild) : Promise<GuildMember | null> {
if (!member) return null;
if (member instanceof GuildMember) return member;

try {
const fetchedMember : GuildMember = await guild.members.fetch((member as APIInteractionDataResolvedGuildMember)?.user?.id); // Here is the problem
return fetchedMember;
} catch (error) {
console.error("Erreur lors de la récupération d'un membre : ",error);
return null;

}
}
Thanks !
8 Replies
d.js toolkit
d.js toolkit7mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
d.js docs
d.js docs7mo ago
:method: BaseInteraction#inCachedGuild @14.15.3 Indicates whether or not this interaction is both cached and received from a guild.
TÆMBØ
TÆMBØ7mo ago
The easiest way to fix this would be to simply ensure that the interaction is from a cached guild with this typeguard, which will then narrow the typing for getMember() to specifically be a GuildMember structure and not raw data
CXazertyuuu
CXazertyuuuOP7mo ago
Okay, and if the guild is not cached can i cache it manually ?
TÆMBØ
TÆMBØ7mo ago
Do you have the Guilds intent?
Unknown User
Unknown User7mo ago
Message Not Public
Sign In & Join Server To View
CXazertyuuu
CXazertyuuuOP7mo ago
Yeah i have it Thanks to both then
Unknown User
Unknown User7mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server