【问题标题】:TypeScript erroring "Object is possibly 'undefined'."TypeScript 错误“对象可能是‘未定义’。”
【发布时间】:2021-08-25 12:24:44
【问题描述】:

我正在使用 TypeScript 为 Discord V13 开发机器人。问题出在第 17/18 行(我有一个错误所在的注释),我收到一条错误消息,提示“对象可能是'未定义'”。我似乎找不到问题,因为我对 JavaScript/TypeScript 很陌生。我希望有人能帮助我。谢谢。

import Discord, { Intents } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()

const Client = new Discord.Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MESSAGE_REACTIONS
    ] 
})

const Prefix = "!"

Client.on("ready", () => {
    console.log("Bot has initialized.")
})

Client.on("messageCreate", (Message) => {
    if(!Message.content.startsWith(Prefix) || Message.author.bot) return;

    const Args = Message.content.slice(Prefix.length).split(/ +/)
    const Command = Args.shift().toLowerCase() // This is 'undefined'

    switch (Command) {
        case "ping":
            Message.reply("pong")
            break;
    }
})

Client.login("")

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以通过添加 optional chaining 来解决此问题,或者先检查它是否未定义:

    Args?.shift()?.toLowerCase()
    

    Args.shift() && Args.shift().toLowerCase()
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 2019-08-20
      • 2022-01-05
      • 1970-01-01
      • 2020-08-11
      • 2020-05-11
      • 2021-10-07
      相关资源
      最近更新 更多