typescript - 如何“说服” TypeScript 该属性存在?
问题描述
我对 TypeScript 和 Immutable 有疑问。我的代码如下:
class Repo {
private repository {
items: Map({ "1": { "a": "b" })
}
public get(id: string) {
if (!id) {
throw new Error("ID must be passed. Use `getAll` or `getAllAsMap` to get all items.");
}
const found: Object | undefined = this.repository.items.get(id);
if (typeof found !== "undefined") {
return this.repository.items.get(id);
}
throw new Error(`Entry with ID ${id} cannot be found.`);
}
}
在这里我收到一个错误,说this.repository.items.get(id)
可能是未定义的。但是我正在检查它是否不是之前的行。除了使用,我还能做什么!
?
解决方案
if (found) { ... }
您可以使用or检查未定义的if(found !== undefined) { ... }
内容,然后您必须这样做,return found
因为这是您检查的对象!
public get(id: string) : Object {
const found: Object | undefined = this.repository.items.get(id)
if (found !== undefined) {
return found
}
}
推荐阅读
- ruby - 如何将当前类引用为 YARD 中的返回类型?
- excel - PySpark 中是否有等效的 ExcelWriter?
- azure-active-directory - 无法使用 Microsoft Graph API 从 Azure AD 获取订阅列表
- dart - 我正在使用 dio 库进行 http 响应,但没有更新 listview 颤振
- delphi - 是否可以在 Delphi 中为 Windows 应用商店创建 MS Office 插件?
- python-3.x - 实现 for 和 if 在 reduce 函数中
- css - 如何根据其值单独设置 ngFor 的每个元素的样式?
- android - 我正在尝试从数组列表中的房间数据库中获取数据,但它仅显示 android 中的最后一条记录
- ruby-on-rails - 无法从我的 Windows 桌面访问在 AWS Ubuntu 上运行的 rails localhost
- arrays - 用汇编语言 x86 从大到小对数组进行排序