typescriptlocalforage

localForage type is unkown


const AddMovieToDashboardFn = (movie) => {
  localForage.getItem('my array').then((value) => {
    const x: string[] = value;
    console.log(x)
  });
}

const x has a syntax error:

Type 'unknown' is not assignable to type 'string[]'.

The value parameter in the then callback is of type unknown so the error makes sense. If I like the value it shows an array. How do I give the value in the then callback a type, should be type array.


Solution

  • Try this:

    const AddMovieToDashboardFn = (movie) => {
      localForage.getItem('my array').then((value: string[]) => {
        const x = value;
        console.log(x)
      });
    }
    
    

    Or, since the typing for localforage allows passing a type parameter (https://github.com/localForage/localForage/blob/master/typings/localforage.d.ts):

    const AddMovieToDashboardFn = (movie) => {
      localForage.getItem<string[]>('my array').then((value) => {
        const x = value;
        console.log(x)
      });
    }
    
    

    (Credit to @Elias Schablowski for suggesting this in the comments)