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

如何编写使用localStorage的TypeScript函数?泛型实现报错求助

Issues with Your Generic localStorage TypeScript Function

Let’s walk through the problems in your setLocStor function and fix them up:

1. Unconstrained Key Type Breaks Type Safety

localStorage’s setItem method requires the key to be a string, but your generic T lets you pass any type (like a number, object, or boolean) without TypeScript complaining. While localStorage will silently convert non-string keys to strings at runtime, this is risky—you might accidentally pass a value that gets coerced into something unexpected (e.g., 123 becomes "123", but an object becomes "[object Object]").

You don’t need a generic for the key here—just explicitly type it as string to enforce correctness.

2. Non-String Values Get Stored as Useless Strings

The bigger problem is your value parameter: localStorage.setItem only accepts strings, but your generic U allows any type. If you pass an object, array, number, or boolean directly, localStorage will store its default string representation (like "[object Object]" for objects), which is impossible to convert back to the original value later.

You need to serialize the value to a JSON string using JSON.stringify() before storing it.

3. Redundant Generics

Using two generics (T for key, U for value) is unnecessary here. Since the key is always a string, you can simplify the function to use a single generic for the value type.

Fixed Version of the Function

Here’s how to rewrite it to address all these issues:

export const setLocStor = <T>(key: string, val: T): void => {
  try {
    // Serialize the value to a JSON string
    const serializedValue = JSON.stringify(val);
    localStorage.setItem(key, serializedValue);
  } catch (error) {
    // Handle cases where serialization fails (e.g., circular references)
    console.error("Failed to store value in localStorage:", error);
  }
};

Bonus: Corresponding Get Function

To make this useful, you’ll also want a function to retrieve and deserialize the value. Here’s that:

export const getLocStor = <T>(key: string): T | null => {
  try {
    const storedValue = localStorage.getItem(key);
    if (storedValue === null) return null;
    // Parse the JSON string back to the original type
    return JSON.parse(storedValue) as T;
  } catch (error) {
    console.error("Failed to retrieve value from localStorage:", error);
    return null;
  }
};

Why This Works

  • The key is explicitly typed as string to enforce type safety.
  • The generic T defines the type of the value you’re storing, so TypeScript will check that you’re passing a valid value (and help with autocompletion when retrieving it).
  • Serializing/deserializing with JSON ensures non-string types are stored correctly and can be retrieved in their original form.
  • The try/catch blocks handle edge cases like circular references in objects, which would break JSON.stringify.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:09:00