You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用映射类型实现TypeScript类型安全的基础JSON存储?

TypeScript JSON存储泛型类型不兼容问题解决方案

问题根源

你遇到的类型错误核心在于MyStorageManager.getStore方法的参数类型定义偏差:方法要求传入的defaultData是Record<string, T>类型(即键为字符串、值为T的键值对对象),但你实际传入的defaultData本身就是T类型({ test: null; astring: string; }),两者类型不匹配导致报错。

解决方案

1. 修正方法参数类型

将getStore方法中defaultData的类型从Record<string, T>改为T,让方法正确接收你要存储的目标对象类型:

class MyStorageManager {
  getStore<T>(key: string, defaultData: T): T {
    const storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) as T : defaultData;
  }
}

2. 正常调用验证

修正后直接传入你的默认数据即可,TypeScript会自动推断T的类型,不再报错:

const defaultData = { test: null, astring: "example" };
const manager = new MyStorageManager();
const myStore = manager.getStore("my-storage-key", defaultData);
// myStore的类型会被正确推断为{ test: null; astring: string; }

额外说明

如果你的设计初衷是存储多组键值对结构(比如多个T类型的对象),则需要调整传入的defaultData格式,示例如下:

type StoreItem = { test: null; astring: string; };
const defaultData: Record<string, StoreItem> = {
  "item1": { test: null, astring: "foo" },
  "item2": { test: null, astring: "bar" }
};

但从你的错误信息判断,你实际需求是存储单个对象,因此第一种修正方式更匹配你的场景。

内容的提问来源于stack exchange,提问作者Rivenscryr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:17:40