Storage array problem with type


#1

Hi,

I want to store an array of object called edition

export class Edition {
title:string;
author:string;
summary:string;

constructor...
}

i use the storage https://ionicframework.com/docs/storage/

So in my code i have

editions is an array of Editions, declared as

 editions: Edition[];

When i want to store i use this method

console.log(this.editions);
this.storage.set("editions", this.editions);

In another function i want to read it later so i wrote this:

this.storage.get("editions").then( (value) => {
   editions: Edition[];
   if(value)
       editions = value;
   console.log(editons);
});

When i look the console. before the set, types in array are Edition objects but in the get they are Object objects. So when later i want to use in a indexOf to find if a certain value exist it fails.

How can i have the right type during the get Process.
(I have also tried using JSON.stringify and JSON.parse function but i have the same result)


#2

.set() and .get() argument isn’t the same key, is that normal?
(book and edition)


#3

my bad i have changed it in one part and not in another during the post. In my code it’s the exact same key.


#4

You can’t. JavaScript doesn’t really have any OO functionality - it is all smoke and mirrors. Hence I recommend using interfaces to store data, moving all fancy logic that you may have in your data object class into a service provider instead.


#5

It is possible to do, there is an npm package that can do it: https://www.npmjs.com/package/serializer.ts

Depending on your needs there are other ways like having the constructor take in the object and set properties, then you could loop through your raw object and construct models from them.

As rapropros says you could also use interfaces if you only care about type checking and not having methods on the models.


#6

For more on my rationale for keeping methods away from models, see this post.