Home > database >  Helper function throwing error in TypeScript
Helper function throwing error in TypeScript

Time:11-10


let storage = {};

storage.saveCredentials = (token:any, id:any) => {
    localStorage.setItem('token', token);
    localStorage.setItem('userId', id);
}

storage.saveStatus = (status:any) => {
    localStorage.setItem('status', JSON.stringify(status));
}


export default storage;

I get the error that Property 'saveCredentials' does not exist on type '{}'.

CodePudding user response:

TypeScript determines the type of storage at declaration, so storage has just the type of an empty object without any members. You should add the functions directly when you create the object:

const storage = {
    saveCredentials: (token:any, id:any) => {
        localStorage.setItem('token', token);
        localStorage.setItem('userId', id);
    },
    saveStatus: (status:any) => {
         localStorage.setItem('status', JSON.stringify(status));
    }
}

export default storage;

If you want to add members dynamically at runtime, declare storage as any:

let storage: any = {}

But you will loose the type safety then.

CodePudding user response:

It is better to create function and export it.

const saveCredentials = (token: any, id: any) => {
  localStorage.setItem('token', token);
  localStorage.setItem('userId', id);
};

const saveStatus = (status: any) => {
  localStorage.setItem('status', JSON.stringify(status));
};

export { saveCredentials, saveStatus };

use it like this

import { saveCredentials, saveStatus } from './storage';
  • Related