【问题标题】:Typescript: Property 'set' does not exist on type '{}'.ts打字稿:类型'{}'.ts 上不存在属性'set'
【发布时间】:2022-01-30 22:44:42
【问题描述】:

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

我的代码工作正常,但我不希望出现任何错误。

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

【问题讨论】:

  • 不要分配 globalstore 的属性。内联声明它们
  • @DanielA.White 怎么样?你能帮我更多吗?

标签: javascript reactjs typescript next.js


【解决方案1】:

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

所以你需要将里面的函数声明为对象,以便打字稿可以推断出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;
}

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

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

export default GlobalStore;

【讨论】:

  • @RezMohsnei 是的!请再次阅读该帖子,我(出于某种原因)没有意识到您实际上并不需要实例。我现在更新了答案,所以第一种方法也有意义:)
猜你喜欢
  • 2018-11-30
  • 2017-03-02
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2017-03-26
  • 2017-09-06
  • 2020-05-21
相关资源
最近更新 更多