Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Property 'set' does not exist on type '{}'.ts

This is my store.tsx:

let store = {};

const globalStore = {};

globalStore.set = (key: string, value: string) => {
    store = { ...store, [key]: value };
}

globalStore.get = (key) => {
    return store[key];
}

export default globalStore;

And I use it:

import globalStore from './library/store';

function MyApp({ Component, pageProps }: AppProps) {
    globalStore.set('cookie', pageProps.cookies);
    return <Component {...pageProps} />
}

But I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Property ‘set’ does not exist on type ‘{}’.ts

My code work fine, but I don’t want get any error.

Actually, I want to store my data to variable and use it from another component.

>Solution :

Well you basically declared the type of the variable as {}, and you can’t easily change that after the fact.

So you need to declare the functions inside to object so typescript can infer the correct type of GlobalStore (with the methods):

const store: Record<string, string> = {};

const GlobalStore = {
    set: (key: string, value: string) => {
        store[key] = value;
    },
    get: (key: string): string => {
        return store[key];
    }
}

export default GlobalStore;

The correct type of GlobalStore would be (in opposition to the {} you currently have):

interface GloabStore {
    set(key: string, value: string): void;
    get(key: string): string;
}

And btw, what you are implementing is basically a (Hash)Map, so I think you could just do:

const GlobalStore = new Map<string, string>();

export default GlobalStore;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading