Created
April 7, 2023 10:37
-
-
Save bryanmylee/47280734c7835409ed7fd99349c71e8a to your computer and use it in GitHub Desktop.
Svelte type-safe context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {getContext, setContext} from 'svelte'; | |
interface Context<TValue> { | |
get: () => TValue | null; | |
set: (currentValue: TValue) => void; | |
} | |
/** | |
* Allow strongly typed Svelte context getters and setters while using a unique | |
* Symbol instead of a string key to avoid any potential key conflicts. | |
* @param keyDescription A descriptor for the context key. | |
* @returns A get and set context function that is intrinsically tied. | |
*/ | |
export function createContext<TValue>(keyDescription?: string): Context<TValue> { | |
const key = Symbol(keyDescription); | |
return { | |
get: () => { | |
const value = getContext(key); | |
if (value == null) { | |
console.warn(`context.get(${key.toString()}) called without context.set in parent scope`); | |
} | |
return (value ?? null) as TValue | null; | |
}, | |
set: (currentValue: TValue) => setContext(key, currentValue), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment