英文:
Why is the nsfw property is missing from a TextChannel from client.on("messageCreate")?
问题
我正在使用Typescript和Discord.js v14。我遇到了以下错误:
属性'nsfw'在类型'DMChannel | PartialDMChannel | ...'上不存在。
以下是代码:
client.on("messageCreate", async msg => {
if (msg.channel.nsfw) { // 这里是错误发生的地方
msg.reply("这有点不安全,朋友..");
}
})
我尝试手动将msg.channel
类型转换为BaseGuildTextChannel
,但这对我来说太不安全了。是否有其他修复方法?
英文:
I'm using Typescript with Discord.js v14. I'm getting the error:
Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | ...
Here is the code:
client.on("messageCreate", async msg => {
if (msg.channel.nsfw) { // here is where the error takes place
msg.reply("That's kinda nsfw man..");
}
})
I tried manually type-casting msg.channel
to a BaseGuildTextChannel
but it was too unsafe for me.
Is there another way to fix this?
答案1
得分: 3
消息来源的频道可以有多种类型,Typescript 告诉你在所有可能的类型上找不到.nsfw
属性,因为 DM 频道缺少这个属性。添加一个类型保护:
// 从 discord.js 中导入 ChannelType
client.on("messageCreate", async msg => {
if (msg.channel.type !== ChannelType.GuildText) return;
if (msg.channel.nsfw) {
msg.reply("这有点不安全,朋友..");
}
})
然后,Typescript 将会知道通过第一个条件检查的任何频道都将是一个公会文本频道。
英文:
The channel a message came from can be of many types, Typescript is telling you the .nsfw
property is not found on every possible type as DM channels are missing this property. Add a type guard:
// require/import ChannelType from discord.js
client.on("messageCreate", async msg => {
if (msg.channel.type !== ChannelType.GuildText) return;
if (msg.channel.nsfw) {
msg.reply("That's kinda nsfw man..");
}
})
Typescript will then know that any channel that passed the first statement will be a guild text channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论