Typescript Partial<T> 即使使用 `?` 链接或条件检查也会导致未定义的错误

Typescript Partial<T> causing undefined error even with `?` chaining or conditional Checks

我有一个猫鼬文档存储如下:

const currentGuildAlerts: Partial<mongoose.Document<IServerSchema> | null> = await Server.findOne(query).exec();

使用 Partial<T>(因为我只从查询返回的 IServerSchema 中得到一条路径),我知道 Partial 链接了一个 ?到界面中每个 属性 的末尾。但是我应该能够通过对值使用条件检查来绕过它吗?

if(currentGuildAlerts) currentGuildAlerts.get("symbol_alerts").btc_alerts;

这仍然给我错误: Cannot invoke an object which is possibly 'undefined'.

我什至尝试过

currentGuildAlerts?.get("symbol_alerts").btc_alerts;

好像还是没有解决问题。我在这里做错了什么?

Partial表示对象的属性可能是undefined。您确定 currentGuildAlerts object 不是 null 但您还没有检查 属性存在。

您还需要在 get 之后添加一个可选的链接 ?.,因为您已经说过 Document 的所有属性都可能是 undefined.

const currentGuildAlerts: Partial<mongoose.Document<IServerSchema>> | null = await Server.findOne(query).exec();

const alerts = currentGuildAlerts?.get?.("symbol_alerts").btc_alerts;

也许将 Partial 移到 Document 中更有意义?

const currentGuildAlerts: mongoose.Document<Partial<IServerSchema>> | null = await Server.findOne(query).exec();

const alerts = currentGuildAlerts?.get("symbol_alerts").btc_alerts;