为什么从client.on(“messageCreate”)中的TextChannel中缺少nsfw属性?

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年1月10日 20:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75070344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定