Home > Net >  How can I define the object type in a returned pipe(map(...)) statement?
How can I define the object type in a returned pipe(map(...)) statement?

Time:10-06

I started developing an app in Angular Ionic Framework.

My problem is that I don't know how to define the type on a returned object to be able to retrieve specific attributes.

I think this is a common problem but I couldn't find the proper results using google.

When I try to return my authentication token from device storage, which looks something like

{
   key:'authData',
   value: token
}

I am not able to compile as my value attribute is not known on the returned storedData field.

error TS2339: Property 'value' does not exist on type 'unknown'.

return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
  if (!storedData || !storedData.value) {
    return null;
  }
  const parsedData = JSON.parse(storedData.value)
}

So I am looking for some type to define the interface type on the storedData object. Kind regards!

CodePudding user response:

You must declare a model in the top of your file

interface StoredData {
   key: string;
   value: string;
}

And then later in your code:

return from(Storage.get({ key: 'authData' })).pipe(map(storedData: StoredData => {
  if (!storedData || !storedData.value) {
    return null;
  }
  const parsedData = JSON.parse(storedData.value)
 }

Alternatively you can cheat the linter with:

return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
  if (!storedData || !storedData['value']) {
    return null;
  }
  const parsedData = JSON.parse(storedData['value'])
 }
  • Related