Jordan
Jordan

Reputation: 9901

How do I add a property to window and make it globally available?

In my code below, I cannot remove window from globalStorage or I get the error:

"cannot find name 'globalStorage'. Did you mean 'GlobalStorage'?"

Is there not a way to add properties to Window and make them available in the global scope without having to reference window? I'm trying to make this work like localStorage and sessionStorage. Having to include window makes it less appealing.

declare global {
    interface Window { globalStorage: GlobalStorage; }
}

window.globalStorage = new GlobalStorage();

export function loadGlobal<TData>(key: string, defaultValue: TData): TData;
export function loadGlobal<TData>(key: string): TData | undefined;
export function loadGlobal<TData>(key: string, defaultValue?: TData) {
    return load(window.globalStorage, key, defaultValue);
}

export function saveGlobal<TData>(key: string, data: TData) {
   return save(window.globalStorage, key, data);
}

export function hasKeyGlobal(key: string) {
    return hasKey(window.globalStorage, key);
}

Upvotes: 0

Views: 1100

Answers (1)

SalientBrain
SalientBrain

Reputation: 2541

Just put your properties inside global namespace to extend globalThis:

declare global {     
    let foo: string; 
    let bar: number;
    globalStorage:  GlobalStorage;
}

Upvotes: 1

Related Questions