You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript编译报':' expected 第17行第5列问题排查求助

报错原因

你代码中channel = client.channels.cache.get('-- censored --')?这行末尾的单个?,TypeScript 会判定为三元表达式的起始标识,三元表达式要求必须符合条件 ? 真值分支 : 假值分支的语法结构,你仅写了?未补充后续的:和对应分支,因此编译器抛出需要:的错误。

修复方案

根据实际需求可选以下两种写法:

方案1:使用可选链规避空值报错(推荐)

你大概率是想判断获取到的频道是否存在,避免空值调用报错,应该把单问号改为可选链运算符?.,同时调整类型声明兼容空值,修改后代码如下:

import { Client , TextChannel } from "discord.js";

module.exports = {
    name: "ready",
    run: async(client: Client) => {
        client.user.setPresence({
            activities: [{
                name: "Aun en beta!"
            }],
            status: "idle"
        })

        let str = `-- censored --`
        // 类型标注添加undefined兼容可能拿不到频道的情况
        let channel: TextChannel | undefined; 
        channel = client.channels.cache.get('-- censored --') as TextChannel | undefined
        // 可选链判断channel存在再调用send
        channel?.send(str)
    }
}

如果要做严格类型校验,避免强制断言的风险,也可以用instanceof做类型收窄:

const rawChannel = client.channels.cache.get('-- censored --')
if (rawChannel instanceof TextChannel) {
  rawChannel.send(str)
}

方案2:补全三元表达式分支

如果你确实需要根据是否拿到频道做不同处理,可以补全三元表达式结构:

const channel = client.channels.cache.get('-- censored --') as TextChannel | undefined
// 示例:拿到频道就发消息,没拿到就打印日志
channel ? channel.send(str) : console.log('目标频道不存在')

内容的提问来源于stack exchange,提问作者akkoboi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 02:24:05