繁体   English   中英

Typescript:类型“{}”.ts 上不存在属性“set”

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

这是我的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;

我使用它:

import globalStore from './library/store';

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

但我得到这个错误:

类型“{}”.ts 上不存在属性“set”

我的代码工作正常,但我不想得到任何错误。

实际上,我想将我的数据存储到变量中并从另一个组件中使用它。

好吧,您基本上将变量的类型声明为{} ,事后您不能轻易更改它。

所以你需要将里面的函数声明为 object 以便 typescript 可以推断出正确的GlobalStore类型(使用方法):

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;

GlobalStore的正确类型是(与您当前拥有的{}相反):

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

顺便说一句,您正在实施的基本上是(哈希) Map ,所以我认为您可以这样做:

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

export default GlobalStore;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM