0

I have a problem with TypeScript and Immutable. My code is as follows:

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.`);
  }
}

In here I am getting an error saying that this.repository.items.get(id) may be undefined. But the line before I am checking whether it is not. What can I do, apart from using !?

Tomek Buszewski
  • 6,696
  • 8
  • 58
  • 103

1 Answers1

0

You can check for undefined using if (found) { ... } or if(found !== undefined) { ... } and then you have to return found since that is the object you checked!

public get(id: string) : Object {

    const found: Object | undefined = this.repository.items.get(id)

    if (found !== undefined) {
      return found
    }
}
Kokodoko
  • 19,176
  • 21
  • 88
  • 153
  • Checking `typeof undefined` is safer than just `is undefined`. But actually yeah, that was my problem, I should just return `found` rather than performing the actual lookup again, thanks! – Tomek Buszewski Jul 12 '19 at 09:12
  • And you had quotes around `"undefined"` :). BTW by using `if (found)` you also check for `null` and `""` so maybe that's even safer. – Kokodoko Jul 12 '19 at 09:14
  • Here's a nice thread about using `typeof undefined`: https://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined – Tomek Buszewski Jul 12 '19 at 09:38
  • Thanks! I didn't realise that technique existed! It seems safer for global variables that may or may not exist outside of your control. But in your case, you created the class yourself. So you know that `found` is either `Object` or `undefined`. This is because the `map.get` will return `undefined` if the key does not exist. So you can safely use `if(found)`. – Kokodoko Jul 12 '19 at 12:12