我对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)
可能未定义。但是我正在检查的行不是。除了使用!
之外,我还能做什么?
答案 0 :(得分:0)
您可以使用if (found) { ... }
或if(found !== undefined) { ... }
检查未定义的对象,然后必须return found
,因为这是您检查的对象!
public get(id: string) : Object {
const found: Object | undefined = this.repository.items.get(id)
if (found !== undefined) {
return found
}
}