Search code examples
angulartypescriptangular-router

How do I parse a field from the route paramMap and return it as an object?


In my component, I have this function:

  getData(): DataObj {
    const data = this.route.snapshot.paramMap.get('data');
    const obj = JSON.parse(data) as DataObj
    return obj;
  }

but the line

    const obj = JSON.parse(data) as DataObj

gives the compilation error

Type 'null' is not assignable to type 'string'

complaining about "data". What's the proper way in strict mode to parse and then return my object?

I'm using Angular 14.


Solution

  • As far as I can tell, Type narrowing should be your friend here.

    Deal with null earlier, to get type narrowing working.

    So, your code should look something like this:

      getData(): DataObj {
        const data = this.route.snapshot.paramMap.get('data');
        if (data === null) return null; // you can return whatever you like
        const obj = JSON.parse(data) as DataObj; // now this line should not complain about `null`
        return obj;
      }