Skip to content
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

Support for typed contexts #10418

Closed
stefanhoelzl opened this issue Feb 6, 2024 · 1 comment
Closed

Support for typed contexts #10418

stefanhoelzl opened this issue Feb 6, 2024 · 1 comment

Comments

@stefanhoelzl
Copy link

Describe the problem

Currently values shared with getContext/setContext are losing their type information.

If have a simple proposal to share the types getween getContext and setContext via the used key.
So that the value returned by getContext for a certain key has the same type as the value provided with setContext for this key.

I am also willing to work on a pull request for this feature, if there is interest to have it in svelte.

Describe the proposed solution

Here is my proposed solution for the interface (similiar to vues provide/inject)

// svelte patch
import { getContext as origGetContext, setContext as origSetContext } from "svelte";

class ContextKey<T> {}
function getContext<T>(key: ContextKey<T>): T {
  return origGetContext(key);
}
function setContext<T>(key: ContextKey<T>, value: T) {
  origSetContext(key, value);
}

// define available context keys in own module
const keyA = new ContextKey<number>();

// use setContext/getContext with typing
setContext(keyA, 100); // ok
setContext(keyA, "FOOBAR"); // ts error

const n: number = getContext(keyA); // ok
const s: string = getContext(keyA); // ts error

Importance

would make my life easier

@dummdidumm
Copy link
Member

Closing as duplicate of #8941

@dummdidumm dummdidumm closed this as not planned Won't fix, can't repro, duplicate, stale Feb 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants