解决TypeScript更新后local-storage.get方法报错问题
Let's break down what's happening here. After updating your dependencies, the type definitions for local-storage have shifted in a key way that's triggering this error.
Looking at the type file you shared:
declare module "local-storage" {
export function set(key: string, value: T): boolean;
export function get(key: string): T;
// ... other methods
export default function(key: string, value?: T): void;
}
The core issue is how you're importing the module. You're using the default export (import ls from 'local-storage'), but that default export is just a single function (likely a shortcut for setting values, given its signature). The get method isn't a property of this default function—it's a separate named export that lives outside of it.
Here are two straightforward fixes:
1. Use named imports for specific methods
Instead of importing the default export, pull in only the methods you need directly:
import { set, get } from 'local-storage'; set('userInfo', user); const userInfo = get('userInfo');
This is the cleanest approach if you only rely on a handful of the library's methods.
2. Import the entire module as a namespace
If you prefer keeping the ls prefix for consistency, import all exports under a single namespace object:
import * as ls from 'local-storage'; ls.set('userInfo', user); const userInfo = ls.get('userInfo');
This works because * as ls captures all named exports (including set, get, remove, etc.) into one object, which matches how you were using the default export before the dependency update.
Why this worked previously
Older versions of the local-storage type definitions probably had the default export as an object containing all the library's methods, letting you call ls.get() directly. The update changed this to make the default export a standalone setter function, while the full API remains accessible via named exports.
内容的提问来源于stack exchange,提问作者Pete

