TypeScript报错:类型'{}'上不存在属性'set'——自定义全局Store的类型问题解决问询
Let's break down why you're seeing this error and how to fix it properly while keeping your global store functionality intact.
The Root Cause
TypeScript infers the type of globalStore as {} (an empty object) when you initialize it that way. Even though you add set and get methods afterward, TypeScript's static type checking doesn't recognize these additions—so it throws an error when you try to access globalStore.set or globalStore.get elsewhere.
Solution 1: Define a Type Interface for the Store
The cleanest way is to explicitly define a type that describes your store's methods, then apply that type to your globalStore variable.
Here's how to update your store.tsx:
// Define the interface for our global store interface GlobalStore { set: (key: string, value: any) => void; get: (key: string) => any; } let store: Record<string, any> = {}; // Initialize globalStore with the correct type const globalStore: GlobalStore = { set: (key: string, value: any) => { store = { ...store, [key]: value }; }, get: (key: string) => { return store[key]; } }; export default globalStore;
Solution 2: Use Type Assertion (Quick Fix)
If you want a quicker adjustment without defining a full interface, you can use a type assertion to tell TypeScript what globalStore will eventually look like:
let store = {}; const globalStore = {} as { set: (key: string, value: string) => void; get: (key: string) => string | undefined; }; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export default globalStore;
Solution 3: Implement with a Class (More Scalable)
For a more maintainable and scalable approach, consider using a class to encapsulate your store logic. TypeScript works seamlessly with classes and their types:
class GlobalStore { private store: Record<string, any> = {}; set(key: string, value: any): void { this.store = { ...this.store, [key]: value }; } get(key: string): any { return this.store[key]; } } // Export a singleton instance so all components use the same store const globalStore = new GlobalStore(); export default globalStore;
Verify the Fix
After updating your store.tsx, your component code will work without TypeScript errors:
import globalStore from './library/store'; function MyApp({ Component, pageProps }: AppProps) { globalStore.set('cookie', pageProps.cookies); return <Component {...pageProps} />; }
All three solutions will eliminate the "Property 'set' does not exist on type '{}'" error while keeping your global store functionality working as expected. The class-based approach is especially recommended if you plan to add more methods or logic to your store later.
内容的提问来源于stack exchange,提问作者Rez Mohsnei

