【问题标题】:Angular unit testing the localstorage, Error ts(7053)角度单元测试本地存储,错误 ts(7053)
【发布时间】:2022-01-07 18:00:42
【问题描述】:

beforeEach (() => { ...

   let store = {};
  const mockSessionStorage = {
  getItem: (key: string): string => key in store ? store[key] : null,
  setItem: (key: string, value: string) => store[key] = `${value}`,
  removeItem: (key: string) => delete store[key],
  clear: () => store = {}
};
...

并且我收到错误消息元素隐式具有类型“any”,因为类型“string”的表达式不能用于索引类型“{}”。 没有为类型“{}”.ts(7053)

找到具有“字符串”类型参数的索引签名

另外我是typscript的新手,不知道是因为错误消息还是我做错了什么,如果有人可以快速浏览一下,我会很高兴。

【问题讨论】:

    标签: javascript angular unit-testing karma-jasmine


    【解决方案1】:

    尝试输入您的 store 变量。

    类似这样的:

    let store:{ [key: string]: string } = {};
    

    【讨论】:

    • 如果我让 store:{ [key: string]: string } = {};所以我在 getItem 得到类型字符串 | 的消息。不能将 null 分配给类型字符串 ts(2322)。为了解决这个问题,我将类型字符串更改为任何类型。所以让 store:{ [key: string]: any} = {};。错误消息现在消失了,但我的解决方法是否正确?
    • 我猜你的解决方案没问题,但先试试这个更改:let store:{ [key: string]: string|null} = {};
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多