New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use ContextKey<T> to type setContext, getContext and hasContext #8941
Comments
Maybe just call it |
@dummdidumm i just checked that adding a new function signature to |
You can add below snippet to type Context = {
theme: Writable<string | null>; // for example
};
declare module 'svelte' {
export function getContext<T>(key: T extends keyof Context ? T : never): Context[T];
export function setContext<T>(
key: T extends keyof Context ? T : never,
context: Context[T],
): void;
} |
To extend the ideas mentioned above, my preferred declare module "svelte" {
export interface ContextKey<T = unknown> {} // eslint-disable-line @typescript-eslint/no-unused-vars
export function getContext<T>(key: ContextKey<T>): T;
export function setContext<T>(key: ContextKey<T>, value: T): void;
export function hasContext<T>(key: ContextKey<T>): boolean;
} Then you can define your key as simply as: export const TabContext: ContextKey<Tab[]> = {}; |
The only real issue with the solution above, is that setContext(MyContextKey, { /* Typescript won't autocomplete this */ }); Anyone know of a way to override instead of extend? |
…text` Not completly ideal because you can circumvent the type safety by doing `getContext<SomeType>(context_key)` - changing this would require a breaking change, which we could do in Svelte 6 after we've given `ContextKey` some time to establish itself. Also doesn't add the interesting type narrowing idea in https://github.com/KamenKolev/svelte-typed-context/blob/master/index.ts#L14 (yet), probably easier to do together with said breaking change. closes #8941
i also tried the approaches above but cant get autocompletion on the value of set context, only on the key declare module 'svelte' {
export function getContext<T extends keyof Context, K extends Context[T]>(key: T): K;
export function setContext<T extends keyof Context, K extends Context[T]>(
key: T,
context: K
): void;
} |
Describe the problem
Currently
getContext
returnsunknown
if no explicit type is provided.Describe the proposed solution
Taking inspiration from
svelte-typed-context
,getContext
can accept anInjectionKey<T>
ContextKey<T>
and returnT
:This will improve type safety
and can be done in a backwards compatible way.The implementation would be just to add a new signature to
getContext
,setContext
andhasContext
Alternatives considered
Importance
nice to have
Search terms
typed context inject provide
The text was updated successfully, but these errors were encountered: