如何解决 VS Code 中"TS1109: Expression expected"的 TypeScript 可选链接错误?



只是为了一些背景,我正在使用discord.js创建一个discordbot。我目前正在遵循这个视频指南(链接到我遇到问题的时间戳(,我已经准确地复制了到那时为止所做的事情。

以下是我使用的所有东西的版本:

  • VS代码:1.65.2
  • 节点:16.14.2
  • npm:8.5.0
  • TypeScript:4.6.2
  • dotenv:16.0.0
  • discord.js:13.60
  • 节点:2.0.15

我会把我的代码和错误放在下面,但这里还有一个SrcShare:SrcShare-Link

指数.ts

import DiscordJS, { Intents } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
],
})
client.on('ready', () => {
console.log('The bot is ready.')
const guildId = '276237909378465794'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application?.commands
}
commands?.create({
name: 'ping',
description: 'Replies with pong.',
})
})
client.login(process.env.TOKEN)

在终端中运行ts-node index.ts时出现错误

return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
index.ts(22,39): error TS1109: Expression expected.
index.ts(23,5): error TS1005: ':' expected.
index.ts(25,14): error TS1109: Expression expected.
index.ts(29,1): error TS1005: ':' expected.
[nodemon] app crashed - waiting for file changes before starting...

我已经尝试了另一篇stackoverflow文章中的解决方案,其中的问题似乎也是使用?运算符的可选链接。该线程中的所有解决方案都表示,您需要更新到TypeScript 3.7+,其中支持可选链接,但我使用的是TypeScript 4.6.2。

如果有人知道这里发生了什么,我将感谢你的帮助!

更新

所以我认为这可能是nodemon的问题。如果我在终端中运行ts-node index.ts,机器人程序启动时不会出现错误。但在package.json中,我有一个类似于"dev": "nodemon index.ts"的脚本。当我运行npm run dev时,我仍然会得到上面显示的错误,即使nodemon应该只是运行ts-node index.ts

检查node_modules文件夹,看看您是否真的使用了您认为正在使用的TypeScript版本。我的问题是,我所依赖的一个包依赖于TypeScript 3.4.3,并将该版本安装在我的项目的node_modules文件夹中。

将包更新为一个没有指定它所依赖的TypeScript版本的包为我修复了它。

最新更新