首页 > 解决方案 > 如何“说服” 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)可能是未定义的。但是我正在检查它是否不是之前的行。除了使用,我还能做什么!

标签: typescript

解决方案


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
    }
}

推荐阅读